Completed
Push — master ( 717daf...0003cd )
by cam
01:14
created
ecrire/inc/filtres_images_lib_mini.php 1 patch
Indentation   +1325 added lines, -1325 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  */
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 include_spip('inc/filtres'); // par precaution
24 24
 include_spip('inc/filtres_images_mini'); // par precaution
@@ -38,21 +38,21 @@  discard block
 block discarded – undo
38 38
  *     Le code de la couleur en hexadécimal.
39 39
  */
40 40
 function _couleur_dec_to_hex($red, $green, $blue) {
41
-	$red = dechex($red);
42
-	$green = dechex($green);
43
-	$blue = dechex($blue);
44
-
45
-	if (strlen($red) == 1) {
46
-		$red = '0' . $red;
47
-	}
48
-	if (strlen($green) == 1) {
49
-		$green = '0' . $green;
50
-	}
51
-	if (strlen($blue) == 1) {
52
-		$blue = '0' . $blue;
53
-	}
54
-
55
-	return "$red$green$blue";
41
+    $red = dechex($red);
42
+    $green = dechex($green);
43
+    $blue = dechex($blue);
44
+
45
+    if (strlen($red) == 1) {
46
+        $red = '0' . $red;
47
+    }
48
+    if (strlen($green) == 1) {
49
+        $green = '0' . $green;
50
+    }
51
+    if (strlen($blue) == 1) {
52
+        $blue = '0' . $blue;
53
+    }
54
+
55
+    return "$red$green$blue";
56 56
 }
57 57
 
58 58
 /**
@@ -64,17 +64,17 @@  discard block
 block discarded – undo
64 64
  *     Un tableau des 3 éléments : rouge, vert, bleu.
65 65
  */
66 66
 function _couleur_hex_to_dec($couleur) {
67
-	$couleur = couleur_html_to_hex($couleur);
68
-	$couleur = ltrim($couleur, '#');
69
-	if (strlen($couleur) === 3) {
70
-		$couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
71
-	}
72
-	$retour = [];
73
-	$retour['red'] = hexdec(substr($couleur, 0, 2));
74
-	$retour['green'] = hexdec(substr($couleur, 2, 2));
75
-	$retour['blue'] = hexdec(substr($couleur, 4, 2));
76
-
77
-	return $retour;
67
+    $couleur = couleur_html_to_hex($couleur);
68
+    $couleur = ltrim($couleur, '#');
69
+    if (strlen($couleur) === 3) {
70
+        $couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
71
+    }
72
+    $retour = [];
73
+    $retour['red'] = hexdec(substr($couleur, 0, 2));
74
+    $retour['green'] = hexdec(substr($couleur, 2, 2));
75
+    $retour['blue'] = hexdec(substr($couleur, 4, 2));
76
+
77
+    return $retour;
78 78
 }
79 79
 
80 80
 
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
  *     Le code de la couleur en hexadécimal.
92 92
  */
93 93
 function _couleur_hsl_to_hex($hue, $saturation, $lightness) {
94
-	$rgb = _couleur_hsl_to_rgb($hue, $saturation, $lightness);
95
-	return _couleur_dec_to_hex($rgb['r'], $rgb['g'], $rgb['b']);
94
+    $rgb = _couleur_hsl_to_rgb($hue, $saturation, $lightness);
95
+    return _couleur_dec_to_hex($rgb['r'], $rgb['g'], $rgb['b']);
96 96
 }
97 97
 
98 98
 /**
@@ -104,8 +104,8 @@  discard block
 block discarded – undo
104 104
  *     Un tableau des 3 éléments : teinte, saturation, luminosité.
105 105
  */
106 106
 function _couleur_hex_to_hsl($couleur) {
107
-	$rgb = _couleur_hex_to_dec($couleur);
108
-	return _couleur_rgb_to_hsl($rgb['red'], $rgb['green'], $rgb['blue']);
107
+    $rgb = _couleur_hex_to_dec($couleur);
108
+    return _couleur_rgb_to_hsl($rgb['red'], $rgb['green'], $rgb['blue']);
109 109
 }
110 110
 
111 111
 /**
@@ -120,59 +120,59 @@  discard block
 block discarded – undo
120 120
  * @return array
121 121
  */
122 122
 function _couleur_rgb_to_hsl($R, $G, $B) {
123
-	$H = null;
124
-	$var_R = ($R / 255); // Where RGB values = 0 ÷ 255
125
-	$var_G = ($G / 255);
126
-	$var_B = ($B / 255);
127
-
128
-	$var_Min = min($var_R, $var_G, $var_B);   //Min. value of RGB
129
-	$var_Max = max($var_R, $var_G, $var_B);   //Max. value of RGB
130
-	$del_Max = $var_Max - $var_Min;           //Delta RGB value
131
-
132
-	$L = ($var_Max + $var_Min) / 2;
133
-
134
-	if ($del_Max == 0) {
135
-		//This is a gray, no chroma...
136
-		$H = 0; //HSL results = 0 ÷ 1
137
-		$S = 0;
138
-	} else {
139
-		// Chromatic data...
140
-		if ($L < 0.5) {
141
-			$S = $del_Max / ($var_Max + $var_Min);
142
-		} else {
143
-			$S = $del_Max / (2 - $var_Max - $var_Min);
144
-		}
145
-
146
-		$del_R = ((($var_Max - $var_R) / 6) + ($del_Max / 2)) / $del_Max;
147
-		$del_G = ((($var_Max - $var_G) / 6) + ($del_Max / 2)) / $del_Max;
148
-		$del_B = ((($var_Max - $var_B) / 6) + ($del_Max / 2)) / $del_Max;
149
-
150
-		if ($var_R == $var_Max) {
151
-			$H = $del_B - $del_G;
152
-		} else {
153
-			if ($var_G == $var_Max) {
154
-				$H = (1 / 3) + $del_R - $del_B;
155
-			} else {
156
-				if ($var_B == $var_Max) {
157
-					$H = (2 / 3) + $del_G - $del_R;
158
-				}
159
-			}
160
-		}
161
-
162
-		if ($H < 0) {
163
-			$H += 1;
164
-		}
165
-		if ($H > 1) {
166
-			$H -= 1;
167
-		}
168
-	}
169
-
170
-	$ret = [];
171
-	$ret['h'] = $H;
172
-	$ret['s'] = $S;
173
-	$ret['l'] = $L;
174
-
175
-	return $ret;
123
+    $H = null;
124
+    $var_R = ($R / 255); // Where RGB values = 0 ÷ 255
125
+    $var_G = ($G / 255);
126
+    $var_B = ($B / 255);
127
+
128
+    $var_Min = min($var_R, $var_G, $var_B);   //Min. value of RGB
129
+    $var_Max = max($var_R, $var_G, $var_B);   //Max. value of RGB
130
+    $del_Max = $var_Max - $var_Min;           //Delta RGB value
131
+
132
+    $L = ($var_Max + $var_Min) / 2;
133
+
134
+    if ($del_Max == 0) {
135
+        //This is a gray, no chroma...
136
+        $H = 0; //HSL results = 0 ÷ 1
137
+        $S = 0;
138
+    } else {
139
+        // Chromatic data...
140
+        if ($L < 0.5) {
141
+            $S = $del_Max / ($var_Max + $var_Min);
142
+        } else {
143
+            $S = $del_Max / (2 - $var_Max - $var_Min);
144
+        }
145
+
146
+        $del_R = ((($var_Max - $var_R) / 6) + ($del_Max / 2)) / $del_Max;
147
+        $del_G = ((($var_Max - $var_G) / 6) + ($del_Max / 2)) / $del_Max;
148
+        $del_B = ((($var_Max - $var_B) / 6) + ($del_Max / 2)) / $del_Max;
149
+
150
+        if ($var_R == $var_Max) {
151
+            $H = $del_B - $del_G;
152
+        } else {
153
+            if ($var_G == $var_Max) {
154
+                $H = (1 / 3) + $del_R - $del_B;
155
+            } else {
156
+                if ($var_B == $var_Max) {
157
+                    $H = (2 / 3) + $del_G - $del_R;
158
+                }
159
+            }
160
+        }
161
+
162
+        if ($H < 0) {
163
+            $H += 1;
164
+        }
165
+        if ($H > 1) {
166
+            $H -= 1;
167
+        }
168
+    }
169
+
170
+    $ret = [];
171
+    $ret['h'] = $H;
172
+    $ret['s'] = $S;
173
+    $ret['l'] = $L;
174
+
175
+    return $ret;
176 176
 }
177 177
 
178 178
 
@@ -188,52 +188,52 @@  discard block
 block discarded – undo
188 188
  * @return array
189 189
  */
190 190
 function _couleur_hsl_to_rgb($H, $S, $L) {
191
-	// helper
192
-	$hue_2_rgb = function ($v1, $v2, $vH) {
193
-		if ($vH < 0) {
194
-			$vH += 1;
195
-		}
196
-		if ($vH > 1) {
197
-			$vH -= 1;
198
-		}
199
-		if ((6 * $vH) < 1) {
200
-			return ($v1 + ($v2 - $v1) * 6 * $vH);
201
-		}
202
-		if ((2 * $vH) < 1) {
203
-			return ($v2);
204
-		}
205
-		if ((3 * $vH) < 2) {
206
-			return ($v1 + ($v2 - $v1) * ((2 / 3) - $vH) * 6);
207
-		}
208
-
209
-		return ($v1);
210
-	};
211
-
212
-	if ($S == 0) {
213
-		// HSV values = 0 -> 1
214
-		$R = $L * 255;
215
-		$G = $L * 255;
216
-		$B = $L * 255;
217
-	} else {
218
-		if ($L < 0.5) {
219
-			$var_2 = $L * (1 + $S);
220
-		} else {
221
-			$var_2 = ($L + $S) - ($S * $L);
222
-		}
223
-
224
-		$var_1 = 2 * $L - $var_2;
225
-
226
-		$R = 255 * $hue_2_rgb($var_1, $var_2, $H + (1 / 3));
227
-		$G = 255 * $hue_2_rgb($var_1, $var_2, $H);
228
-		$B = 255 * $hue_2_rgb($var_1, $var_2, $H - (1 / 3));
229
-	}
230
-
231
-	$ret = [];
232
-	$ret['r'] = floor($R);
233
-	$ret['g'] = floor($G);
234
-	$ret['b'] = floor($B);
235
-
236
-	return $ret;
191
+    // helper
192
+    $hue_2_rgb = function ($v1, $v2, $vH) {
193
+        if ($vH < 0) {
194
+            $vH += 1;
195
+        }
196
+        if ($vH > 1) {
197
+            $vH -= 1;
198
+        }
199
+        if ((6 * $vH) < 1) {
200
+            return ($v1 + ($v2 - $v1) * 6 * $vH);
201
+        }
202
+        if ((2 * $vH) < 1) {
203
+            return ($v2);
204
+        }
205
+        if ((3 * $vH) < 2) {
206
+            return ($v1 + ($v2 - $v1) * ((2 / 3) - $vH) * 6);
207
+        }
208
+
209
+        return ($v1);
210
+    };
211
+
212
+    if ($S == 0) {
213
+        // HSV values = 0 -> 1
214
+        $R = $L * 255;
215
+        $G = $L * 255;
216
+        $B = $L * 255;
217
+    } else {
218
+        if ($L < 0.5) {
219
+            $var_2 = $L * (1 + $S);
220
+        } else {
221
+            $var_2 = ($L + $S) - ($S * $L);
222
+        }
223
+
224
+        $var_1 = 2 * $L - $var_2;
225
+
226
+        $R = 255 * $hue_2_rgb($var_1, $var_2, $H + (1 / 3));
227
+        $G = 255 * $hue_2_rgb($var_1, $var_2, $H);
228
+        $B = 255 * $hue_2_rgb($var_1, $var_2, $H - (1 / 3));
229
+    }
230
+
231
+    $ret = [];
232
+    $ret['r'] = floor($R);
233
+    $ret['g'] = floor($G);
234
+    $ret['b'] = floor($B);
235
+
236
+    return $ret;
237 237
 }
238 238
 
239 239
 /**
@@ -251,11 +251,11 @@  discard block
 block discarded – undo
251 251
  *     true si il faut supprimer le fichier temporaire ; false sinon.
252 252
  */
253 253
 function statut_effacer_images_temporaires($stat) {
254
-	static $statut = false; // par defaut on grave toute les images
255
-	if ($stat === 'get') {
256
-		return $statut;
257
-	}
258
-	$statut = $stat ? true : false;
254
+    static $statut = false; // par defaut on grave toute les images
255
+    if ($stat === 'get') {
256
+        return $statut;
257
+    }
258
+    $statut = $stat ? true : false;
259 259
 }
260 260
 
261 261
 
@@ -308,243 +308,243 @@  discard block
 block discarded – undo
308 308
  *     - array : tableau décrivant de l'image
309 309
  */
