@massimo-cassandro/minimo 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dev-tools/README.md +1 -1
  2. package/dev-tools/update-version/index.mjs +1 -1
  3. package/dev-tools/update-version/src/chooser-inquirer.mjs +1 -1
  4. package/dev-tools/webpack-setup/starter-install.sh +149 -0
  5. package/dev-tools/webpack-setup/templates/__project__.code-workspace +93 -0
  6. package/dev-tools/webpack-setup/templates/_browserslistrc +27 -0
  7. package/dev-tools/webpack-setup/templates/_editorconfig +17 -0
  8. package/dev-tools/webpack-setup/templates/_gitignore +21 -0
  9. package/dev-tools/webpack-setup/templates/_prettierrc +9 -0
  10. package/dev-tools/webpack-setup/templates/eslint.config.mjs +31 -0
  11. package/dev-tools/webpack-setup/templates/jsconfig.json +22 -0
  12. package/dev-tools/webpack-setup/templates/package-tpl.json +37 -0
  13. package/dev-tools/webpack-setup/templates/stylelint.config.mjs +32 -0
  14. package/dev-tools/webpack-setup/webpack-modules/css-rules.mjs +177 -0
  15. package/dev-tools/webpack-setup/webpack-modules/get-jsConfig-aliases.mjs +33 -0
  16. package/dev-tools/webpack-setup/webpack-modules/postcss.config.mjs +77 -0
  17. package/dev-tools/webpack-setup/webpack-modules/svg-rules.mjs +154 -0
  18. package/dev-tools/webpack-setup/webpack-modules/svgo.config.mjs +26 -0
  19. package/dev-tools/webpack-setup/webpack-template.ejs +20 -0
  20. package/dev-tools/webpack-setup/webpack.config.mjs +585 -0
  21. package/package.json +6 -3
  22. package/snippets/ImgViewerController.php +403 -0
  23. package/snippets/UnsplashController.php +74 -0
  24. package/snippets/controllo-codice-fiscale-IT.js +48 -0
  25. package/snippets/controllo-partita-iva-IT.js +32 -0
  26. package/snippets/email-antispam.js +108 -0
  27. package/snippets/error-pages/bundles/TwigBundle/Exception/error.html.twig +33 -0
  28. package/snippets/error-pages/error-pages.js +37 -0
  29. package/snippets/festivita.js +101 -0
  30. package/snippets/minimo-form-layout.html.twig +446 -0
  31. package/src/components/form-reset-submit.js +1 -1
  32. package/src/utilities/better-text.js +39 -30