310 310
 function _image_valeurs_trans($img, $effet, $forcer_format = false, $fonction_creation = null, $find_in_path = false, $support_svg = false) {
311
-	$ret = [];
312
-	$f = null;
313
-	static $images_recalcul = [];
314
-	if (strlen($img) == 0) {
315
-		return false;
316
-	}
317
-
318
-	$source = trim(extraire_attribut($img, 'src') ?? '');
319
-	if (strlen($source) < 1) {
320
-		$source = $img;
321
-		$img = "<img src='$source' />";
322
-	} elseif (
323
-		preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
324
-		and $extension = _image_trouver_extension_depuis_mime('image/' . $regs[1])
325
-		and in_array($extension, _image_extensions_acceptees_en_entree())
326
-	) {
327
-		# gerer img src="data:....base64"
328
-		$local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
329
-		if (!file_exists($local)) {
330
-			ecrire_fichier($local, base64_decode($regs[2]));
331
-		}
332
-		if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
333
-			$sanitizer($local);
334
-		}
335
-		$source = $local;
336
-		$img = inserer_attribut($img, 'src', $source);
337
-		# eviter les mauvaises surprises lors de conversions de format
338
-		$img = inserer_attribut($img, 'width', '');
339
-		$img = inserer_attribut($img, 'height', '');
340
-	}
341
-
342
-	// les protocoles web prennent au moins 3 lettres
343
-	if (tester_url_absolue($source)) {
344
-		include_spip('inc/distant');
345
-		$fichier = _DIR_RACINE . copie_locale($source);
346
-		if (!$fichier) {
347
-			return '';
348
-		}
349
-		if (
350
-			$extension = _image_trouver_extension($fichier)
351
-			and $sanitizer = charger_fonction($extension, 'sanitizer', true)
352
-		) {
353
-			$sanitizer($fichier);
354
-		}
355
-	} else {
356
-		// enlever le timestamp eventuel
357
-		if (strpos($source, '?') !== false) {
358
-			$source = preg_replace(',[?][0-9]+$,', '', $source);
359
-		}
360
-		if (
361
-			strpos($source, '?') !== false
362
-			and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
363
-			and file_exists($f = preg_replace(',[?].*$,', '', $source))
364
-		) {
365
-			$source = $f;
366
-		}
367
-		$fichier = $source;
368
-	}
369
-
370
-	$terminaison_dest = '';
371
-	if ($terminaison = _image_trouver_extension($fichier)) {
372
-		$terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
373
-	}
374
-
375
-	if (
376
-		$forcer_format !== false
377
-		// ignorer forcer_format si on a une image svg, que le filtre appelant ne supporte pas SVG, et que le forcage est un autre format image
378
-		and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format, _image_extensions_acceptees_en_sortie()))
379
-	) {
380
-		$terminaison_dest = $forcer_format;
381
-	}
382
-
383
-	if (!$terminaison_dest) {
384
-		return false;
385
-	}
386
-
387
-	$nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
388
-	$fichier_dest = $nom_fichier;
389
-	if (
390
-		($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
391
-		or @file_exists($f = $fichier)
392
-	) {
393
-		// on passe la balise img a taille image qui exraira les attributs si possible
394
-		// au lieu de faire un acces disque sur le fichier
395
-		[$ret['hauteur'], $ret['largeur']] = taille_image($find_in_path ? $f : $img);
396
-		$date_src = @filemtime($f);
397
-	} elseif (
398
-		@file_exists($f = "$fichier.src")
399
-		and lire_fichier($f, $valeurs)
400
-		and $valeurs = unserialize($valeurs)
401
-		and isset($valeurs['hauteur_dest'])
402
-		and isset($valeurs['largeur_dest'])
403
-	) {
404
-		$ret['hauteur'] = $valeurs['hauteur_dest'];
405
-		$ret['largeur'] = $valeurs['largeur_dest'];
406
-		$date_src = $valeurs['date'];
407
-	} // pas de fichier source par la
408
-	else {
409
-		return false;
410
-	}
411
-
412
-	// pas de taille mesurable
413
-	if (!($ret['hauteur'] or $ret['largeur'])) {
414
-		return false;
415
-	}
416
-
417
-	// les images calculees dependent du chemin du fichier source
418
-	// pour une meme image source et un meme filtre on aboutira a 2 fichiers selon si l'appel est dans le public ou dans le prive
419
-	// ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
420
-	// qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
421
-	// la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
422
-	// alors que ca concerne peu de site au final
423
-	// la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
424
-	$identifiant = $fichier;
425
-
426
-	// cas general :
427
-	// on a un dossier cache commun et un nom de fichier qui varie avec l'effet
428
-	// cas particulier de reduire :
429
-	// un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
430
-	$cache = 'cache-gd2';
431
-	if (substr($effet, 0, 7) == 'reduire') {
432
-		[, $maxWidth, $maxHeight] = explode('-', $effet);
433
-		[$destWidth, $destHeight] = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
434
-		$ret['largeur_dest'] = $destWidth;
435
-		$ret['hauteur_dest'] = $destHeight;
436
-		$effet = "L{$destWidth}xH$destHeight";
437
-		$cache = 'cache-vignettes';
438
-		$fichier_dest = basename($fichier_dest);
439
-		if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
440
-			// on garde la terminaison initiale car image simplement copiee
441
-			// et on postfixe son nom avec un md5 du path
442
-			$terminaison_dest = $terminaison;
443
-			$fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
444
-		} else {
445
-			$fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
446
-		}
447
-		$cache = sous_repertoire(_DIR_VAR, $cache);
448
-		$cache = sous_repertoire($cache, $effet);
449
-	} else {
450
-		$fichier_dest = md5("$identifiant-$effet");
451
-		$cache = sous_repertoire(_DIR_VAR, $cache);
452
-		$cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
453
-		$fichier_dest = substr($fichier_dest, 2);
454
-	}
455
-
456
-	$fichier_dest = $cache . $fichier_dest . '.' . $terminaison_dest;
457
-
458
-	$GLOBALS['images_calculees'][] = $fichier_dest;
459
-
460
-	$creer = true;
461
-	// si recalcul des images demande, recalculer chaque image une fois
462
-	if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
463
-		$images_recalcul[$fichier_dest] = true;
464
-	} else {
465
-		if (@file_exists($f = $fichier_dest)) {
466
-			if (filemtime($f) >= $date_src) {
467
-				$creer = false;
468
-			}
469
-		} else {
470
-			if (
471
-				@file_exists($f = "$fichier_dest.src")
472
-				and lire_fichier($f, $valeurs)
473
-				and $valeurs = unserialize($valeurs)
474
-				and $valeurs['date'] >= $date_src
475
-			) {
476
-				$creer = false;
477
-			}
478
-		}
479
-	}
480
-	if ($creer) {
481
-		if (!@file_exists($fichier)) {
482
-			if (!@file_exists("$fichier.src")) {
483
-				spip_log("Image absente : $fichier");
484
-
485
-				return false;
486
-			}
487
-			# on reconstruit l'image source absente a partir de la chaine des .src
488
-			reconstruire_image_intermediaire($fichier);
489
-		}
490
-	}
491
-
492
-	if ($creer) {
493
-		spip_log(
494
-			'filtre image ' . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
495
-			'images' . _LOG_DEBUG
496
-		);
497
-	}
498
-
499
-	$term_fonction = _image_trouver_extension_pertinente($fichier);
500
-	$ret['fonction_imagecreatefrom'] = '_imagecreatefrom' . $term_fonction;
501
-	$ret['fichier'] = $fichier;
502
-	$ret['fonction_image'] = '_image_image' . $terminaison_dest;
503
-	$ret['fichier_dest'] = $fichier_dest;
504
-	$ret['format_source'] = _image_extension_normalisee($terminaison);
505
-	$ret['format_dest'] = $terminaison_dest;
506
-	$ret['date_src'] = $date_src;
507
-	$ret['creer'] = $creer;
508
-	$ret['class'] = extraire_attribut($img, 'class');
509
-	$ret['alt'] = extraire_attribut($img, 'alt');
510
-	$ret['style'] = extraire_attribut($img, 'style');
511
-	$ret['tag'] = $img;
512
-	if ($fonction_creation) {
513
-		$ret['reconstruction'] = $fonction_creation;
514
-		# ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement
515
-		# cas de image_reduire qui finalement ne reduit pas l'image source
516
-		# ca evite d'essayer de le creer au prochain hit si il n'est pas la
517
-		#ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
518
-	}
519
-
520
-	$ret = pipeline('image_preparer_filtre', [
521
-			'args' => [
522
-				'img' => $img,
523
-				'effet' => $effet,
524
-				'forcer_format' => $forcer_format,
525
-				'fonction_creation' => $fonction_creation,
526
-				'find_in_path' => $find_in_path,
527
-			],
528
-			'data' => $ret
529
-		]);
530
-
531
-	// une globale pour le debug en cas de crash memoire
532
-	$GLOBALS['derniere_image_calculee'] = $ret;
533
-
534
-	// traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
535
-	if ($term_fonction === 'svg') {
536
-		if ($creer and !$support_svg) {
537
-			process_image_svg_identite($ret);
538
-			$ret['creer'] = false;
539
-		}
540
-	}
541
-	else {
542
-		if (!function_exists($ret['fonction_imagecreatefrom'])) {
543
-			return false;
544
-		}
545
-	}
546
-
547
-	return $ret;
311
+    $ret = [];
312
+    $f = null;
313
+    static $images_recalcul = [];
314
+    if (strlen($img) == 0) {
315
+        return false;
316
+    }
317
+
318
+    $source = trim(extraire_attribut($img, 'src') ?? '');
319
+    if (strlen($source) < 1) {
320
+        $source = $img;
321
+        $img = "<img src='$source' />";
322
+    } elseif (
323
+        preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
324
+        and $extension = _image_trouver_extension_depuis_mime('image/' . $regs[1])
325
+        and in_array($extension, _image_extensions_acceptees_en_entree())
326
+    ) {
327
+        # gerer img src="data:....base64"
328
+        $local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
329
+        if (!file_exists($local)) {
330
+            ecrire_fichier($local, base64_decode($regs[2]));
331
+        }
332
+        if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
333
+            $sanitizer($local);
334
+        }
335
+        $source = $local;
336
+        $img = inserer_attribut($img, 'src', $source);
337
+        # eviter les mauvaises surprises lors de conversions de format
338
+        $img = inserer_attribut($img, 'width', '');
339
+        $img = inserer_attribut($img, 'height', '');
340
+    }
341
+
342
+    // les protocoles web prennent au moins 3 lettres
343
+    if (tester_url_absolue($source)) {
344
+        include_spip('inc/distant');
345
+        $fichier = _DIR_RACINE . copie_locale($source);
346
+        if (!$fichier) {
347
+            return '';
348
+        }
349
+        if (
350
+            $extension = _image_trouver_extension($fichier)
351
+            and $sanitizer = charger_fonction($extension, 'sanitizer', true)
352
+        ) {
353
+            $sanitizer($fichier);
354
+        }
355
+    } else {
356
+        // enlever le timestamp eventuel
357
+        if (strpos($source, '?') !== false) {
358
+            $source = preg_replace(',[?][0-9]+$,', '', $source);
359
+        }
360
+        if (
361
+            strpos($source, '?') !== false
362
+            and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
363
+            and file_exists($f = preg_replace(',[?].*$,', '', $source))
364
+        ) {
365
+            $source = $f;
366
+        }
367
+        $fichier = $source;
368
+    }
369
+
370
+    $terminaison_dest = '';
371
+    if ($terminaison = _image_trouver_extension($fichier)) {
372
+        $terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
373
+    }
374
+
375
+    if (
376
+        $forcer_format !== false
377
+        // ignorer forcer_format si on a une image svg, que le filtre appelant ne supporte pas SVG, et que le forcage est un autre format image
378
+        and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format, _image_extensions_acceptees_en_sortie()))
379
+    ) {
380
+        $terminaison_dest = $forcer_format;
381
+    }
382
+
383
+    if (!$terminaison_dest) {
384
+        return false;
385
+    }
386
+
387
+    $nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
388
+    $fichier_dest = $nom_fichier;
389
+    if (
390
+        ($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
391
+        or @file_exists($f = $fichier)
392
+    ) {
393
+        // on passe la balise img a taille image qui exraira les attributs si possible
394
+        // au lieu de faire un acces disque sur le fichier
395
+        [$ret['hauteur'], $ret['largeur']] = taille_image($find_in_path ? $f : $img);
396
+        $date_src = @filemtime($f);
397
+    } elseif (
398
+        @file_exists($f = "$fichier.src")
399
+        and lire_fichier($f, $valeurs)
400
+        and $valeurs = unserialize($valeurs)
401
+        and isset($valeurs['hauteur_dest'])
402
+        and isset($valeurs['largeur_dest'])
403
+    ) {
404
+        $ret['hauteur'] = $valeurs['hauteur_dest'];
405
+        $ret['largeur'] = $valeurs['largeur_dest'];
406
+        $date_src = $valeurs['date'];
407
+    } // pas de fichier source par la
408
+    else {
409
+        return false;
410
+    }
411
+
412
+    // pas de taille mesurable
413
+    if (!($ret['hauteur'] or $ret['largeur'])) {
414
+        return false;
415
+    }
416
+
417
+    // les images calculees dependent du chemin du fichier source
418
+    // pour une meme image source et un meme filtre on aboutira a 2 fichiers selon si l'appel est dans le public ou dans le prive
419
+    // ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
420
+    // qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
421
+    // la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
422
+    // alors que ca concerne peu de site au final
423
+    // la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
424
+    $identifiant = $fichier;
425
+
426
+    // cas general :
427
+    // on a un dossier cache commun et un nom de fichier qui varie avec l'effet
428
+    // cas particulier de reduire :
429
+    // un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
430
+    $cache = 'cache-gd2';
431
+    if (substr($effet, 0, 7) == 'reduire') {
432
+        [, $maxWidth, $maxHeight] = explode('-', $effet);
433
+        [$destWidth, $destHeight] = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
434
+        $ret['largeur_dest'] = $destWidth;
435
+        $ret['hauteur_dest'] = $destHeight;
436
+        $effet = "L{$destWidth}xH$destHeight";
437
+        $cache = 'cache-vignettes';
438
+        $fichier_dest = basename($fichier_dest);
439
+        if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
440
+            // on garde la terminaison initiale car image simplement copiee
441
+            // et on postfixe son nom avec un md5 du path
442
+            $terminaison_dest = $terminaison;
443
+            $fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
444
+        } else {
445
+            $fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
446
+        }
447
+        $cache = sous_repertoire(_DIR_VAR, $cache);
448
+        $cache = sous_repertoire($cache, $effet);
449
+    } else {
450
+        $fichier_dest = md5("$identifiant-$effet");
451
+        $cache = sous_repertoire(_DIR_VAR, $cache);
452
+        $cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
453
+        $fichier_dest = substr($fichier_dest, 2);
454
+    }
455
+
456
+    $fichier_dest = $cache . $fichier_dest . '.' . $terminaison_dest;
457
+
458
+    $GLOBALS['images_calculees'][] = $fichier_dest;
459
+
460
+    $creer = true;
461
+    // si recalcul des images demande, recalculer chaque image une fois
462
+    if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
463
+        $images_recalcul[$fichier_dest] = true;
464
+    } else {
465
+        if (@file_exists($f = $fichier_dest)) {
466
+            if (filemtime($f) >= $date_src) {
467
+                $creer = false;
468
+            }
469
+        } else {
470
+            if (
471
+                @file_exists($f = "$fichier_dest.src")
472
+                and lire_fichier($f, $valeurs)
473
+                and $valeurs = unserialize($valeurs)
474
+                and $valeurs['date'] >= $date_src
475
+            ) {
476
+                $creer = false;
477
+            }
478
+        }
479
+    }
480
+    if ($creer) {
481
+        if (!@file_exists($fichier)) {
482
+            if (!@file_exists("$fichier.src")) {
483
+                spip_log("Image absente : $fichier");
484
+
485
+                return false;
486
+            }
487
+            # on reconstruit l'image source absente a partir de la chaine des .src
488
+            reconstruire_image_intermediaire($fichier);
489
+        }
490
+    }
491
+
492
+    if ($creer) {
493
+        spip_log(
494
+            'filtre image ' . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
495
+            'images' . _LOG_DEBUG
496
+        );
497
+    }
498
+
499
+    $term_fonction = _image_trouver_extension_pertinente($fichier);
500
+    $ret['fonction_imagecreatefrom'] = '_imagecreatefrom' . $term_fonction;
501
+    $ret['fichier'] = $fichier;
502
+    $ret['fonction_image'] = '_image_image' . $terminaison_dest;
503
+    $ret['fichier_dest'] = $fichier_dest;
504
+    $ret['format_source'] = _image_extension_normalisee($terminaison);
505
+    $ret['format_dest'] = $terminaison_dest;
506
+    $ret['date_src'] = $date_src;
507
+    $ret['creer'] = $creer;
508
+    $ret['class'] = extraire_attribut($img, 'class');
509
+    $ret['alt'] = extraire_attribut($img, 'alt');
510
+    $ret['style'] = extraire_attribut($img, 'style');
511
+    $ret['tag'] = $img;
512
+    if ($fonction_creation) {
513
+        $ret['reconstruction'] = $fonction_creation;
514
+        # ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement
515
+        # cas de image_reduire qui finalement ne reduit pas l'image source
516
+        # ca evite d'essayer de le creer au prochain hit si il n'est pas la
517
+        #ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
518
+    }
519
+
520
+    $ret = pipeline('image_preparer_filtre', [
521
+            'args' => [
522
+                'img' => $img,
523
+                'effet' => $effet,
524
+                'forcer_format' => $forcer_format,
525
+                'fonction_creation' => $fonction_creation,
526
+                'find_in_path' => $find_in_path,
527
+            ],
528
+            'data' => $ret
529
+        ]);
530
+
531
+    // une globale pour le debug en cas de crash memoire
532
+    $GLOBALS['derniere_image_calculee'] = $ret;
533
+
534
+    // traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
535
+    if ($term_fonction === 'svg') {
536
+        if ($creer and !$support_svg) {
537
+            process_image_svg_identite($ret);
538
+            $ret['creer'] = false;
539
+        }
540
+    }
541
+    else {
542
+        if (!function_exists($ret['fonction_imagecreatefrom'])) {
543
+            return false;
544
+        }
545
+    }
546
+
547
+    return $ret;
548 548
 }
549 549
 
550 550
 
@@ -553,54 +553,54 @@  discard block
 block discarded – undo
553 553
  * @return array
554 554
  */
555 555
 function _image_extensions_acceptees_en_entree() {
556
-	static $extensions = null;
557
-	if (empty($extensions)) {
558
-		$extensions = ['png', 'gif', 'jpg', 'jpeg'];
559
-		if (!empty($GLOBALS['meta']['gd_formats'])) {
560
-			// action=tester renseigne gd_formats et detecte le support de webp
561
-			$extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
562
-			$extensions = array_map('trim', $extensions);
563
-			$extensions = array_filter($extensions);
564
-			if (in_array('jpg', $extensions)) {
565
-				$extensions[] = 'jpeg';
566
-			}
567
-			$extensions = array_unique($extensions);
568
-		}
569
-		$extensions[] = 'svg'; // on le supporte toujours avec des fonctions specifiques
570
-	}
571
-
572
-	return $extensions;
556
+    static $extensions = null;
557
+    if (empty($extensions)) {
558
+        $extensions = ['png', 'gif', 'jpg', 'jpeg'];
559
+        if (!empty($GLOBALS['meta']['gd_formats'])) {
560
+            // action=tester renseigne gd_formats et detecte le support de webp
561
+            $extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
562
+            $extensions = array_map('trim', $extensions);
563
+            $extensions = array_filter($extensions);
564
+            if (in_array('jpg', $extensions)) {
565
+                $extensions[] = 'jpeg';
566
+            }
567
+            $extensions = array_unique($extensions);
568
+        }
569
+        $extensions[] = 'svg'; // on le supporte toujours avec des fonctions specifiques
570
+    }
571
+
572
+    return $extensions;
573 573
 }
574 574
 
575 575
 /**
576 576
  * @return array|string[]|null
577 577
  */
578 578
 function _image_extensions_acceptees_en_sortie() {
579
-	static $extensions = null;
580
-	if (empty($extensions)) {
581
-		$extensions = _image_extensions_acceptees_en_entree();
582
-		$extensions = array_diff($extensions, ['jpeg']);
583
-		if (in_array('gif', $extensions) and !function_exists('imagegif')) {
584
-			$extensions = array_diff($extensions, ['gif']);
585
-		}
586
-		if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
587
-			$extensions = array_diff($extensions, ['webp']);
588
-		}
589
-	}
590
-
591
-	return $extensions;
579
+    static $extensions = null;
580
+    if (empty($extensions)) {
581
+        $extensions = _image_extensions_acceptees_en_entree();
582
+        $extensions = array_diff($extensions, ['jpeg']);
583
+        if (in_array('gif', $extensions) and !function_exists('imagegif')) {
584
+            $extensions = array_diff($extensions, ['gif']);
585
+        }
586
+        if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
587
+            $extensions = array_diff($extensions, ['webp']);
588
+        }
589
+    }
590
+
591
+    return $extensions;
592 592
 }
593 593
 
594 594
 function _image_extension_normalisee($extension) {
595
-	$extension = strtolower($extension);
596
-	if ($extension === 'jpeg') {
597
-		$extension = 'jpg';
598
-	}
599
-	return $extension;
595
+    $extension = strtolower($extension);
596
+    if ($extension === 'jpeg') {
597
+        $extension = 'jpg';
598
+    }
599
+    return $extension;
600 600
 }
601 601
 
602 602
 function _image_extensions_conservent_transparence() {
603
-	return ['png', 'webp'];
603
+    return ['png', 'webp'];
604 604
 }
605 605
 
606 606
 
@@ -610,12 +610,12 @@  discard block
 block discarded – undo
610 610
  * @return string
611 611
  */
612 612
 function _image_trouver_extension($path) {
613
-	$preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
614
-	if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
615
-		$terminaison = strtolower($regs[1]);
616
-		return $terminaison;
617
-	}
618
-	return '';
613
+    $preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
614
+    if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
615
+        $terminaison = strtolower($regs[1]);
616
+        return $terminaison;
617
+    }
618
+    return '';
619 619
 }
620 620
 
621 621
 /**
@@ -626,33 +626,33 @@  discard block
 block discarded – undo
626 626
  * @return string Extension, dans le format attendu par les fonctions 'gd' ('jpeg' pour les .jpg par exemple)
627 627
  */
628 628
 function _image_trouver_extension_pertinente($path) {
629
-	$path = supprimer_timestamp($path);
630
-	$terminaison = _image_trouver_extension($path);
631
-	if ($terminaison == 'jpg') {
632
-		$terminaison = 'jpeg';
633
-	}
634
-
635
-	if (!file_exists($path)) {
636
-		return $terminaison;
637
-	}
638
-
639
-	if (!$info = @spip_getimagesize($path)) {
640
-		return $terminaison;
641
-	}
642
-
643
-	if (isset($info['mime'])) {
644
-		$mime = $info['mime'];
645
-	}
646
-	else {
647
-		$mime = image_type_to_mime_type($info[2]);
648
-	}
649
-
650
-	$_terminaison = _image_trouver_extension_depuis_mime($mime);
651
-	if ($_terminaison and $_terminaison !== $terminaison) {
652
-		spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", 'images.' . _LOG_INFO_IMPORTANTE);
653
-		$terminaison = $_terminaison;
654
-	}
655
-	return $terminaison;
629
+    $path = supprimer_timestamp($path);
630
+    $terminaison = _image_trouver_extension($path);
631
+    if ($terminaison == 'jpg') {
632
+        $terminaison = 'jpeg';
633
+    }
634
+
635
+    if (!file_exists($path)) {
636
+        return $terminaison;
637
+    }
638
+
639
+    if (!$info = @spip_getimagesize($path)) {
640
+        return $terminaison;
641
+    }
642
+
643
+    if (isset($info['mime'])) {
644
+        $mime = $info['mime'];
645
+    }
646
+    else {
647
+        $mime = image_type_to_mime_type($info[2]);
648
+    }
649
+
650
+    $_terminaison = _image_trouver_extension_depuis_mime($mime);
651
+    if ($_terminaison and $_terminaison !== $terminaison) {
652
+        spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", 'images.' . _LOG_INFO_IMPORTANTE);
653
+        $terminaison = $_terminaison;
654
+    }
655
+    return $terminaison;
656 656
 }
657 657
 
658 658
 /**
@@ -660,36 +660,36 @@  discard block
 block discarded – undo
660 660
  * @return string
661 661
  */
662 662
 function _image_trouver_extension_depuis_mime($mime) {
663
-	switch (strtolower($mime)) {
664
-		case 'image/png':
665
-		case 'image/x-png':
666
-			$terminaison = 'png';
667
-			break;
668
-
669
-		case 'image/jpg':
670
-		case 'image/jpeg':
671
-		case 'image/pjpeg':
672
-			$terminaison = 'jpeg';
673
-			break;
674
-
675
-		case 'image/gif':
676
-			$terminaison = 'gif';
677
-			break;
678
-
679
-		case 'image/webp':
680
-		case 'image/x-webp':
681
-			$terminaison = 'webp';
682
-			break;
683
-
684
-		case 'image/svg+xml':
685
-			$terminaison = 'svg';
686
-			break;
687
-
688
-		default:
689
-			$terminaison = '';
690
-	}
691
-
692
-	return $terminaison;
663
+    switch (strtolower($mime)) {
664
+        case 'image/png':
665
+        case 'image/x-png':
666
+            $terminaison = 'png';
667
+            break;
668
+
669
+        case 'image/jpg':
670
+        case 'image/jpeg':
671
+        case 'image/pjpeg':
672
+            $terminaison = 'jpeg';
673
+            break;
674
+
675
+        case 'image/gif':
676
+            $terminaison = 'gif';
677
+            break;
678
+
679
+        case 'image/webp':
680
+        case 'image/x-webp':
681
+            $terminaison = 'webp';
682
+            break;
683
+
684
+        case 'image/svg+xml':
685
+            $terminaison = 'svg';
686
+            break;
687
+
688
+        default:
689
+            $terminaison = '';
690
+    }
691
+
692
+    return $terminaison;
693 693
 }
694 694
 
695 695
 
@@ -709,18 +709,18 @@  discard block
 block discarded – undo
709 709
  *     Une ressource de type Image GD.
710 710
  */
711 711
 function _imagecreatefrom_func(string $func, string $filename) {
712
-	if (!function_exists($func)) {
713
-		spip_log("GD indisponible : $func inexistante. Traitement $filename impossible.", _LOG_CRITIQUE);
714
-		erreur_squelette("GD indisponible : $func inexistante. Traitement $filename impossible.");
715
-		return null;
716
-	}
717
-	$img = @$func($filename);
718
-	if (!$img) {
719
-		spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
720
-		erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
721
-		$img = imagecreate(10, 10);
722
-	}
723
-	return $img;
712
+    if (!function_exists($func)) {
713
+        spip_log("GD indisponible : $func inexistante. Traitement $filename impossible.", _LOG_CRITIQUE);
714
+        erreur_squelette("GD indisponible : $func inexistante. Traitement $filename impossible.");
715
+        return null;
716
+    }
717
+    $img = @$func($filename);
718
+    if (!$img) {
719
+        spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
720
+        erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
721
+        $img = imagecreate(10, 10);
722
+    }
723
+    return $img;
724 724
 }
725 725
 
726 726
 /**
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
  *     Une ressource de type Image GD.
737 737
  */
738 738
 function _imagecreatefromjpeg($filename) {
739
-	return _imagecreatefrom_func('imagecreatefromjpeg', $filename);
739
+    return _imagecreatefrom_func('imagecreatefromjpeg', $filename);
740 740
 }
741 741
 
742 742
 /**
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
  *     Une ressource de type Image GD.
753 753
  */