@@ -0,0 +1,403 @@
1
+ <?php
2
+
3
+ namespace App\Controller;
4
+
5
+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6
+ use Symfony\Component\Routing\Annotation\Route;
7
+ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
8
+ use Symfony\Component\HttpFoundation\Request;
9
+ use Symfony\Component\HttpFoundation\Response;
10
+ use Symfony\Component\HttpFoundation\BinaryFileResponse;
11
+ use Symfony\Component\HttpFoundation\JsonResponse;
12
+
13
+
14
+
15
+ class ImgViewerController extends AbstractController
16
+ {
17
+ /**
18
+ *
19
+ * @param src: (string) path immagine
20
+ * @param raw: (bool) nessuna eleborazione (no image magick)
21
+ * @param crop: ritaglia l'immagine originale (prima dell'eventuale ridimensionamento con bb)
22
+ * secondo i parametri forniti: x,y (origine immagine), w,h (dimensioni ritaglio)
23
+ * es: crop=10,10,100,100 -> ritaglia un quadrato di 100px a partire dal punto 10,10
24
+ * @param bb: bounding box dell'area che deve contenere l'immagine ridimensionata
25
+ * @param fd: (bool) forza dimensioni (utilizzato in coppia con bb)
26
+ * @param q: compression quality
27
+ * @param alpha: mantiene la trasparenza nelle png (default 0)
28
+ * @param bg: in combinazione con alpha=1 definisce il bg color della png
29
+ * @param refresh: (bool) forza la rigenerazione dell'immagine
30
+ * @param f: definisce il formato dell'immagine, secondo le chiavi di ALLOWED_FORMATS
31
+ * il valore 'auto' (default) imposta il formato migliore secondo i valori in PREFERRED_AUTO_FORMATS
32
+ * @param ext: lascia inalterato il formato dell'immagine
33
+ * @param d: (bool) forza il download dell'immagine
34
+ */
35
+
36
+ // parametri get del viewer accettati
37
+ const ALLOWED_PARAMS = array('raw', 'bb', 'fd', 'q', 'alpha', 'bg', 'refresh', 'f', 'ext', 'd', 'crop');
38
+ // formati output
39
+ const ALLOWED_FORMATS = array(
40
+ 'avif' => 'image/avif',
41
+ 'pjpeg' => 'image/pjpeg',
42
+ 'jpeg' => 'image/jpeg',
43
+ 'jpg' => 'image/jpeg',
44
+ 'png' => 'image/png',
45
+ 'gif' => 'image/gif',
46
+ 'webp' => 'image/webp',
47
+ 'ico' => 'image/vnd.microsoft.icon'
48
+ );
49
+
50
+ // formati preferiti per la scelta automatica in ordine di preferenza
51
+ // in loro mancanza il formato prefefinito è jpeg
52
+ // (NB: devono essere uguali alle chiavi di ALLOWED_FORMATS)
53
+ const PREFERRED_AUTO_FORMATS = ['avif', 'webp'];
54
+
55
+ // formati input accettati da Imagick (in aggiunta a quelli definiti in ALLOWED_FORMATS)
56
+ const ALLOWED_INPUT = ['bmp', 'tiff', 'tif'];
57
+
58
+ // parametro compression quality di default
59
+ const DEFAULT_COMPRESSION_QUALITY = 60;
60
+
61
+ // src -> percorso assoluto dentro la dir public con gli slash
62
+ #[Route(path: '/iviewer', name: 'img_viewer')]
63
+ public function indexAction(Request $request)
64
+ {
65
+
66
+
67
+ $get = $request->query->all();
68
+ $src = $get['src'];
69
+
70
+ if (!$src)
71
+ throw $this->createNotFoundException('Parametro mancante! (src)');
72
+
73
+ // formati supportati dall'istanza imageMagick
74
+ $supported_formats = array_map("strtolower", \imagick::queryFormats());
75
+
76
+ // formati accettati dal browser
77
+ $accept = $request->server->get('HTTP_ACCEPT');
78
+
79
+ // format 'auto' default
80
+ if(!isset($get['f'])) $get['f'] = 'auto';
81
+
82
+ // format 'auto' -> sceglie il formato migliore per il browser, se disponibile
83
+ if(isset($get['f']) && strtolower($get['f']) == 'auto') {
84
+
85
+ foreach(self::PREFERRED_AUTO_FORMATS as $f) {
86
+ if(strpos($accept, self::ALLOWED_FORMATS[$f]) !== false &&
87
+ in_array($f, array_keys(self::ALLOWED_FORMATS)) &&
88
+ in_array($f, $supported_formats)
89
+ ) {
90
+ $get['f']=$f;
91
+ break;
92
+ }
93
+ }
94
+ }
95
+
96
+
97
+ // durata della cache dei file: 7gg
98
+ $cache_lifetime = 604800;
99
+
100
+ $params = $this->cleanParams($get);
101
+
102
+ $cache_params_str = "";
103
+
104
+ // parte del nome file del cache formata da tutti i parametri concatenati tra loro
105
+ foreach ($params as $kg => $g) {
106
+ if ($kg != 'refresh' && $kg != 'raw')
107
+ $cache_params_str .= '_' . $kg . $g;
108
+ }
109
+ $cache_params_str = str_replace(',', '_', $cache_params_str);
110
+
111
+
112
+ $publicPath = $this->getParameter('kernel.project_dir') . '/public';
113
+ $filePath = $publicPath . $src;
114
+
115
+ $fileExt = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
116
+ // $fileBasename = strtolower(pathinfo($filePath, PATHINFO_BASENAME));
117
+ // $fileCacheName = $fileBasename; // porzione inziale del nome del file di cache
118
+ $fileCacheName = str_replace('/', '_', $src); // porzione inziale del nome del file di cache
119
+
120
+
121
+ if (isset($params['d'])) {
122
+ $disposition = 'attachment';
123
+ } else {
124
+ $disposition = 'inline';
125
+ }
126
+
127
+
128
+ // elaborazione immagine: se sono presenti parametri, non è settato raw ed è un formato trattabile da imagick
129
+ if (count($params) && !isset($params['raw']) && in_array($fileExt, array_merge(self::ALLOWED_INPUT, array_keys(self::ALLOWED_FORMATS)))) {
130
+
131
+ // se è richiesto un formato deve essere tra quelli permessi
132
+ if (isset($params['f']) &&
133
+ in_array($params['f'], array_keys(self::ALLOWED_FORMATS)) &&
134
+ in_array($params['f'], $supported_formats)
135
+ ) {
136
+
137
+ $format = $params['f'];
138
+
139
+ // se è presente il parametro ext ed è tra quelli permessi
140
+ } else if (isset($params['ext']) && $params['ext'] && in_array(strtolower($fileExt), array_keys(self::ALLOWED_FORMATS))) {
141
+
142
+ $format = strtolower($fileExt);
143
+
144
+ // formato predefinito in assenza di altre impostazioni
145
+ } else {
146
+ $format = 'jpeg';
147
+ }
148
+
149
+ $fileCacheName = $fileCacheName . $cache_params_str . '.' . ($format == 'pjpeg' ? 'jpeg' : $format);
150
+
151
+ $cachefile = $this->getParameter('cache_dir') . $fileCacheName;
152
+
153
+ // definizione della qualità della compressione dell'immagine
154
+ $compressionQuality = !empty($params['q']) ? intval($params['q']) : self::DEFAULT_COMPRESSION_QUALITY;
155
+
156
+
157
+ // elaborazione con imagick per i seguenti casi:
158
+ // 1) non esiste il file nella cartella cache
159
+ // 2) la cache è scaduta
160
+ // 3) è richiesto il refresh
161
+ if (!file_exists($cachefile) || (filemtime($cachefile) + $cache_lifetime) < time() || isset($params['refresh'])) {
162
+
163
+ // inizializzazione imagick
164
+ $img = new \Imagick();
165
+ $img->readImage($filePath);
166
+
167
+ $img->stripImage(); // Strips an image of all profiles and comments
168
+
169
+ if(isset($params['crop']) or isset($params['bb'])) {
170
+ // dimensioni originali
171
+ $ow = $img->getImageWidth();
172
+ $oh = $img->getImageHeight();
173
+ }
174
+
175
+
176
+ if(isset($params['crop'])) {
177
+ $crop_params = array_map( fn($val) => intval(trim($val)), explode(',', $params['crop']));
178
+
179
+ // devono essere presenti tutti e 4 i parametri e devono essere maggiori di zero
180
+ if(count($crop_params) != 4 or min($crop_params) < 0) {
181
+ throw $this->createNotFoundException('Errore di configurazione! (crop 1)');
182
+ }
183
+
184
+ [$x,$y,$crop_w,$crop_h] = $crop_params;
185
+
186
+ // l'area ritagliata non può essere più grande dell'immagine
187
+ if($x + $crop_w > $ow or $y + $crop_h > $oh) {
188
+ throw $this->createNotFoundException('Errore di configurazione! (crop 2)');
189
+ }
190
+
191
+ $img->cropImage($crop_w, $crop_h, $x, $y);
192
+
193
+ // nuove dimensioni dell'immagine (corrispondono a $crop_w e $crop_h)
194
+ $ow = $img->getImageWidth();
195
+ $oh = $img->getImageHeight();
196
+ }
197
+
198
+ if (isset($params['bb'])) {
199
+ $bb_param = strtolower($params['bb']);
200
+ $bb_has_x = strpos($bb_param, 'x') !== false;
201
+
202
+ if ($bb_has_x) {
203
+ // dimensioni richieste
204
+ // se un parametro è mancante viene impostato a 0 e non ha influenza nelle elaborazioni successive
205
+ [$w, $h] = array_map( fn($val) => $val? (int)$val : 0, explode('x', $bb_param));
206
+
207
+ // le dimensioni richieste non possono superare quelle originali
208
+ if ($w > $ow) $w = $ow;
209
+ if ($h > $oh) $h = $oh;
210
+ }
211
+ }
212
+
213
+ // fd => l'immagine deve rispettare con precisione le dimensioni richieste
214
+ // è necessario che siano presenti entrambi i parametri bb
215
+ if (isset($params['bb']) && isset($params['fd']) && $bb_has_x && $w > 0 && $h > 0) {
216
+
217
+ if ($ow < $w && $oh < $h) {
218
+ $nb = $ow;
219
+ $nh = $oh;
220
+
221
+ if ($w > $h) {
222
+ $r = $h / $w;
223
+ } else {
224
+ $r = $w / $h;
225
+ }
226
+
227
+ if ($nb > $nh) {
228
+ $nh = $r * $nb;
229
+ } else {
230
+ $nb = $r * $nh;
231
+ }
232
+
233
+ $w = $nb;
234
+ $h = $nh;
235
+
236
+ }
237
+
238
+ $img->cropThumbnailImage($w, $h);
239
+ // $img->resizeImage($w, $h, \imagick::FILTER_GAUSSIAN, 0);
240
+
241
+ } elseif (isset($params['bb']) && $bb_has_x) {
242
+
243
+ if ($w != 0 || $h != 0) {
244
+ $nb = $ow;
245
+ $nh = $oh;
246
+ if ($w != 0 && $w < $nb) {
247
+ $nh = ($w / $nb) * $nh;
248
+ $nb = $w;
249
+ }
250
+
251
+ if ($h != 0 && $h < $nh) {
252
+ $nb = ($h / $nh) * $nb;
253
+ $nh = $h;
254
+ }
255
+
256
+ $w = $nb;
257
+ $h = $nh;
258
+ }
259
+ $img->thumbnailImage($w, $h, true);
260
+ // $img->resizeImage($w, $h, \imagick::FILTER_GAUSSIAN, 0);
261
+ }
262
+
263
+ // compressione immagine
264
+ if ($compressionQuality) {
265
+ $img->setImageCompressionQuality($compressionQuality);
266
+ }
267
+ //$img->setImageAlphaChannel(\imagick::COMPOSITE_CLEAR);
268
+ //$img->setBackgroundColor(new \ImagickPixel('white'));
269
+
270
+ // formato immagine
271
+
272
+ $img->setImageFormat($format);
273
+
274
+ // $mimeType = $img->getImageMimeType();
275
+ $mimeType = self::ALLOWED_FORMATS[$format];
276
+
277
+
278
+ /*if ($format == 'webp') {
279
+ // per i webp non posso recuperare direttamente il mime type con il metodo
280
+ $mimeType = 'image/webp';
281
+
282
+ //$img->setImageAlphaChannel(\imagick::COMPOSITE_CLEAR);
283
+ //$img->setBackgroundColor(new \ImagickPixel('transparent'));
284
+
285
+ } else if ($format == 'pjpeg') {
286
+ $mimeType = 'image/jpeg';
287
+
288
+ } else */
289
+
290
+ if ($format == 'ico') {
291
+ $img->setImageAlphaChannel(\imagick::COMPOSITE_CLEAR);
292
+ $img->setBackgroundColor(new \ImagickPixel('transparent'));
293
+ $img->cropThumbnailImage(16, 16);
294
+ // $mimeType = self::ALLOWED_FORMATS['ico']; //'image/vnd.microsoft.icon';
295
+
296
+ } else if ($format == 'png') {
297
+ $mimeType = 'png';
298
+ if (isset($params['alpha']) && isset($params['bg']) && preg_match('/[0-9a-f]{6}/i', $params['bg'])) {
299
+ $bgColor = '#' . $params['bg'];
300
+ // elimino la trasparenza
301
+ //$img->setImageAlphaChannel(\imagick::COMPOSITE_CLEAR);
302
+ $img->setImageBackgroundColor($bgColor);
303
+ $img = $img->flattenImages();
304
+
305
+ } else {
306
+ //$bgColor = '#ffffff';
307
+ //$img->setImageAlphaChannel(\imagick::COMPOSITE_CLEAR);
308
+ //$img->setBackgroundColor(new \ImagickPixel('transparent'));
309
+
310
+ $draw = new \ImagickDraw();
311
+ $draw->setStrokeAntialias(false);
312
+ $img->drawImage($draw);
313
+ }
314
+ }
315
+
316
+ $img->writeImage($cachefile);
317
+ $img->clear();
318
+ $img->destroy();
319
+
320
+ } else {
321
+
322
+ $mimeType = self::ALLOWED_FORMATS[$format];
323
+ }
324
+
325
+
326
+
327
+ // nessuna elaborazione richiesta: restituisce il file originale
328
+ } else {
329
+
330
+ $cachefile = $filePath;
331
+ // $fileCacheName = $fileBasename . '.' . $fileExt;
332
+ $fileCacheName = str_replace('/', '_', $src);
333
+
334
+ if ($fileExt == 'svg')
335
+ $mimeType = 'image/svg+xml';
336
+ }
337
+
338
+
339
+ $response = new BinaryFileResponse($cachefile);
340
+ $response->trustXSendfileTypeHeader();
341
+
342
+ if (isset($mimeType)) {
343
+ $response->headers->set('Content-Type', $mimeType);
344
+ }
345
+
346
+ $response->headers->set('Content-Disposition', $disposition . '; filename = ' . $fileCacheName);
347
+
348
+ return $response;
349
+
350
+ //return array();
351
+
352
+ }
353
+
354
+ protected function cleanParams($params) {
355
+
356
+ //compatibilità con vecchio parametro jq
357
+ // if(isset($params['jq']) && !isset($params['q'])) {
358
+ // $params['q'] = $params['jq'];
359
+ // }
360
+
361
+ // array_walk($params, create_function('&$val', '$val = trim($val);'));
362
+ // array_walk($params, function ($val): string {
363
+ // return trim($val);
364
+ // });
365
+
366
+
367
+ foreach ($params as $key => $value) {
368
+ if(!in_array($key, self::ALLOWED_PARAMS)) {
369
+ unset($params[$key]);
370
+ } else if($value) {
371
+ $params[$key] = trim($value);
372
+ }
373
+ }
374
+
375
+ if(isset($params['f'])) {
376
+ $params['f'] = strtolower($params['f']);
377
+ }
378
+
379
+ return $params;
380
+ }
381
+
382
+ // restituisce un json con le info dell'immagine indicata
383
+ #[Route(path: '/iviewer-info', name: 'img_viewer_info')]
384
+ public function iviewerInfo(Request $request)
385
+ {
386
+ $get = $request->query->all();
387
+ $src = $get['src'];
388
+
389
+ if (!$src)
390
+ throw $this->createNotFoundException('iviewer-info: Parametro mancante! (src)');
391
+
392
+ $publicPath = $this->getParameter('kernel.project_dir') . '/public';
393
+ $filePath = $publicPath . $src;
394
+
395
+ $img_info = getimagesize($filePath);
396
+
397
+ $response = new JsonResponse();
398
+ $response->setData($img_info);
399
+
400
+ return $response;
401
+
402
+ }
403
+ }
@@ -0,0 +1,74 @@
1
+ <?php
2
+
3
+ namespace App\Controller;
4
+
5
+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6
+ use Symfony\Component\Routing\Annotation\Route;
7
+ use Symfony\Component\HttpFoundation\Request;
8
+ use Symfony\Component\HttpFoundation\Response;
9
+
10
+ class UnsplashController extends AbstractController
11
+ {
12
+
13
+ #[Route('/get-unsplash', name: 'get_unsplash')]
14
+ public function get(Request $request)
15
+ {
16
+ // $get = $request->query->all();
17
+ // $src = $get['src'];
18
+ $orientation = $request->query->get('orientation', 'landscape'); // landscape, portrait, squarish, null
19
+
20
+ $allowed = ['landscape', 'portrait', 'squarish', null];
21
+ if (!in_array($orientation, $allowed)) {
22
+ $orientation = 'landscape';
23
+ }
24
+
25
+ $unsplash_access_key = 'xxxxxxx';
26
+ $collections_ids = '3660951'; // comma separated list
27
+ $count = null;
28
+
29
+ $url = 'https://api.unsplash.com/photos/random' .
30
+ "?client_id={$unsplash_access_key}" .
31
+ "&collections={$collections_ids}" .
32
+ ($orientation? "&orientation={$orientation}" : '') .
33
+ ($count != null? "&count={$count}" : '');
34
+
35
+ $json = file_get_contents($url);
36
+
37
+
38
+ $response = new Response();
39
+ $response->headers->set('Content-Type', 'application/json; charset=utf-8');
40
+ $response->setContent($json);
41
+
42
+ $env = $this->getParameter('kernel.environment');
43
+
44
+ return $response;
45
+
46
+ }
47
+
48
+ #[Route('/unsplash-browser', name: 'unsplash_browser')]
49
+ public function browse(Request $request)
50
+ {
51
+ $unsplash_access_key = 'xxxxxxx';
52
+
53
+ $get = $request->query->all();
54
+
55
+ $url = 'https://api.unsplash.com/search/photos' .
56
+ "?client_id={$unsplash_access_key}";
57
+
58
+ foreach($get as $key => $value) {
59
+ $url .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
60
+ }
61
+
62
+ $json = file_get_contents($url);
63
+
64
+ $response = new Response();
65
+ $response->headers->set('Content-Type', 'application/json; charset=utf-8');
66
+ $response->setContent($json);
67
+
68
+ $env = $this->getParameter('kernel.environment');
69
+
70
+ return $response;
71
+
72
+ }
73
+
74
+ }
@@ -0,0 +1,48 @@
1
+ // basato sulla classe `CodiceFiscale` di Umberto Salsi <salsi@icosaedro.it>
2
+ // http://www.icosaedro.it/cf-pi/index.html
3
+
4
+ import {controllo_partita_iva} from './controllo-partita-iva-IT.js';
5
+
6
+ export function controllo_codice_fiscale(cf) {
7
+
8
+ cf = cf.replace(/\s/g, '').toUpperCase();
9
+
10
+
11
+ const controllo_cf = cf => {
12
+ if( ! /^[0-9A-Z]{16}$/.test(cf) )
13
+ return false;
14
+
15
+ var s = 0;
16
+ var even_map = 'BAFHJNPRTVCESULDGIMOQKWZYX';
17
+ for(var i = 0; i < 15; i++){
18
+ var c = cf[i];
19
+ var n = 0;
20
+ if( '0' <= c && c <= '9' ) {
21
+ n = c.charCodeAt(0) - '0'.charCodeAt(0);
22
+ } else {
23
+ n = c.charCodeAt(0) - 'A'.charCodeAt(0);
24
+ }
25
+ if( (i & 1) === 0 ) {
26
+ n = even_map.charCodeAt(n) - 'A'.charCodeAt(0);
27
+ }
28
+ s += n;
29
+ }
30
+ if( s % 26 + 'A'.charCodeAt(0) !== cf.charCodeAt(15) ) {
31
+ return false;
32
+ }
33
+ return true;
34
+ };
35
+
36
+
37
+
38
+ if( cf.length === 11 ) {
39
+ return controllo_partita_iva(cf); // il codice fiscale può corrispondere alla partita IVA
40
+
41
+ } else if( cf.length === 16 )
42
+ return controllo_cf(cf);
43
+
44
+ else {
45
+ return false;
46
+ }
47
+
48
+ }
@@ -0,0 +1,32 @@
1
+ // basato sulla classe `PartitaIVA` di Umberto Salsi <salsi@icosaedro.it>
2
+ // http://www.icosaedro.it/cf-pi/index.html
3
+
4
+ export function controllo_partita_iva(piva='') {
5
+
6
+ piva = piva.replace(/\s/g, '');
7
+
8
+ if( piva.length !== 11 ) {
9
+ return false;
10
+ }
11
+
12
+ if( !/^[0-9]{11}$/.test(piva) ) {
13
+ return false;
14
+ }
15
+
16
+ let s = 0;
17
+ for(let i = 0; i < 11; i++ ){
18
+ let n = piva.charCodeAt(i) - '0'.charCodeAt(0);
19
+
20
+ if( (i & 1) === 1 ){
21
+ n *= 2;
22
+ if( n > 9 ) n -= 9;
23
+ }
24
+ s += n;
25
+ }
26
+
27
+ if( s % 10 !== 0 ) {
28
+ return false;
29
+ }
30
+
31
+ return true;
32
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * email_antispam
3
+ * Nasconde le email agli spammer
4
+ * sostituire i tag mailto con
5
+ *
6
+ * <span data-as-e="xxxx" data-as-d="xxxx/it">__argument__</span>
7
+ *
8
+ * dove:
9
+ * - `e` è la porzione utente dell'indirizzo email (prima della chiocciola)
10
+ * - `d` è il dominio (dopo la chiocciola). Se è indicato un dominio di default
11
+ * può essere omesso. È possibile sostituire i punti con lo slash ('/')
12
+ * per rendere meno riconoscibile il dominio
13
+ * - `__argument__` è il testo (opzionale) da mostrare. Se non è presente viene
14
+ * mostrato l'indirizzo email (offuscato)
15
+ */
16
+
17
+ export function obfuscate_email (email, hard = true) {
18
+
19
+ // const rand_string = () => {
20
+ // const chars='abcedefghjilmnopqestuvwxyz ABCEDEFGHJILMNOPQESTUVWXYZ 0123456789' +
21
+ // '\n\t“”"«»%$£&/()=?^*é§°çòàù+èùàò-_.:,;',
22
+ // lunghezza = 4;
23
+
24
+ // let str = '', i, pos;
25
+
26
+ // for( i = 0; i < lunghezza; i++ ) {
27
+ // pos = Math.floor(Math.random() * chars.length);
28
+ // str += chars.charAt(pos);
29
+ // }
30
+ // return str;
31
+ // };
32
+
33
+ let encoded_email = '';
34
+
35
+ email.split('').forEach((char, idx) => {
36
+ // if(hard && [2,5,6,79,10,13,15,20,22].indexOf(idx) !== -1) {
37
+ // encoded_email += `<span style="display:none" aria-hidden="true">${rand_string()}</span>`;
38
+ // }
39
+ if( char === '@') {
40
+ encoded_email += hard?'<span>&commat;</span><wbr>' : '&commat;';
41
+
42
+ } else if (char === '.') {
43
+ encoded_email += hard? '<span>&#x0002E;</span><wbr>' : '&#x0002E;';
44
+
45
+ } else if (char === '-') {
46
+ encoded_email += hard? '<span>&#x02010;</span><span></span>' : '&#x02010;';
47
+
48
+ } else if (char === '_') {
49
+ encoded_email += hard? '<span>&lowbar;</span><span></span>' : '&lowbar;';
50
+
51
+ } else if(idx % 2 === 0) {
52
+ encoded_email += `&#${email.charCodeAt(idx)};`;
53
+
54
+ } else {
55
+ encoded_email += char;
56
+ }
57
+
58
+ });
59
+ return encoded_email;
60
+
61
+ }
62
+
63
+ export function email_antispam (options) {
64
+
65
+ const default_options = {
66
+ default_domain: null
67
+ };
68
+
69
+ options = Object.assign(default_options, options);
70
+
71
+ if( Object.assign && typeof Object.assign === 'function') {
72
+ options = Object.assign(default_options, options);
73
+
74
+ } else { // IE
75
+ let opts = {};
76
+ for(let i in default_options) {
77
+ opts[i] = options[i] ? options[i] : default_options[i];
78
+ }
79
+ options = opts;
80
+ }
81
+
82
+ document.querySelectorAll('[data-as-e]').forEach(el => {
83
+ let domain = el.dataset.asD || options.default_domain;
84
+ if(domain) {
85
+ domain = domain.replace(/\//g, '.');
86
+ let email = el.dataset.asE + '@' + domain,
87
+ content = el.innerHTML || obfuscate_email(email);
88
+
89
+ // el.innerHTML = `<a href="mailto:${email}" target="_blank" rel="noopener noreferrer">${content}</a>`;
90
+
91
+ el.innerHTML = `<!--googleoff: all-->
92
+ <a href="#" target="_blank" rel="noopener noreferrer">${content}</a>
93
+ <!--googleon: all-->`;
94
+ if(el.dataset.addMicrodata !== undefined) {
95
+
96
+ el.insertAdjacentHTML('beforeend',
97
+ `<meta itemprop="email" content="${obfuscate_email(email, false)}">`
98
+ );
99
+ }
100
+ el.querySelector('a').addEventListener('click', (e) => {
101
+ e.preventDefault();
102
+ window.location.href = `mailto:${email}`;
103
+ }, false);
104
+ }
105
+ });
106
+ }
107
+
108
+