754 754
 function _imagecreatefrompng($filename) {
755
-	return _imagecreatefrom_func('imagecreatefrompng', $filename);
755
+    return _imagecreatefrom_func('imagecreatefrompng', $filename);
756 756
 }
757 757
 
758 758
 /**
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
  *     Une ressource de type Image GD.
769 769
  */
770 770
 function _imagecreatefromgif($filename) {
771
-	return _imagecreatefrom_func('imagecreatefromgif', $filename);
771
+    return _imagecreatefrom_func('imagecreatefromgif', $filename);
772 772
 }
773 773
 
774 774
 
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
  *     Une ressource de type Image GD.
786 786
  */
787 787
 function _imagecreatefromwebp($filename) {
788
-	return _imagecreatefrom_func('imagecreatefromwebp', $filename);
788
+    return _imagecreatefrom_func('imagecreatefromwebp', $filename);
789 789
 }
790 790
 
791 791
 /**
@@ -803,24 +803,24 @@  discard block
 block discarded – undo
803 803
  *     - true si une image est bien retournée.
804 804
  */
805 805
 function _image_imagepng($img, $fichier) {
806
-	if (!function_exists('imagepng')) {
807
-		return false;
808
-	}
809
-	$tmp = $fichier . '.tmp';
810
-	$ret = imagepng($img, $tmp);
811
-	if (file_exists($tmp)) {
812
-		$taille_test = getimagesize($tmp);
813
-		if ($taille_test[0] < 1) {
814
-			return false;
815
-		}
816
-
817
-		spip_unlink($fichier); // le fichier peut deja exister
818
-		@rename($tmp, $fichier);
819
-
820
-		return $ret;
821
-	}
822
-
823
-	return false;
806
+    if (!function_exists('imagepng')) {
807
+        return false;
808
+    }
809
+    $tmp = $fichier . '.tmp';
810
+    $ret = imagepng($img, $tmp);
811
+    if (file_exists($tmp)) {
812
+        $taille_test = getimagesize($tmp);
813
+        if ($taille_test[0] < 1) {
814
+            return false;
815
+        }
816
+
817
+        spip_unlink($fichier); // le fichier peut deja exister
818
+        @rename($tmp, $fichier);
819
+
820
+        return $ret;
821
+    }
822
+
823
+    return false;
824 824
 }
825 825
 
826 826
 /**
@@ -838,24 +838,24 @@  discard block
 block discarded – undo
838 838
  *     - true si une image est bien retournée.
839 839
  */
840 840
 function _image_imagegif($img, $fichier) {
841
-	if (!function_exists('imagegif')) {
842
-		return false;
843
-	}
844
-	$tmp = $fichier . '.tmp';
845
-	$ret = imagegif($img, $tmp);
846
-	if (file_exists($tmp)) {
847
-		$taille_test = getimagesize($tmp);
848
-		if ($taille_test[0] < 1) {
849
-			return false;
850
-		}
851
-
852
-		spip_unlink($fichier); // le fichier peut deja exister
853
-		@rename($tmp, $fichier);
854
-
855
-		return $ret;
856
-	}
857
-
858
-	return false;
841
+    if (!function_exists('imagegif')) {
842
+        return false;
843
+    }
844
+    $tmp = $fichier . '.tmp';
845
+    $ret = imagegif($img, $tmp);
846
+    if (file_exists($tmp)) {
847
+        $taille_test = getimagesize($tmp);
848
+        if ($taille_test[0] < 1) {
849
+            return false;
850
+        }
851
+
852
+        spip_unlink($fichier); // le fichier peut deja exister
853
+        @rename($tmp, $fichier);
854
+
855
+        return $ret;
856
+    }
857
+
858
+    return false;
859 859
 }
860 860
 
861 861
 /**
@@ -878,29 +878,29 @@  discard block
 block discarded – undo
878 878
  *     - true si une image est bien retournée.
879 879
  */
880 880
 function _image_imagejpg($img, $fichier, $qualite = _IMG_GD_QUALITE) {
881
-	if (!function_exists('imagejpeg')) {
882
-		return false;
883
-	}
884
-	$tmp = $fichier . '.tmp';
881
+    if (!function_exists('imagejpeg')) {
882
+        return false;
883
+    }
884
+    $tmp = $fichier . '.tmp';
885 885
 
886
-	// Enable interlancing
887
-	imageinterlace($img, true);
886
+    // Enable interlancing
887
+    imageinterlace($img, true);
888 888
 
889
-	$ret = imagejpeg($img, $tmp, $qualite);
889
+    $ret = imagejpeg($img, $tmp, $qualite);
890 890
 
891
-	if (file_exists($tmp)) {
892
-		$taille_test = getimagesize($tmp);
893
-		if ($taille_test[0] < 1) {
894
-			return false;
895
-		}
891
+    if (file_exists($tmp)) {
892
+        $taille_test = getimagesize($tmp);
893
+        if ($taille_test[0] < 1) {
894
+            return false;
895
+        }
896 896
 
897
-		spip_unlink($fichier); // le fichier peut deja exister
898
-		@rename($tmp, $fichier);
897
+        spip_unlink($fichier); // le fichier peut deja exister
898
+        @rename($tmp, $fichier);
899 899
 
900
-		return $ret;
901
-	}
900
+        return $ret;
901
+    }
902 902
 
903
-	return false;
903
+    return false;
904 904
 }
905 905
 
906 906
 /**
@@ -918,9 +918,9 @@  discard block
 block discarded – undo
918 918
  *     true si le fichier a bien été créé ; false sinon.
919 919
  */
920 920
 function _image_imageico($img, $fichier) {
921
-	$gd_image_array = [$img];
921
+    $gd_image_array = [$img];
922 922
 
923
-	return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
923
+    return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
924 924
 }
925 925
 
926 926
 
@@ -939,24 +939,24 @@  discard block
 block discarded – undo
939 939
  *     - true si une image est bien retournée.
940 940
  */
941 941
 function _image_imagewebp($img, $fichier, $qualite = _IMG_GD_QUALITE) {
942
-	if (!function_exists('imagewebp')) {
943
-		return false;
944
-	}
945
-	$tmp = $fichier . '.tmp';
946
-	$ret = imagewebp($img, $tmp, $qualite);
947
-	if (file_exists($tmp)) {
948
-		$taille_test = getimagesize($tmp);
949
-		if ($taille_test[0] < 1) {
950
-			return false;
951
-		}
952
-
953
-		spip_unlink($fichier); // le fichier peut deja exister
954
-		@rename($tmp, $fichier);
955
-
956
-		return $ret;
957
-	}
958
-
959
-	return false;
942
+    if (!function_exists('imagewebp')) {
943
+        return false;
944
+    }
945
+    $tmp = $fichier . '.tmp';
946
+    $ret = imagewebp($img, $tmp, $qualite);
947
+    if (file_exists($tmp)) {
948
+        $taille_test = getimagesize($tmp);
949
+        if ($taille_test[0] < 1) {
950
+            return false;
951
+        }
952
+
953
+        spip_unlink($fichier); // le fichier peut deja exister
954
+        @rename($tmp, $fichier);
955
+
956
+        return $ret;
957
+    }
958
+
959
+    return false;
960 960
 }
961 961
 
962 962
 /**
@@ -976,35 +976,35 @@  discard block
 block discarded – undo
976 976
  */
977 977
 function _image_imagesvg($img, $fichier) {
978 978
 
979
-	$tmp = $fichier . '.tmp';
980
-	if (strpos($img, '<') === false) {
981
-		$img = supprimer_timestamp($img);
982
-		if (!file_exists($img)) {
983
-			return false;
984
-		}
985
-		@copy($img, $tmp);
986
-		if (filesize($tmp) == filesize($img)) {
987
-			spip_unlink($fichier); // le fichier peut deja exister
988
-			@rename($tmp, $fichier);
989
-			return true;
990
-		}
991
-		return false;
992
-	}
993
-
994
-	file_put_contents($tmp, $img);
995
-	if (file_exists($tmp)) {
996
-		$taille_test = spip_getimagesize($tmp);
997
-		if ($taille_test[0] < 1) {
998
-			return false;
999
-		}
1000
-
1001
-		spip_unlink($fichier); // le fichier peut deja exister
1002
-		@rename($tmp, $fichier);
1003
-
1004
-		return true;
1005
-	}
1006
-
1007
-	return false;
979
+    $tmp = $fichier . '.tmp';
980
+    if (strpos($img, '<') === false) {
981
+        $img = supprimer_timestamp($img);
982
+        if (!file_exists($img)) {
983
+            return false;
984
+        }
985
+        @copy($img, $tmp);
986
+        if (filesize($tmp) == filesize($img)) {
987
+            spip_unlink($fichier); // le fichier peut deja exister
988
+            @rename($tmp, $fichier);
989
+            return true;
990
+        }
991
+        return false;
992
+    }
993
+
994
+    file_put_contents($tmp, $img);
995
+    if (file_exists($tmp)) {
996
+        $taille_test = spip_getimagesize($tmp);
997
+        if ($taille_test[0] < 1) {
998
+            return false;
999
+        }
1000
+
1001
+        spip_unlink($fichier); // le fichier peut deja exister
1002
+        @rename($tmp, $fichier);
1003
+
1004
+        return true;
1005
+    }
1006
+
1007
+    return false;
1008 1008
 }
1009 1009
 
1010 1010
 
@@ -1032,31 +1032,31 @@  discard block
 block discarded – undo
1032 1032
  *     - false sinon.
1033 1033
  */
1034 1034
 function _image_gd_output($img, $valeurs, $qualite = _IMG_GD_QUALITE, $fonction = null) {
1035
-	if (is_null($fonction)) {
1036
-		$fonction = '_image_image' . $valeurs['format_dest'];
1037
-	}
1038
-	$ret = false;
1039
-	#un flag pour reperer les images gravees
1040
-	$lock = (
1041
-		!statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
1042
-	    or
1043
-		(@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'))
1044
-		);
1045
-	if (
1046
-		function_exists($fonction)
1047
-		&& ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
1048
-		&& isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
1049
-		&& !$lock
1050
-	) {
1051
-		if (@file_exists($valeurs['fichier_dest'])) {
1052
-			// dans tous les cas mettre a jour la taille de l'image finale
1053
-			[$valeurs['hauteur_dest'], $valeurs['largeur_dest']] = taille_image($valeurs['fichier_dest']);
1054
-			$valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
1055
-			ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
1056
-		}
1057
-	}
1058
-
1059
-	return $ret;
1035
+    if (is_null($fonction)) {
1036
+        $fonction = '_image_image' . $valeurs['format_dest'];
1037
+    }
1038
+    $ret = false;
1039
+    #un flag pour reperer les images gravees
1040
+    $lock = (
1041
+        !statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
1042
+        or
1043
+        (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'))
1044
+        );
1045
+    if (
1046
+        function_exists($fonction)
1047
+        && ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
1048
+        && isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
1049
+        && !$lock
1050
+    ) {
1051
+        if (@file_exists($valeurs['fichier_dest'])) {
1052
+            // dans tous les cas mettre a jour la taille de l'image finale
1053
+            [$valeurs['hauteur_dest'], $valeurs['largeur_dest']] = taille_image($valeurs['fichier_dest']);
1054
+            $valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
1055
+            ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
1056
+        }
1057
+    }
1058
+
1059
+    return $ret;
1060 1060
 }
1061 1061
 
1062 1062
 /**
@@ -1069,27 +1069,27 @@  discard block
 block discarded – undo
1069 1069
  *     Chemin vers le fichier manquant
1070 1070
  **/
1071 1071
 function reconstruire_image_intermediaire($fichier_manquant) {
1072
-	$reconstruire = [];
1073
-	$fichier = $fichier_manquant;
1074
-	while (
1075
-		strpos($fichier, '://') === false
1076
-		and !@file_exists($fichier)
1077
-		and lire_fichier($src = "$fichier.src", $source)
1078
-		and $valeurs = unserialize($source)
1079
-		and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1080
-	) {
1081
-		spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
1082
-		$reconstruire[] = $valeurs['reconstruction'];
1083
-	}
1084
-	while (count($reconstruire)) {
1085
-		$r = array_pop($reconstruire);
1086
-		$fonction = $r[0];
1087
-		$args = $r[1];
1088
-		$fonction(...$args);
1089
-	}
1090
-	// cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
1091
-	// mais l'on peut nettoyer les miettes de sa creation
1092
-	ramasse_miettes($fichier_manquant);
1072
+    $reconstruire = [];
1073
+    $fichier = $fichier_manquant;
1074
+    while (
1075
+        strpos($fichier, '://') === false
1076
+        and !@file_exists($fichier)
1077
+        and lire_fichier($src = "$fichier.src", $source)
1078
+        and $valeurs = unserialize($source)
1079
+        and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1080
+    ) {
1081
+        spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
1082
+        $reconstruire[] = $valeurs['reconstruction'];
1083
+    }
1084
+    while (count($reconstruire)) {
1085
+        $r = array_pop($reconstruire);
1086
+        $fonction = $r[0];
1087
+        $args = $r[1];
1088
+        $fonction(...$args);
1089
+    }
1090
+    // cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
1091
+    // mais l'on peut nettoyer les miettes de sa creation
1092
+    ramasse_miettes($fichier_manquant);
1093 1093
 }
1094 1094
 
1095 1095
 /**
@@ -1109,28 +1109,28 @@  discard block
 block discarded – undo
1109 1109
  *     Chemin du fichier d'image calculé
1110 1110
  **/
1111 1111
 function ramasse_miettes($fichier) {
1112
-	if (
1113
-		strpos($fichier, '://') !== false
1114
-		or !lire_fichier($src = "$fichier.src", $source)
1115
-		or !$valeurs = unserialize($source)
1116
-	) {
1117
-		return;
1118
-	}
1119
-	spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
1120
-	while (
1121
-		($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1122
-		and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
1123
-		and (lire_fichier(
1124
-			$src = "$fichier.src",
1125
-			$source
1126
-		)) # le fichier a une source connue (c'est donc une image calculee intermediaire)
1127
-		and ($valeurs = unserialize($source))  # et valide
1128
-	) {
1129
-		# on efface le fichier
1130
-		spip_unlink($fichier);
1131
-		# mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
1132
-		#spip_unlink($src);
1133
-	}
1112
+    if (
1113
+        strpos($fichier, '://') !== false
1114
+        or !lire_fichier($src = "$fichier.src", $source)
1115
+        or !$valeurs = unserialize($source)
1116
+    ) {
1117
+        return;
1118
+    }
1119
+    spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
1120
+    while (
1121
+        ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1122
+        and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
1123
+        and (lire_fichier(
1124
+            $src = "$fichier.src",
1125
+            $source
1126
+        )) # le fichier a une source connue (c'est donc une image calculee intermediaire)
1127
+        and ($valeurs = unserialize($source))  # et valide
1128
+    ) {
1129
+        # on efface le fichier
1130
+        spip_unlink($fichier);
1131
+        # mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
1132
+        #spip_unlink($src);
1133
+    }
1134 1134
 }
1135 1135
 
1136 1136
 
@@ -1155,31 +1155,31 @@  discard block
 block discarded – undo
1155 1155
  *     Code HTML de l'image
1156 1156
  **/
1157 1157
 function image_graver($img) {
1158
-	// appeler le filtre post_image_filtrer qui permet de faire
1159
-	// des traitements auto a la fin d'une serie de filtres
1160
-	$img = pipeline('post_image_filtrer', $img);
1161
-
1162
-	$fichier_ori = $fichier = extraire_attribut($img, 'src');
1163
-	if (($p = strpos($fichier, '?')) !== false) {
1164
-		$fichier = substr($fichier, 0, $p);
1165
-	}
1166
-	if (strlen($fichier) < 1) {
1167
-		$fichier = $img;
1168
-	}
1169
-	# si jamais le fichier final n'a pas ete calcule car suppose temporaire
1170
-	# et qu'il ne s'agit pas d'une URL
1171
-	if (strpos($fichier, '://') === false and !@file_exists($fichier)) {
1172
-		reconstruire_image_intermediaire($fichier);
1173
-	}
1174
-	ramasse_miettes($fichier);
1175
-
1176
-	// ajouter le timestamp si besoin
1177
-	if (strpos($fichier_ori, '?') === false) {
1178
-		// on utilise str_replace pour attraper le onmouseover des logo si besoin
1179
-		$img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
1180
-	}
1181
-
1182
-	return $img;
1158
+    // appeler le filtre post_image_filtrer qui permet de faire
1159
+    // des traitements auto a la fin d'une serie de filtres
1160
+    $img = pipeline('post_image_filtrer', $img);
1161
+
1162
+    $fichier_ori = $fichier = extraire_attribut($img, 'src');
1163
+    if (($p = strpos($fichier, '?')) !== false) {
1164
+        $fichier = substr($fichier, 0, $p);
1165
+    }
1166
+    if (strlen($fichier) < 1) {
1167
+        $fichier = $img;
1168
+    }
1169
+    # si jamais le fichier final n'a pas ete calcule car suppose temporaire
1170
+    # et qu'il ne s'agit pas d'une URL
1171
+    if (strpos($fichier, '://') === false and !@file_exists($fichier)) {
1172
+        reconstruire_image_intermediaire($fichier);
1173
+    }
1174
+    ramasse_miettes($fichier);
1175
+
1176
+    // ajouter le timestamp si besoin
1177
+    if (strpos($fichier_ori, '?') === false) {
1178
+        // on utilise str_replace pour attraper le onmouseover des logo si besoin
1179
+        $img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
1180
+    }
1181
+
1182
+    return $img;
1183 1183
 }
1184 1184
 
1185 1185
 /**
@@ -1206,34 +1206,34 @@  discard block
 block discarded – undo
1206 1206
  *     Code html modifié de la balise.
1207 1207
  **/
1208 1208
 function _image_tag_changer_taille($tag, $width, $height, $style = false) {
1209
-	if ($style === false) {
1210
-		$style = extraire_attribut($tag, 'style');
1211
-	}
1212
-
1213
-	// enlever le width et height du style
1214
-	if ($style) {
1215
-		$style = preg_replace(',(^|;)\s*(width|height)\s*:\s*[^;]+,ims', '', $style);
1216
-	}
1217
-	if ($style and $style[0] === ';') {
1218
-		$style = substr($style, 1);
1219
-	}
1220
-
1221
-	// mettre des attributs de width et height sur les images,
1222
-	// ca accelere le rendu du navigateur
1223
-	// ca permet aux navigateurs de reserver la bonne taille
1224
-	// quand on a desactive l'affichage des images.
1225
-	$tag = inserer_attribut($tag, 'width', round($width));
1226
-	$tag = inserer_attribut($tag, 'height', round($height));
1227
-
1228
-	// attributs deprecies. Transformer en CSS
1229
-	if ($espace = extraire_attribut($tag, 'hspace')) {
1230
-		$style = "margin:${espace}px;" . $style;
1231
-		$tag = inserer_attribut($tag, 'hspace', '');
1232
-	}
1233
-
1234
-	$tag = inserer_attribut($tag, 'style', (string) $style, true, $style ? false : true);
1235
-
1236
-	return $tag;
1209
+    if ($style === false) {
1210
+        $style = extraire_attribut($tag, 'style');
1211
+    }
1212
+
1213
+    // enlever le width et height du style
1214
+    if ($style) {
1215
+        $style = preg_replace(',(^|;)\s*(width|height)\s*:\s*[^;]+,ims', '', $style);
1216
+    }
1217
+    if ($style and $style[0] === ';') {
1218
+        $style = substr($style, 1);
1219
+    }
1220
+
1221
+    // mettre des attributs de width et height sur les images,
1222
+    // ca accelere le rendu du navigateur
1223
+    // ca permet aux navigateurs de reserver la bonne taille
1224
+    // quand on a desactive l'affichage des images.
1225
+    $tag = inserer_attribut($tag, 'width', round($width));
1226
+    $tag = inserer_attribut($tag, 'height', round($height));
1227
+
1228
+    // attributs deprecies. Transformer en CSS
1229
+    if ($espace = extraire_attribut($tag, 'hspace')) {
1230
+        $style = "margin:${espace}px;" . $style;
1231
+        $tag = inserer_attribut($tag, 'hspace', '');
1232
+    }
1233
+
1234
+    $tag = inserer_attribut($tag, 'style', (string) $style, true, $style ? false : true);
1235
+
1236
+    return $tag;
1237 1237
 }
1238 1238
 
1239 1239
 
@@ -1259,72 +1259,72 @@  discard block
 block discarded – undo
1259 1259
  *     Retourne le code HTML de l'image
1260 1260
  **/
1261 1261
 function _image_ecrire_tag($valeurs, $surcharge = []) {
1262
-	$valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1263
-
1264
-	// fermer les tags img pas bien fermes;
1265
-	$tag = str_replace('>', '/>', str_replace('/>', '>', $valeurs['tag']));
1266
-
1267
-	// le style
1268
-	$style = $valeurs['style'];
1269
-	if (isset($surcharge['style'])) {
1270
-		$style = $surcharge['style'];
1271
-		unset($surcharge['style']);
1272
-	}
1273
-
1274
-	// traiter specifiquement la largeur et la hauteur
1275
-	$width = $valeurs['largeur'];
1276
-	if (isset($surcharge['width'])) {
1277
-		$width = $surcharge['width'];
1278
-		unset($surcharge['width']);
1279
-	}
1280
-	$height = $valeurs['hauteur'];
1281
-	if (isset($surcharge['height'])) {
1282
-		$height = $surcharge['height'];
1283
-		unset($surcharge['height']);
1284
-	}
1285
-
1286
-	$tag = _image_tag_changer_taille($tag, $width, $height, $style);
1287
-	// traiter specifiquement le src qui peut etre repris dans un onmouseout
1288
-	// on remplace toute les ref a src dans le tag
1289
-	$src = extraire_attribut($tag, 'src');
1290
-	if (isset($surcharge['src'])) {
1291
-		$tag = str_replace($src, $surcharge['src'], $tag);
1292
-		// si il y a des & dans src, alors ils peuvent provenir d'un &amp
1293
-		// pas garanti comme methode, mais mieux que rien
1294
-		if (strpos($src, '&') !== false) {
1295
-			$tag = str_replace(str_replace('&', '&amp;', $src), $surcharge['src'], $tag);
1296
-		}
1297
-		$src = $surcharge['src'];
1298
-		unset($surcharge['src']);
1299
-	}
1300
-
1301
-	$class = $valeurs['class'];
1302
-	if (isset($surcharge['class'])) {
1303
-		$class = $surcharge['class'];
1304
-		unset($surcharge['class']);
1305
-	}
1306
-	if (is_scalar($class) && strlen($class)) {
1307
-		$tag = inserer_attribut($tag, 'class', $class);
1308
-	}
1309
-
1310
-	if (count($surcharge)) {
1311
-		foreach ($surcharge as $attribut => $valeur) {
1312
-			$tag = inserer_attribut($tag, $attribut, $valeur);
1313
-		}
1314
-	}
1315
-
1316
-	$tag = pipeline(
1317
-		'image_ecrire_tag_finir',
1318
-		[
1319
-			'args' => [
1320
-				'valeurs' => $valeurs,
1321
-				'surcharge' => $surcharge,
1322
-			],
1323
-			'data' => $tag
1324
-		]
1325
-	);
1326
-
1327
-	return $tag;
1262
+    $valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1263
+
1264
+    // fermer les tags img pas bien fermes;
1265
+    $tag = str_replace('>', '/>', str_replace('/>', '>', $valeurs['tag']));
1266
+
1267
+    // le style
1268
+    $style = $valeurs['style'];
1269
+    if (isset($surcharge['style'])) {
1270
+        $style = $surcharge['style'];
1271
+        unset($surcharge['style']);
1272
+    }
1273
+
1274
+    // traiter specifiquement la largeur et la hauteur
1275
+    $width = $valeurs['largeur'];
1276
+    if (isset($surcharge['width'])) {
1277
+        $width = $surcharge['width'];
1278
+        unset($surcharge['width']);
1279
+    }
1280
+    $height = $valeurs['hauteur'];
1281
+    if (isset($surcharge['height'])) {
1282
+        $height = $surcharge['height'];
1283
+        unset($surcharge['height']);
1284
+    }
1285
+
1286
+    $tag = _image_tag_changer_taille($tag, $width, $height, $style);
1287
+    // traiter specifiquement le src qui peut etre repris dans un onmouseout
1288
+    // on remplace toute les ref a src dans le tag
1289
+    $src = extraire_attribut($tag, 'src');
1290
+    if (isset($surcharge['src'])) {
1291
+        $tag = str_replace($src, $surcharge['src'], $tag);
1292
+        // si il y a des & dans src, alors ils peuvent provenir d'un &amp
1293
+        // pas garanti comme methode, mais mieux que rien
1294
+        if (strpos($src, '&') !== false) {
1295
+            $tag = str_replace(str_replace('&', '&amp;', $src), $surcharge['src'], $tag);
1296
+        }
1297
+        $src = $surcharge['src'];
1298
+        unset($surcharge['src']);
1299
+    }
1300
+
1301
+    $class = $valeurs['class'];
1302
+    if (isset($surcharge['class'])) {
1303
+        $class = $surcharge['class'];
1304
+        unset($surcharge['class']);
1305
+    }
1306
+    if (is_scalar($class) && strlen($class)) {
1307
+        $tag = inserer_attribut($tag, 'class', $class);
1308
+    }
1309
+
1310
+    if (count($surcharge)) {
1311
+        foreach ($surcharge as $attribut => $valeur) {
1312
+            $tag = inserer_attribut($tag, $attribut, $valeur);
1313
+        }
1314
+    }
1315
+
1316
+    $tag = pipeline(
1317
+        'image_ecrire_tag_finir',
1318
+        [
1319
+            'args' => [
1320
+                'valeurs' => $valeurs,
1321
+                'surcharge' => $surcharge,
1322
+            ],
1323
+            'data' => $tag
1324
+        ]
1325
+    );
1326
+
1327
+    return $tag;
1328 1328
 }
1329 1329
 
1330 1330
 /**
@@ -1347,268 +1347,268 @@  discard block
 block discarded – undo
1347 1347
  *     Description de l'image, sinon null.
1348 1348
  **/
1349 1349
 function _image_creer_vignette($valeurs, $maxWidth, $maxHeight, $process = 'AUTO', $force = false) {
1350
-	$srcHeight = null;
1351
-	$retour = [];
1352
-	// ordre de preference des formats graphiques pour creer les vignettes
1353
-	// le premier format disponible, selon la methode demandee, est utilise
1354
-	$image = $valeurs['fichier'];
1355
-	$format = $valeurs['format_source'];
1356
-	$destdir = dirname($valeurs['fichier_dest']);
1357
-	$destfile = basename($valeurs['fichier_dest'], '.' . $valeurs['format_dest']);
1358
-
1359
-	$format_sortie = $valeurs['format_dest'];
1360
-
1361
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1362
-		$process = $GLOBALS['meta']['image_process'];
1363
-	}
1364
-
1365
-	// si le doc n'est pas une image dans un format accetpable, refuser
1366
-	if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1367
-		return;
1368
-	}
1369
-	$destination = "$destdir/$destfile";
1370
-
1371
-	// calculer la taille
1372
-	if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1373
-		if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1374
-			[$destWidth, $destHeight] = _image_ratio($srcWidth, $srcHeight, $maxWidth, $maxHeight);
1375
-		}
1376
-	} elseif ($process == 'convert' or $process == 'imagick') {
1377
-		$destWidth = $maxWidth;
1378
-		$destHeight = $maxHeight;
1379
-	} else {
1380
-		spip_log("echec $process sur $image");
1381
-
1382
-		return;
1383
-	}
1384
-
1385
-	$vignette = '';
1386
-
1387
-	// Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1388
-	if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1389
-		$vignette = $destination . '.' . $format;
1390
-		@copy($image, $vignette);
1391
-	}
1392
-
1393
-	elseif ($valeurs['format_source'] === 'svg') {
1394
-		if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)) {
1395
-			$format_sortie = 'svg';
1396
-			$vignette = $destination . '.' . $format_sortie;
1397
-			$valeurs['fichier_dest'] = $vignette;
1398
-			_image_gd_output($svg, $valeurs);
1399
-		}
1400
-	}
1401
-
1402
-	// imagemagick en ligne de commande
1403
-	elseif ($process == 'convert') {
1404
-		if (!defined('_CONVERT_COMMAND')) {
1405
-			define('_CONVERT_COMMAND', 'convert');
1406
-		} // Securite : mes_options.php peut preciser le chemin absolu
1407
-		if (!defined('_RESIZE_COMMAND')) {
1408
-			define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1409
-		}
1410
-		$vignette = $destination . '.' . $format_sortie;
1411
-		$commande = str_replace(
1412
-			['%x', '%y', '%src', '%dest'],
1413
-			[
1414
-				$destWidth,
1415
-				$destHeight,
1416
-				escapeshellcmd($image),
1417
-				escapeshellcmd($vignette)
1418
-			],
1419
-			_RESIZE_COMMAND
1420
-		);
1421
-		spip_log($commande);
1422
-		exec($commande);
1423
-		if (!@file_exists($vignette)) {
1424
-			spip_log("echec convert sur $vignette");
1425
-
1426
-			return;  // echec commande
1427
-		}
1428
-	}
1429
-
1430
-	// php5 imagemagick
1431
-	elseif ($process == 'imagick') {
1432
-
1433
-		if (!class_exists(\Imagick::class)) {
1434
-			spip_log('Classe Imagick absente !', _LOG_ERREUR);
1435
-
1436
-			return;
1437
-		}
1438
-
1439
-		// chemin compatible Windows
1440
-		$output = realpath(dirname($destination));
1441
-		if (!$output) {
1442
-			return;
1443
-		}
1444
-		$vignette = $output . DIRECTORY_SEPARATOR . basename($destination) . '.' . $format_sortie;
1445
-
1446
-		$imagick = new Imagick();
1447
-		$imagick->readImage(realpath($image));
1448
-		$imagick->resizeImage(
1449
-			$destWidth,
1450
-			$destHeight,
1451
-			Imagick::FILTER_LANCZOS,
1452
-			1
1453
-		);//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1454
-		$imagick->writeImage($vignette);
1455
-
1456
-		if (!@file_exists($vignette)) {
1457
-			spip_log("echec imagick sur $vignette");
1458
-
1459
-			return;
1460
-		}
1461
-		// remettre le chemin relatif car c'est ce qu'attend SPIP pour la suite (en particlier action/tester)
1462
-		$vignette = $destination . '.' . $format_sortie;
1463
-	}
1464
-
1465
-	// netpbm
1466
-	elseif ($process == 'netpbm') {
1467
-		if (!defined('_PNMSCALE_COMMAND')) {
1468
-			define('_PNMSCALE_COMMAND', 'pnmscale');
1469
-		} // Securite : mes_options.php peut preciser le chemin absolu
1470
-		if (_PNMSCALE_COMMAND == '') {
1471
-			return;
1472
-		}
1473
-		$vignette = $destination . '.' . $format_sortie;
1474
-		$pnmtojpeg_command = str_replace('pnmscale', 'pnmtojpeg', _PNMSCALE_COMMAND);
1475
-		if ($format == 'jpg') {
1476
-			$jpegtopnm_command = str_replace('pnmscale', 'jpegtopnm', _PNMSCALE_COMMAND);
1477
-			exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1478
-			if (!($s = @filesize($vignette))) {
1479
-				spip_unlink($vignette);
1480
-			}
1481
-			if (!@file_exists($vignette)) {
1482
-				spip_log("echec netpbm-jpg sur $vignette");
1483
-
1484
-				return;
1485
-			}
1486
-		} else {
1487
-			if ($format == 'gif') {
1488
-				$giftopnm_command = str_replace('pnmscale', 'giftopnm', _PNMSCALE_COMMAND);
1489
-				exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1490
-				if (!($s = @filesize($vignette))) {
1491
-					spip_unlink($vignette);
1492
-				}
1493
-				if (!@file_exists($vignette)) {
1494
-					spip_log("echec netpbm-gif sur $vignette");
1495
-
1496
-					return;
1497
-				}
1498
-			} else {
1499
-				if ($format == 'png') {
1500
-					$pngtopnm_command = str_replace('pnmscale', 'pngtopnm', _PNMSCALE_COMMAND);
1501
-					exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1502
-					if (!($s = @filesize($vignette))) {
1503
-						spip_unlink($vignette);
1504
-					}
1505
-					if (!@file_exists($vignette)) {
1506
-						spip_log("echec netpbm-png sur $vignette");
1507
-
1508
-						return;
1509
-					}
1510
-				}
1511
-			}
1512
-		}
1513
-	}
1514
-
1515
-	// gd ou gd2
1516
-	elseif ($process == 'gd1' or $process == 'gd2') {
1517
-		if (!function_exists('gd_info')) {
1518
-			spip_log('Librairie GD absente !', _LOG_ERREUR);
1519
-
1520
-			return;
1521
-		}
1522
-		if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1523
-			spip_log('vignette gd1/gd2 impossible : ' . $srcWidth * $srcHeight . 'pixels');
1524
-
1525
-			return;
1526
-		}
1527
-		$destFormat = $format_sortie;
1528
-		if (!$destFormat) {
1529
-			spip_log("pas de format pour $image");
1530
-
1531
-			return;
1532
-		}
1533
-
1534
-		$fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1535
-		if (!function_exists($fonction_imagecreatefrom)) {
1536
-			return;
1537
-		}
1538
-		$srcImage = @$fonction_imagecreatefrom($image);
1539
-		if (!$srcImage) {
1540
-			spip_log('echec gd1/gd2');
1541
-
1542
-			return;
1543
-		}
1544
-
1545
-		// Initialisation de l'image destination
1546
-		$destImage = null;
1547
-		if ($process == 'gd2' and $destFormat != 'gif') {
1548
-			$destImage = ImageCreateTrueColor($destWidth, $destHeight);
1549
-		}
1550
-		if (!$destImage) {
1551
-			$destImage = ImageCreate($destWidth, $destHeight);
1552
-		}
1553
-
1554
-		// Recopie de l'image d'origine avec adaptation de la taille
1555
-		$ok = false;
1556
-		if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1557
-			if ($format == 'gif') {
1558
-				// Si un GIF est transparent,
1559
-				// fabriquer un PNG transparent
1560
-				$transp = imagecolortransparent($srcImage);
1561
-				if ($transp > 0) {
1562
-					$destFormat = 'png';
1563
-				}
1564
-			}
1565
-			if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1566
-				// Conserver la transparence
1567
-				if (function_exists('imageAntiAlias')) {
1568
-					imageAntiAlias($destImage, true);
1569
-				}
1570
-				@imagealphablending($destImage, false);
1571
-				@imagesavealpha($destImage, true);
1572
-			}
1573
-			$ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1574
-		}
1575
-		if (!$ok) {
1576
-			$ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1577
-		}
1578
-
1579
-		// Sauvegarde de l'image destination
1580
-		$valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1581
-		$valeurs['format_dest'] = $format = $destFormat;
1582
-		_image_gd_output($destImage, $valeurs);
1583
-
1584
-		if ($srcImage) {
1585
-			ImageDestroy($srcImage);
1586
-		}
1587
-		ImageDestroy($destImage);
1588
-	}
1589
-
1590
-	if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1591
-		$size = [$destWidth, $destHeight];
1592
-	}
1593
-
1594
-	// Gaffe: en safe mode, pas d'acces a la vignette,
1595
-	// donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1596
-	if ($size[0] < 1) {
1597
-		$size[0] = $destWidth;
1598
-	}
1599
-	if ($size[1] < 1) {
1600
-		$size[1] = $destHeight;
1601
-	}
1602
-
1603
-	$retour['width'] = $largeur = $size[0];
1604
-	$retour['height'] = $hauteur = $size[1];
1605
-
1606
-	$retour['fichier'] = $vignette;
1607
-	$retour['format'] = $format;
1608
-	$retour['date'] = @filemtime($vignette);
1609
-
1610
-	// renvoyer l'image
1611
-	return $retour;
1350
+    $srcHeight = null;
1351
+    $retour = [];
1352
+    // ordre de preference des formats graphiques pour creer les vignettes
1353
+    // le premier format disponible, selon la methode demandee, est utilise
1354
+    $image = $valeurs['fichier'];
1355
+    $format = $valeurs['format_source'];
1356
+    $destdir = dirname($valeurs['fichier_dest']);
1357
+    $destfile = basename($valeurs['fichier_dest'], '.' . $valeurs['format_dest']);
1358
+
1359
+    $format_sortie = $valeurs['format_dest'];
1360
+
1361
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1362
+        $process = $GLOBALS['meta']['image_process'];
1363
+    }
1364
+
1365
+    // si le doc n'est pas une image dans un format accetpable, refuser
1366
+    if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1367
+        return;
1368
+    }
1369
+    $destination = "$destdir/$destfile";
1370
+
1371
+    // calculer la taille
1372
+    if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1373
+        if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1374
+            [$destWidth, $destHeight] = _image_ratio($srcWidth, $srcHeight, $maxWidth, $maxHeight);
1375
+        }
1376
+    } elseif ($process == 'convert' or $process == 'imagick') {
1377
+        $destWidth = $maxWidth;
1378
+        $destHeight = $maxHeight;
1379
+    } else {
1380
+        spip_log("echec $process sur $image");
1381
+
1382
+        return;
1383
+    }
1384
+
1385
+    $vignette = '';
1386
+
1387
+    // Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1388
+    if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1389
+        $vignette = $destination . '.' . $format;
1390
+        @copy($image, $vignette);
1391
+    }
1392
+
1393
+    elseif ($valeurs['format_source'] === 'svg') {
1394
+        if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)) {
1395
+            $format_sortie = 'svg';
1396
+            $vignette = $destination . '.' . $format_sortie;
1397
+            $valeurs['fichier_dest'] = $vignette;
1398
+            _image_gd_output($svg, $valeurs);
1399
+        }
1400
+    }
1401
+
1402
+    // imagemagick en ligne de commande
1403
+    elseif ($process == 'convert') {
1404
+        if (!defined('_CONVERT_COMMAND')) {
1405
+            define('_CONVERT_COMMAND', 'convert');
1406
+        } // Securite : mes_options.php peut preciser le chemin absolu
1407
+        if (!defined('_RESIZE_COMMAND')) {
1408
+            define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1409
+        }
1410
+        $vignette = $destination . '.' . $format_sortie;
1411
+        $commande = str_replace(
1412
+            ['%x', '%y', '%src', '%dest'],
1413
+            [
1414
+                $destWidth,
1415
+                $destHeight,
1416
+                escapeshellcmd($image),
1417
+                escapeshellcmd($vignette)
1418
+            ],
1419
+            _RESIZE_COMMAND
1420
+        );
1421
+        spip_log($commande);
1422
+        exec($commande);
1423
+        if (!@file_exists($vignette)) {
1424
+            spip_log("echec convert sur $vignette");
1425
+
1426
+            return;  // echec commande
1427
+        }
1428
+    }
1429
+
1430
+    // php5 imagemagick
1431
+    elseif ($process == 'imagick') {
1432
+
1433
+        if (!class_exists(\Imagick::class)) {
1434
+            spip_log('Classe Imagick absente !', _LOG_ERREUR);
1435
+
1436
+            return;
1437
+        }
1438
+
1439
+        // chemin compatible Windows
1440
+        $output = realpath(dirname($destination));
1441
+        if (!$output) {
1442
+            return;
1443
+        }
1444
+        $vignette = $output . DIRECTORY_SEPARATOR . basename($destination) . '.' . $format_sortie;
1445
+
1446
+        $imagick = new Imagick();
1447
+        $imagick->readImage(realpath($image));
1448
+        $imagick->resizeImage(
1449
+            $destWidth,
1450
+            $destHeight,
1451
+            Imagick::FILTER_LANCZOS,
1452
+            1
1453
+        );//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1454
+        $imagick->writeImage($vignette);
1455
+
1456
+        if (!@file_exists($vignette)) {
1457
+            spip_log("echec imagick sur $vignette");
1458
+
1459
+            return;
1460
+        }
1461
+        // remettre le chemin relatif car c'est ce qu'attend SPIP pour la suite (en particlier action/tester)
1462
+        $vignette = $destination . '.' . $format_sortie;
1463
+    }
1464
+
1465
+    // netpbm
1466
+    elseif ($process == 'netpbm') {
1467
+        if (!defined('_PNMSCALE_COMMAND')) {
1468
+            define('_PNMSCALE_COMMAND', 'pnmscale');
1469
+        } // Securite : mes_options.php peut preciser le chemin absolu
1470
+        if (_PNMSCALE_COMMAND == '') {
1471
+            return;
1472
+        }
1473
+        $vignette = $destination . '.' . $format_sortie;
1474
+        $pnmtojpeg_command = str_replace('pnmscale', 'pnmtojpeg', _PNMSCALE_COMMAND);
1475
+        if ($format == 'jpg') {
1476
+            $jpegtopnm_command = str_replace('pnmscale', 'jpegtopnm', _PNMSCALE_COMMAND);
1477
+            exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1478
+            if (!($s = @filesize($vignette))) {
1479
+                spip_unlink($vignette);
1480
+            }
1481
+            if (!@file_exists($vignette)) {
1482
+                spip_log("echec netpbm-jpg sur $vignette");
1483
+
1484
+                return;
1485
+            }
1486
+        } else {
1487
+            if ($format == 'gif') {
1488
+                $giftopnm_command = str_replace('pnmscale', 'giftopnm', _PNMSCALE_COMMAND);
1489
+                exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1490
+                if (!($s = @filesize($vignette))) {
1491
+                    spip_unlink($vignette);
1492
+                }
1493
+                if (!@file_exists($vignette)) {
1494
+                    spip_log("echec netpbm-gif sur $vignette");
1495
+
1496
+                    return;
1497
+                }
1498
+            } else {
1499
+                if ($format == 'png') {
1500
+                    $pngtopnm_command = str_replace('pnmscale', 'pngtopnm', _PNMSCALE_COMMAND);
1501
+                    exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1502
+                    if (!($s = @filesize($vignette))) {
1503
+                        spip_unlink($vignette);
1504
+                    }
1505
+                    if (!@file_exists($vignette)) {
1506
+                        spip_log("echec netpbm-png sur $vignette");
1507
+
1508
+                        return;
1509
+                    }
1510
+                }
1511
+            }
1512
+        }
1513
+    }
1514
+
1515
+    // gd ou gd2
1516
+    elseif ($process == 'gd1' or $process == 'gd2') {
1517
+        if (!function_exists('gd_info')) {
1518
+            spip_log('Librairie GD absente !', _LOG_ERREUR);
1519
+
1520
+            return;
1521
+        }
1522
+        if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1523
+            spip_log('vignette gd1/gd2 impossible : ' . $srcWidth * $srcHeight . 'pixels');
1524
+
1525
+            return;
1526
+        }
1527
+        $destFormat = $format_sortie;
1528
+        if (!$destFormat) {
1529
+            spip_log("pas de format pour $image");
1530
+
1531
+            return;
1532
+        }
1533
+
1534
+        $fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1535
+        if (!function_exists($fonction_imagecreatefrom)) {
1536
+            return;
1537
+        }
1538
+        $srcImage = @$fonction_imagecreatefrom($image);
1539
+        if (!$srcImage) {
1540
+            spip_log('echec gd1/gd2');
1541
+
1542
+            return;
1543
+        }
1544
+
1545
+        // Initialisation de l'image destination
1546
+        $destImage = null;
1547
+        if ($process == 'gd2' and $destFormat != 'gif') {
1548
+            $destImage = ImageCreateTrueColor($destWidth, $destHeight);
1549
+        }
1550
+        if (!$destImage) {
1551
+            $destImage = ImageCreate($destWidth, $destHeight);
1552
+        }
1553
+
1554
+        // Recopie de l'image d'origine avec adaptation de la taille
1555
+        $ok = false;
1556
+        if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1557
+            if ($format == 'gif') {
1558
+                // Si un GIF est transparent,
1559
+                // fabriquer un PNG transparent
1560
+                $transp = imagecolortransparent($srcImage);
1561
+                if ($transp > 0) {
1562
+                    $destFormat = 'png';
1563
+                }
1564
+            }
1565
+            if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1566
+                // Conserver la transparence
1567
+                if (function_exists('imageAntiAlias')) {
1568
+                    imageAntiAlias($destImage, true);
1569
+                }
1570
+                @imagealphablending($destImage, false);
1571
+                @imagesavealpha($destImage, true);
1572
+            }
1573
+            $ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1574
+        }
1575
+        if (!$ok) {
1576
+            $ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1577
+        }
1578
+
1579
+        // Sauvegarde de l'image destination
1580
+        $valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1581
+        $valeurs['format_dest'] = $format = $destFormat;
1582
+        _image_gd_output($destImage, $valeurs);
1583
+
1584
+        if ($srcImage) {
1585
+            ImageDestroy($srcImage);
1586
+        }
1587
+        ImageDestroy($destImage);
1588
+    }
1589
+
1590
+    if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1591
+        $size = [$destWidth, $destHeight];
1592
+    }
1593
+
1594
+    // Gaffe: en safe mode, pas d'acces a la vignette,
1595
+    // donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1596
+    if ($size[0] < 1) {
1597
+        $size[0] = $destWidth;
1598
+    }
1599
+    if ($size[1] < 1) {
1600
+        $size[1] = $destHeight;
1601
+    }
1602
+
1603
+    $retour['width'] = $largeur = $size[0];
1604
+    $retour['height'] = $hauteur = $size[1];
1605
+
1606
+    $retour['fichier'] = $vignette;
1607
+    $retour['format'] = $format;
1608
+    $retour['date'] = @filemtime($vignette);
1609
+
1610
+    // renvoyer l'image
1611
+    return $retour;
1612 1612
 }
1613 1613
 
1614 1614
 /**
@@ -1628,25 +1628,25 @@  discard block
 block discarded – undo
1628 1628
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1629 1629
  **/
1630 1630
 function _image_ratio(int $srcWidth, int $srcHeight, int $maxWidth, int $maxHeight): array {
1631
-	$ratioWidth = $srcWidth / $maxWidth;
1632
-	$ratioHeight = $srcHeight / $maxHeight;
1633
-
1634
-	if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1635
-		$destWidth = $srcWidth;
1636
-		$destHeight = $srcHeight;
1637
-	} elseif ($ratioWidth < $ratioHeight) {
1638
-		$destWidth = $srcWidth / $ratioHeight;
1639
-		$destHeight = $maxHeight;
1640
-	} else {
1641
-		$destWidth = $maxWidth;
1642
-		$destHeight = $srcHeight / $ratioWidth;
1643
-	}
1644
-
1645
-	return [
1646
-		intval(round($destWidth)),
1647
-		intval(round($destHeight)),
1648
-		max($ratioWidth, $ratioHeight)
1649
-	];
1631
+    $ratioWidth = $srcWidth / $maxWidth;
1632
+    $ratioHeight = $srcHeight / $maxHeight;
1633
+
1634
+    if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1635
+        $destWidth = $srcWidth;
1636
+        $destHeight = $srcHeight;
1637
+    } elseif ($ratioWidth < $ratioHeight) {
1638
+        $destWidth = $srcWidth / $ratioHeight;
1639
+        $destHeight = $maxHeight;
1640
+    } else {
1641
+        $destWidth = $maxWidth;
1642
+        $destHeight = $srcHeight / $ratioWidth;
1643
+    }
1644
+
1645
+    return [
1646
+        intval(round($destWidth)),
1647
+        intval(round($destHeight)),
1648
+        max($ratioWidth, $ratioHeight)
1649
+    ];
1650 1650
 }
1651 1651
 
1652 1652
 /**
@@ -1666,25 +1666,25 @@  discard block
 block discarded – undo
1666 1666
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1667 1667
  **/
1668 1668
 function ratio_passe_partout(int $srcWidth, int $srcHeight, int $maxWidth, int $maxHeight): array {
1669
-	$ratioWidth = $srcWidth / $maxWidth;
1670
-	$ratioHeight = $srcHeight / $maxHeight;
1671
-
1672
-	if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1673
-		$destWidth = $srcWidth;
1674
-		$destHeight = $srcHeight;
1675
-	} elseif ($ratioWidth > $ratioHeight) {
1676
-		$destWidth = $srcWidth / $ratioHeight;
1677
-		$destHeight = $maxHeight;
1678
-	} else {
1679
-		$destWidth = $maxWidth;
1680
-		$destHeight = $srcHeight / $ratioWidth;
1681
-	}
1682
-
1683
-	return [
1684
-		intval(round($destWidth)),
1685
-		intval(round($destHeight)),
1686
-		min($ratioWidth, $ratioHeight)
1687
-	];
1669
+    $ratioWidth = $srcWidth / $maxWidth;
1670
+    $ratioHeight = $srcHeight / $maxHeight;
1671
+
1672
+    if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1673
+        $destWidth = $srcWidth;
1674
+        $destHeight = $srcHeight;
1675
+    } elseif ($ratioWidth > $ratioHeight) {
1676
+        $destWidth = $srcWidth / $ratioHeight;
1677
+        $destHeight = $maxHeight;
1678
+    } else {
1679
+        $destWidth = $maxWidth;
1680
+        $destHeight = $srcHeight / $ratioWidth;
1681
+    }
1682
+
1683
+    return [
1684
+        intval(round($destWidth)),
1685
+        intval(round($destHeight)),
1686
+        min($ratioWidth, $ratioHeight)
1687
+    ];
1688 1688
 }
1689 1689
 
1690 1690
 
@@ -1697,12 +1697,12 @@  discard block
 block discarded – undo
1697 1697
  * @return string
1698 1698
  */
1699 1699
 function process_image_svg_identite($image) {
1700
-	if ($image['creer']) {
1701
-		$source = $image['fichier'];
1702
-		_image_gd_output($source, $image);
1703
-	}
1700
+    if ($image['creer']) {
1701
+        $source = $image['fichier'];
1702
+        _image_gd_output($source, $image);
1703
+    }
1704 1704
 
1705
-	return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1705
+    return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1706 1706
 }
1707 1707
 
1708 1708
 
@@ -1735,109 +1735,109 @@  discard block
 block discarded – undo
1735 1735
  *     Code HTML de la balise img produite
1736 1736
  **/
1737 1737
 function process_image_reduire($fonction, $img, $taille, $taille_y, $force, $process = 'AUTO') {
1738
-	$image = false;
1739
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1740
-		$process = $GLOBALS['meta']['image_process'];
1741
-	}
1742
-	# determiner le format de sortie
1743
-	$format_sortie = false; // le choix par defaut sera bon
1744
-	if ($process == 'netpbm') {
1745
-		$format_sortie = 'jpg';
1746
-	} elseif ($process == 'gd1' or $process == 'gd2') {
1747
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1748
-		// on verifie que l'extension choisie est bonne (en principe oui)
1749
-		$gd_formats = formats_image_acceptables(true);
1750
-		if (
1751
-			is_array($image)
1752
-			and (!in_array($image['format_dest'], $gd_formats)
1753
-				or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1754
-			)
1755
-		) {
1756
-			if ($image['format_source'] == 'jpg') {
1757
-				$formats_sortie = ['jpg', 'png', 'gif'];
1758
-			} else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1759
-			{
1760
-				$formats_sortie = ['png', 'jpg', 'gif'];
1761
-			}
1762
-			// Choisir le format destination
1763
-			// - on sauve de preference en JPEG (meilleure compression)
1764
-			// - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1765
-			# bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1766
-			# pas *ecrire*
1767
-			$format_sortie = '';
1768
-			foreach ($formats_sortie as $fmt) {
1769
-				if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1770
-					$format_sortie = $fmt;
1771
-					break;
1772
-				}
1773
-			}
1774
-			$image = false;
1775
-		}
1776
-	}
1777
-
1778
-	if (!is_array($image)) {
1779
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1780
-	}
1781
-
1782
-	if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1783
-		spip_log("image_reduire_src:pas de version locale de $img ou extension non prise en charge");
1784
-		// on peut resizer en mode html si on dispose des elements
1785
-		[$srcw, $srch] = taille_image($img);
1786
-		if ($srcw and $srch) {
1787
-			[$w, $h] = _image_ratio($srcw, $srch, $taille, $taille_y);
1788
-
1789
-			return _image_tag_changer_taille($img, $w, $h);
1790
-		}
1791
-		// la on n'a pas d'infos sur l'image source... on refile le truc a css
1792
-		// sous la forme style='max-width: NNpx;'
1793
-		return inserer_attribut(
1794
-			$img,
1795
-			'style',
1796
-			"max-width: ${taille}px;max-width: min(100%,${taille}px); max-height: ${taille_y}px"
1797
-		);
1798
-	}
1799
-
1800
-	// si l'image est plus petite que la cible retourner une copie cachee de l'image
1801
-	if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1802
-		if ($image['creer']) {
1803
-			@copy($image['fichier'], $image['fichier_dest']);
1804
-		}
1805
-
1806
-		return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1807
-	}
1808
-
1809
-	if ($image['creer'] == false && !$force) {
1810
-		return _image_ecrire_tag(
1811
-			$image,
1812
-			['src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']]
1813
-		);
1814
-	}
1815
-
1816
-	if (in_array($image['format_source'], _image_extensions_acceptees_en_entree())) {
1817
-		$destWidth = $image['largeur_dest'];
1818
-		$destHeight = $image['hauteur_dest'];
1819
-		$logo = $image['fichier'];
1820
-		$date = $image['date_src'];
1821
-		$preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1822
-
1823
-		if ($preview && $preview['fichier']) {
1824
-			$logo = $preview['fichier'];
1825
-			$destWidth = $preview['width'];
1826
-			$destHeight = $preview['height'];
1827
-			$date = $preview['date'];
1828
-		}
1829
-		// dans l'espace prive mettre un timestamp sur l'adresse
1830
-		// de l'image, de facon a tromper le cache du navigateur
1831
-		// quand on fait supprimer/reuploader un logo
1832
-		// (pas de filemtime si SAFE MODE)
1833
-		$date = test_espace_prive() ? ('?' . $date) : '';
1834
-
1835
-		return _image_ecrire_tag($image, ['src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight]);
1836
-	}
1837
-	else {
1838
-		# BMP, tiff ... les redacteurs osent tout!
1839
-		return $img;
1840
-	}
1738
+    $image = false;
1739
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1740
+        $process = $GLOBALS['meta']['image_process'];
1741
+    }
1742
+    # determiner le format de sortie
1743
+    $format_sortie = false; // le choix par defaut sera bon
1744
+    if ($process == 'netpbm') {
1745
+        $format_sortie = 'jpg';
1746
+    } elseif ($process == 'gd1' or $process == 'gd2') {
1747
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1748
+        // on verifie que l'extension choisie est bonne (en principe oui)
1749
+        $gd_formats = formats_image_acceptables(true);
1750
+        if (
1751
+            is_array($image)
1752
+            and (!in_array($image['format_dest'], $gd_formats)
1753
+                or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1754
+            )
1755
+        ) {
1756
+            if ($image['format_source'] == 'jpg') {
1757
+                $formats_sortie = ['jpg', 'png', 'gif'];
1758
+            } else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1759
+            {
1760
+                $formats_sortie = ['png', 'jpg', 'gif'];
1761
+            }
1762
+            // Choisir le format destination
1763
+            // - on sauve de preference en JPEG (meilleure compression)
1764
+            // - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1765
+            # bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1766
+            # pas *ecrire*
1767
+            $format_sortie = '';
1768
+            foreach ($formats_sortie as $fmt) {
1769
+                if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1770
+                    $format_sortie = $fmt;
1771
+                    break;
1772
+                }
1773
+            }
1774
+            $image = false;
1775
+        }
1776
+    }
1777
+
1778
+    if (!is_array($image)) {
1779
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1780
+    }
1781
+
1782
+    if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1783
+        spip_log("image_reduire_src:pas de version locale de $img ou extension non prise en charge");
1784
+        // on peut resizer en mode html si on dispose des elements
1785
+        [$srcw, $srch] = taille_image($img);
1786
+        if ($srcw and $srch) {
1787
+            [$w, $h] = _image_ratio($srcw, $srch, $taille, $taille_y);
1788
+
1789
+            return _image_tag_changer_taille($img, $w, $h);
1790
+        }
1791
+        // la on n'a pas d'infos sur l'image source... on refile le truc a css
1792
+        // sous la forme style='max-width: NNpx;'
1793
+        return inserer_attribut(
1794
+            $img,
1795
+            'style',
1796
+            "max-width: ${taille}px;max-width: min(100%,${taille}px); max-height: ${taille_y}px"
1797
+        );
1798
+    }
1799
+
1800
+    // si l'image est plus petite que la cible retourner une copie cachee de l'image
1801
+    if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1802
+        if ($image['creer']) {
1803
+            @copy($image['fichier'], $image['fichier_dest']);
1804
+        }
1805
+
1806
+        return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1807
+    }
1808
+
1809
+    if ($image['creer'] == false && !$force) {
1810
+        return _image_ecrire_tag(
1811
+            $image,
1812
+            ['src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']]
1813
+        );
1814
+    }
1815
+
1816
+    if (in_array($image['format_source'], _image_extensions_acceptees_en_entree())) {
1817
+        $destWidth = $image['largeur_dest'];
1818
+        $destHeight = $image['hauteur_dest'];
1819
+        $logo = $image['fichier'];
1820
+        $date = $image['date_src'];
1821
+        $preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1822
+
1823
+        if ($preview && $preview['fichier']) {
1824
+            $logo = $preview['fichier'];
1825
+            $destWidth = $preview['width'];
1826
+            $destHeight = $preview['height'];
1827
+            $date = $preview['date'];
1828
+        }
1829
+        // dans l'espace prive mettre un timestamp sur l'adresse
1830
+        // de l'image, de facon a tromper le cache du navigateur
1831
+        // quand on fait supprimer/reuploader un logo
1832
+        // (pas de filemtime si SAFE MODE)
1833
+        $date = test_espace_prive() ? ('?' . $date) : '';
1834
+
1835
+        return _image_ecrire_tag($image, ['src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight]);
1836
+    }
1837
+    else {
1838
+        # BMP, tiff ... les redacteurs osent tout!
1839
+        return $img;
1840
+    }
1841 1841
 }
1842 1842
 
1843 1843
 /**
@@ -1851,145 +1851,145 @@  discard block
 block discarded – undo
1851 1851
  * Class phpthumb_functions
1852 1852
  */
1853 1853
 class phpthumb_functions {
1854
-	/**
1855
-	 * Retourne la couleur d'un pixel dans une image
1856
-	 *
1857
-	 * @param resource|GdImage $img
1858
-	 * @param int $x
1859
-	 * @param int $y
1860
-	 * @return array|bool
1861
-	 */
1862
-	public static function GetPixelColor(&$img, $x, $y) {
1863
-		if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1864
-			return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1865
-		}
1866
-		return false;
1867
-	}
1868
-
1869
-	/**
1870
-	 * Retourne un nombre dans une représentation en Little Endian
1871
-	 *
1872
-	 * @param int $number
1873
-	 * @param int $minbytes
1874
-	 * @return string
1875
-	 */
1876
-	public static function LittleEndian2String($number, $minbytes = 1) {
1877
-		$intstring = '';
1878
-		while ($number > 0) {
1879
-			$intstring = $intstring . chr($number & 255);
1880
-			$number >>= 8;
1881
-		}
1882
-
1883
-		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1884
-	}
1885
-
1886
-	/**
1887
-	 * Transforme une ressource GD en image au format ICO
1888
-	 *
1889
-	 * @param array $gd_image_array
1890
-	 *     Tableau de ressources d'images GD
1891
-	 * @return string
1892
-	 *     Image au format ICO
1893
-	 */
1894
-	public static function GD2ICOstring(&$gd_image_array) {
1895
-		foreach ($gd_image_array as $key => $gd_image) {
1896
-			$ImageWidths[$key] = ImageSX($gd_image);
1897
-			$ImageHeights[$key] = ImageSY($gd_image);
1898
-			$bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1899
-			$totalcolors[$key] = ImageColorsTotal($gd_image);
1900
-
1901
-			$icXOR[$key] = '';
1902
-			for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1903
-				for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1904
-					$argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1905
-					$a = round(255 * ((127 - $argb['alpha']) / 127));
1906
-					$r = $argb['red'];
1907
-					$g = $argb['green'];
1908
-					$b = $argb['blue'];
1909
-
1910
-					if ($bpp[$key] == 32) {
1911
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1912
-					} elseif ($bpp[$key] == 24) {
1913
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r);
1914
-					}
1915
-
1916
-					if ($a < 128) {
1917
-						@$icANDmask[$key][$y] .= '1';
1918
-					} else {
1919
-						@$icANDmask[$key][$y] .= '0';
1920
-					}
1921
-				}
1922
-				// mask bits are 32-bit aligned per scanline
1923
-				while (strlen($icANDmask[$key][$y]) % 32) {
1924
-					$icANDmask[$key][$y] .= '0';
1925
-				}
1926
-			}
1927
-			$icAND[$key] = '';
1928
-			foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1929
-				for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1930
-					$icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1931
-				}
1932
-			}
1933
-		}
1934
-
1935
-		foreach ($gd_image_array as $key => $gd_image) {
1936
-			$biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1937
-
1938
-			// BITMAPINFOHEADER - 40 bytes
1939
-			$BitmapInfoHeader[$key] = '';
1940
-			$BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1941
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1942
-			// The biHeight member specifies the combined
1943
-			// height of the XOR and AND masks.
1944
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1945
-			$BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1946
-			$BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1947
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1948
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1949
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1950
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1951
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1952
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1953
-		}
1954
-
1955
-
1956
-		$icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1957
-		$icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1958
-		$icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1959
-
1960
-		$dwImageOffset = 6 + (count($gd_image_array) * 16);
1961
-		foreach ($gd_image_array as $key => $gd_image) {
1962
-			// ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1963
-
1964
-			$icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1965
-			$icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1966
-			$icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1967
-			$icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1968
-
1969
-			$icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
1970
-			$icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
1971
-
1972
-			$dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
1973
-			$icondata .= phpthumb_functions::LittleEndian2String(
1974
-				$dwBytesInRes,
1975
-				4
1976
-			);     // dwBytesInRes;	// How many bytes in this resource?
1977
-
1978
-			$icondata .= phpthumb_functions::LittleEndian2String(
1979
-				$dwImageOffset,
1980
-				4
1981
-			);    // dwImageOffset;   // Where in the file is this image?
1982
-			$dwImageOffset += strlen($BitmapInfoHeader[$key]);
1983
-			$dwImageOffset += strlen($icXOR[$key]);
1984
-			$dwImageOffset += strlen($icAND[$key]);
1985
-		}
1986
-
1987
-		foreach ($gd_image_array as $key => $gd_image) {
1988
-			$icondata .= $BitmapInfoHeader[$key];
1989
-			$icondata .= $icXOR[$key];
1990
-			$icondata .= $icAND[$key];
1991
-		}
1992
-
1993
-		return $icondata;
1994
-	}
1854
+    /**
1855
+     * Retourne la couleur d'un pixel dans une image
1856
+     *
1857
+     * @param resource|GdImage $img
1858
+     * @param int $x
1859
+     * @param int $y
1860
+     * @return array|bool
1861
+     */
1862
+    public static function GetPixelColor(&$img, $x, $y) {
1863
+        if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1864
+            return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1865
+        }
1866
+        return false;
1867
+    }
1868
+
1869
+    /**
1870
+     * Retourne un nombre dans une représentation en Little Endian
1871
+     *
1872
+     * @param int $number
1873
+     * @param int $minbytes
1874
+     * @return string
1875
+     */
1876
+    public static function LittleEndian2String($number, $minbytes = 1) {
1877
+        $intstring = '';
1878
+        while ($number > 0) {
1879
+            $intstring = $intstring . chr($number & 255);
1880
+            $number >>= 8;
1881
+        }
1882
+
1883
+        return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1884
+    }
1885
+
1886
+    /**
1887
+     * Transforme une ressource GD en image au format ICO
1888
+     *
1889
+     * @param array $gd_image_array
1890
+     *     Tableau de ressources d'images GD
1891
+     * @return string
1892
+     *     Image au format ICO
1893
+     */
1894
+    public static function GD2ICOstring(&$gd_image_array) {
1895
+        foreach ($gd_image_array as $key => $gd_image) {
1896
+            $ImageWidths[$key] = ImageSX($gd_image);
1897
+            $ImageHeights[$key] = ImageSY($gd_image);
1898
+            $bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1899
+            $totalcolors[$key] = ImageColorsTotal($gd_image);
1900
+
1901
+            $icXOR[$key] = '';
1902
+            for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1903
+                for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1904
+                    $argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1905
+                    $a = round(255 * ((127 - $argb['alpha']) / 127));
1906
+                    $r = $argb['red'];
1907
+                    $g = $argb['green'];
1908
+                    $b = $argb['blue'];
1909
+
1910
+                    if ($bpp[$key] == 32) {
1911
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1912
+                    } elseif ($bpp[$key] == 24) {
1913
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r);
1914
+                    }
1915
+
1916
+                    if ($a < 128) {
1917
+                        @$icANDmask[$key][$y] .= '1';
1918
+                    } else {
1919
+                        @$icANDmask[$key][$y] .= '0';
1920
+                    }
1921
+                }
1922
+                // mask bits are 32-bit aligned per scanline
1923
+                while (strlen($icANDmask[$key][$y]) % 32) {
1924
+                    $icANDmask[$key][$y] .= '0';
1925
+                }
1926
+            }
1927
+            $icAND[$key] = '';
1928
+            foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1929
+                for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1930
+                    $icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1931
+                }
1932
+            }
1933
+        }
1934
+
1935
+        foreach ($gd_image_array as $key => $gd_image) {
1936
+            $biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1937
+
1938
+            // BITMAPINFOHEADER - 40 bytes
1939
+            $BitmapInfoHeader[$key] = '';
1940
+            $BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1941
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1942
+            // The biHeight member specifies the combined
1943
+            // height of the XOR and AND masks.
1944
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1945
+            $BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1946
+            $BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1947
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1948
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1949
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1950
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1951
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1952
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1953
+        }
1954
+
1955
+
1956
+        $icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1957
+        $icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1958
+        $icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1959
+
1960
+        $dwImageOffset = 6 + (count($gd_image_array) * 16);
1961
+        foreach ($gd_image_array as $key => $gd_image) {
1962
+            // ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1963
+
1964
+            $icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1965
+            $icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1966
+            $icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1967
+            $icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1968
+
1969
+            $icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
1970
+            $icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
1971
+
1972
+            $dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
1973
+            $icondata .= phpthumb_functions::LittleEndian2String(
1974
+                $dwBytesInRes,
1975
+                4
1976
+            );     // dwBytesInRes;	// How many bytes in this resource?
1977
+
1978
+            $icondata .= phpthumb_functions::LittleEndian2String(
1979
+                $dwImageOffset,
1980
+                4
1981
+            );    // dwImageOffset;   // Where in the file is this image?
1982
+            $dwImageOffset += strlen($BitmapInfoHeader[$key]);
1983
+            $dwImageOffset += strlen($icXOR[$key]);
1984
+            $dwImageOffset += strlen($icAND[$key]);
1985
+        }
1986
+
1987
+        foreach ($gd_image_array as $key => $gd_image) {
1988
+            $icondata .= $BitmapInfoHeader[$key];
1989
+            $icondata .= $icXOR[$key];
1990
+            $icondata .= $icAND[$key];
1991
+        }
1992
+
1993
+        return $icondata;
1994
+    }
1995 1995
 }
Please login to merge, or discard this patch.