Completed
Push — master ( 2ca868...d39161 )
by cam
08:10 queued 03:16
created
ecrire/inc/filtres_images_lib_mini.php 3 patches
Doc Comments   +5 added lines, -3 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
  *
88 88
  * @param bool|string $stat
89 89
  *     true, false ou le statut déjà défini si traitements enchaînés.
90
- * @return bool
90
+ * @return false|null
91 91
  *     true si il faut supprimer le fichier temporaire ; false sinon.
92 92
  */
93 93
 function statut_effacer_images_temporaires($stat) {
@@ -367,7 +367,6 @@  discard block
 block discarded – undo
367 367
 
368 368
 
369 369
 /**
370
- * @param string $quoi
371 370
  * @return array
372 371
  */
373 372
 function _image_extensions_acceptees_en_entree() {
@@ -405,6 +404,9 @@  discard block
 block discarded – undo
405 404
 	return $extensions;
406 405
 }
407 406
 
407
+/**
408
+ * @param string $extension
409
+ */
408 410
 function _image_extension_normalisee($extension){
409 411
 	$extension = strtolower($extension);
410 412
 	if ($extension === 'jpeg') {
@@ -1703,7 +1705,7 @@  discard block
 block discarded – undo
1703 1705
 	/**
1704 1706
 	 * Transforme une ressource GD en image au format ICO
1705 1707
 	 *
1706
-	 * @param array $gd_image_array
1708
+	 * @param resource[] $gd_image_array
1707 1709
 	 *     Tableau de ressources d'images GD
1708 1710
 	 * @return string
1709 1711
 	 *     Image au format ICO
Please login to merge, or discard this patch.
Indentation   +1217 added lines, -1217 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 
20 20
 
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	return;
22
+    return;
23 23
 }
24 24
 include_spip('inc/filtres'); // par precaution
25 25
 include_spip('inc/filtres_images_mini'); // par precaution
@@ -39,21 +39,21 @@  discard block
 block discarded – undo
39 39
  *     Le code de la couleur en hexadécimal.
40 40
  */
41 41
 function _couleur_dec_to_hex($red, $green, $blue) {
42
-	$red = dechex($red);
43
-	$green = dechex($green);
44
-	$blue = dechex($blue);
45
-
46
-	if (strlen($red) == 1) {
47
-		$red = "0" . $red;
48
-	}
49
-	if (strlen($green) == 1) {
50
-		$green = "0" . $green;
51
-	}
52
-	if (strlen($blue) == 1) {
53
-		$blue = "0" . $blue;
54
-	}
55
-
56
-	return "$red$green$blue";
42
+    $red = dechex($red);
43
+    $green = dechex($green);
44
+    $blue = dechex($blue);
45
+
46
+    if (strlen($red) == 1) {
47
+        $red = "0" . $red;
48
+    }
49
+    if (strlen($green) == 1) {
50
+        $green = "0" . $green;
51
+    }
52
+    if (strlen($blue) == 1) {
53
+        $blue = "0" . $blue;
54
+    }
55
+
56
+    return "$red$green$blue";
57 57
 }
58 58
 
59 59
 /**
@@ -65,16 +65,16 @@  discard block
 block discarded – undo
65 65
  *     Un tableau des 3 éléments : rouge, vert, bleu.
66 66
  */
67 67
 function _couleur_hex_to_dec($couleur) {
68
-	$couleur = couleur_html_to_hex($couleur);
69
-	$couleur = ltrim($couleur, '#');
70
-	if (strlen($couleur) === 3) {
71
-		$couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
72
-	}
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;
68
+    $couleur = couleur_html_to_hex($couleur);
69
+    $couleur = ltrim($couleur, '#');
70
+    if (strlen($couleur) === 3) {
71
+        $couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
72
+    }
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,11 +91,11 @@  discard block
 block discarded – undo
91 91
  *     true si il faut supprimer le fichier temporaire ; false sinon.
92 92
  */
93 93
 function statut_effacer_images_temporaires($stat) {
94
-	static $statut = false; // par defaut on grave toute les images
95
-	if ($stat === 'get') {
96
-		return $statut;
97
-	}
98
-	$statut = $stat ? true : false;
94
+    static $statut = false; // par defaut on grave toute les images
95
+    if ($stat === 'get') {
96
+        return $statut;
97
+    }
98
+    $statut = $stat ? true : false;
99 99
 }
100 100
 
101 101
 
@@ -145,224 +145,224 @@  discard block
 block discarded – undo
145 145
  *     - array : tableau décrivant de l'image
146 146
  */
147 147
 function _image_valeurs_trans($img, $effet, $forcer_format = false, $fonction_creation = null, $find_in_path = false, $support_svg = false) {
148
-	static $images_recalcul = array();
149
-	if (strlen($img) == 0) {
150
-		return false;
151
-	}
152
-
153
-	$source = trim(extraire_attribut($img, 'src'));
154
-	if (strlen($source) < 1) {
155
-		$source = $img;
156
-		$img = "<img src='$source' />";
157
-	} # gerer img src="data:....base64"
158
-	elseif (preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
159
-	  and $extension = _image_trouver_extension_depuis_mime("image/".$regs[1])
160
-		and in_array($extension, _image_extensions_acceptees_en_entree())
161
-	) {
162
-		$local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
163
-		if (!file_exists($local)) {
164
-			ecrire_fichier($local, base64_decode($regs[2]));
165
-		}
166
-		$source = $local;
167
-		$img = inserer_attribut($img, 'src', $source);
168
-		# eviter les mauvaises surprises lors de conversions de format
169
-		$img = inserer_attribut($img, 'width', '');
170
-		$img = inserer_attribut($img, 'height', '');
171
-	}
172
-
173
-	// les protocoles web prennent au moins 3 lettres
174
-	if (tester_url_absolue($source)) {
175
-		include_spip('inc/distant');
176
-		$fichier = _DIR_RACINE . copie_locale($source);
177
-		if (!$fichier) {
178
-			return "";
179
-		}
180
-	} else {
181
-		// enlever le timestamp eventuel
182
-		if (strpos($source, "?") !== false) {
183
-			$source = preg_replace(',[?][0-9]+$,', '', $source);
184
-		}
185
-		if (strpos($source, "?") !== false
186
-			and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
187
-			and file_exists($f = preg_replace(',[?].*$,', '', $source))
188
-		) {
189
-			$source = $f;
190
-		}
191
-		$fichier = $source;
192
-	}
193
-
194
-	$terminaison_dest = "";
195
-	if ($terminaison = _image_trouver_extension($fichier)) {
196
-		$terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
197
-	}
198
-
199
-	if ($forcer_format !== false
200
-		// 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
201
-		and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format,_image_extensions_acceptees_en_sortie()))) {
202
-		$terminaison_dest = $forcer_format;
203
-	}
204
-
205
-	if (!$terminaison_dest) {
206
-		return false;
207
-	}
208
-
209
-	$nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
210
-	$fichier_dest = $nom_fichier;
211
-	if (($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
212
-		or @file_exists($f = $fichier)
213
-	) {
214
-		// on passe la balise img a taille image qui exraira les attributs si possible
215
-		// au lieu de faire un acces disque sur le fichier
216
-		list($ret["hauteur"], $ret["largeur"]) = taille_image($find_in_path ? $f : $img);
217
-		$date_src = @filemtime($f);
218
-	} elseif (@file_exists($f = "$fichier.src")
219
-		and lire_fichier($f, $valeurs)
220
-		and $valeurs = unserialize($valeurs)
221
-		and isset($valeurs["hauteur_dest"])
222
-		and isset($valeurs["largeur_dest"])
223
-	) {
224
-		$ret["hauteur"] = $valeurs["hauteur_dest"];
225
-		$ret["largeur"] = $valeurs["largeur_dest"];
226
-		$date_src = $valeurs["date"];
227
-	} // pas de fichier source par la
228
-	else {
229
-		return false;
230
-	}
231
-
232
-	// pas de taille mesurable
233
-	if (!($ret["hauteur"] or $ret["largeur"])) {
234
-		return false;
235
-	}
236
-
237
-	// les images calculees dependent du chemin du fichier source
238
-	// 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
239
-	// ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
240
-	// qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
241
-	// la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
242
-	// alors que ca concerne peu de site au final
243
-	// la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
244
-	$identifiant = $fichier;
245
-
246
-	// cas general :
247
-	// on a un dossier cache commun et un nom de fichier qui varie avec l'effet
248
-	// cas particulier de reduire :
249
-	// un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
250
-	$cache = "cache-gd2";
251
-	if (substr($effet, 0, 7) == 'reduire') {
252
-		list(, $maxWidth, $maxHeight) = explode('-', $effet);
253
-		list($destWidth, $destHeight) = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
254
-		$ret['largeur_dest'] = $destWidth;
255
-		$ret['hauteur_dest'] = $destHeight;
256
-		$effet = "L{$destWidth}xH$destHeight";
257
-		$cache = "cache-vignettes";
258
-		$fichier_dest = basename($fichier_dest);
259
-		if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
260
-			// on garde la terminaison initiale car image simplement copiee
261
-			// et on postfixe son nom avec un md5 du path
262
-			$terminaison_dest = $terminaison;
263
-			$fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
264
-		} else {
265
-			$fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
266
-		}
267
-		$cache = sous_repertoire(_DIR_VAR, $cache);
268
-		$cache = sous_repertoire($cache, $effet);
269
-	} else {
270
-		$fichier_dest = md5("$identifiant-$effet");
271
-		$cache = sous_repertoire(_DIR_VAR, $cache);
272
-		$cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
273
-		$fichier_dest = substr($fichier_dest, 2);
274
-	}
275
-
276
-	$fichier_dest = $cache . $fichier_dest . "." . $terminaison_dest;
277
-
278
-	$GLOBALS["images_calculees"][] = $fichier_dest;
279
-
280
-	$creer = true;
281
-	// si recalcul des images demande, recalculer chaque image une fois
282
-	if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
283
-		$images_recalcul[$fichier_dest] = true;
284
-	} else {
285
-		if (@file_exists($f = $fichier_dest)) {
286
-			if (filemtime($f) >= $date_src) {
287
-				$creer = false;
288
-			}
289
-		} else {
290
-			if (@file_exists($f = "$fichier_dest.src")
291
-				and lire_fichier($f, $valeurs)
292
-				and $valeurs = unserialize($valeurs)
293
-				and $valeurs["date"] >= $date_src
294
-			) {
295
-				$creer = false;
296
-			}
297
-		}
298
-	}
299
-	if ($creer) {
300
-		if (!@file_exists($fichier)) {
301
-			if (!@file_exists("$fichier.src")) {
302
-				spip_log("Image absente : $fichier");
303
-
304
-				return false;
305
-			}
306
-			# on reconstruit l'image source absente a partir de la chaine des .src
307
-			reconstruire_image_intermediaire($fichier);
308
-		}
309
-	}
310
-
311
-	if ($creer) {
312
-		spip_log("filtre image " . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
313
-			"images" . _LOG_DEBUG);
314
-	}
315
-
316
-	$term_fonction = _image_trouver_extension_pertinente($fichier);
317
-	$ret["fonction_imagecreatefrom"] = "_imagecreatefrom" . $term_fonction;
318
-	$ret["fichier"] = $fichier;
319
-	$ret["fonction_image"] = "_image_image" . $terminaison_dest;
320
-	$ret["fichier_dest"] = $fichier_dest;
321
-	$ret["format_source"] = _image_extension_normalisee($terminaison);
322
-	$ret["format_dest"] = $terminaison_dest;
323
-	$ret["date_src"] = $date_src;
324
-	$ret["creer"] = $creer;
325
-	$ret["class"] = extraire_attribut($img, 'class');
326
-	$ret["alt"] = extraire_attribut($img, 'alt');
327
-	$ret["style"] = extraire_attribut($img, 'style');
328
-	$ret["tag"] = $img;
329
-	if ($fonction_creation) {
330
-		$ret["reconstruction"] = $fonction_creation;
331
-		# ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement 
332
-		# cas de image_reduire qui finalement ne reduit pas l'image source
333
-		# ca evite d'essayer de le creer au prochain hit si il n'est pas la
334
-		#ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
335
-	}
336
-
337
-	$ret = pipeline('image_preparer_filtre', array(
338
-			'args' => array(
339
-				'img' => $img,
340
-				'effet' => $effet,
341
-				'forcer_format' => $forcer_format,
342
-				'fonction_creation' => $fonction_creation,
343
-				'find_in_path' => $find_in_path,
344
-			),
345
-			'data' => $ret
346
-		)
347
-	);
348
-
349
-	// une globale pour le debug en cas de crash memoire
350
-	$GLOBALS["derniere_image_calculee"] = $ret;
351
-
352
-	// traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
353
-	if ($term_fonction === 'svg') {
354
-		if ($creer and !$support_svg) {
355
-			process_image_svg_identite($ret);
356
-			$ret['creer'] = false;
357
-		}
358
-	}
359
-	else {
360
-		if (!function_exists($ret["fonction_imagecreatefrom"])) {
361
-			return false;
362
-		}
363
-	}
364
-
365
-	return $ret;
148
+    static $images_recalcul = array();
149
+    if (strlen($img) == 0) {
150
+        return false;
151
+    }
152
+
153
+    $source = trim(extraire_attribut($img, 'src'));
154
+    if (strlen($source) < 1) {
155
+        $source = $img;
156
+        $img = "<img src='$source' />";
157
+    } # gerer img src="data:....base64"
158
+    elseif (preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
159
+      and $extension = _image_trouver_extension_depuis_mime("image/".$regs[1])
160
+        and in_array($extension, _image_extensions_acceptees_en_entree())
161
+    ) {
162
+        $local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
163
+        if (!file_exists($local)) {
164
+            ecrire_fichier($local, base64_decode($regs[2]));
165
+        }
166
+        $source = $local;
167
+        $img = inserer_attribut($img, 'src', $source);
168
+        # eviter les mauvaises surprises lors de conversions de format
169
+        $img = inserer_attribut($img, 'width', '');
170
+        $img = inserer_attribut($img, 'height', '');
171
+    }
172
+
173
+    // les protocoles web prennent au moins 3 lettres
174
+    if (tester_url_absolue($source)) {
175
+        include_spip('inc/distant');
176
+        $fichier = _DIR_RACINE . copie_locale($source);
177
+        if (!$fichier) {
178
+            return "";
179
+        }
180
+    } else {
181
+        // enlever le timestamp eventuel
182
+        if (strpos($source, "?") !== false) {
183
+            $source = preg_replace(',[?][0-9]+$,', '', $source);
184
+        }
185
+        if (strpos($source, "?") !== false
186
+            and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
187
+            and file_exists($f = preg_replace(',[?].*$,', '', $source))
188
+        ) {
189
+            $source = $f;
190
+        }
191
+        $fichier = $source;
192
+    }
193
+
194
+    $terminaison_dest = "";
195
+    if ($terminaison = _image_trouver_extension($fichier)) {
196
+        $terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
197
+    }
198
+
199
+    if ($forcer_format !== false
200
+        // 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
201
+        and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format,_image_extensions_acceptees_en_sortie()))) {
202
+        $terminaison_dest = $forcer_format;
203
+    }
204
+
205
+    if (!$terminaison_dest) {
206
+        return false;
207
+    }
208
+
209
+    $nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
210
+    $fichier_dest = $nom_fichier;
211
+    if (($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
212
+        or @file_exists($f = $fichier)
213
+    ) {
214
+        // on passe la balise img a taille image qui exraira les attributs si possible
215
+        // au lieu de faire un acces disque sur le fichier
216
+        list($ret["hauteur"], $ret["largeur"]) = taille_image($find_in_path ? $f : $img);
217
+        $date_src = @filemtime($f);
218
+    } elseif (@file_exists($f = "$fichier.src")
219
+        and lire_fichier($f, $valeurs)
220
+        and $valeurs = unserialize($valeurs)
221
+        and isset($valeurs["hauteur_dest"])
222
+        and isset($valeurs["largeur_dest"])
223
+    ) {
224
+        $ret["hauteur"] = $valeurs["hauteur_dest"];
225
+        $ret["largeur"] = $valeurs["largeur_dest"];
226
+        $date_src = $valeurs["date"];
227
+    } // pas de fichier source par la
228
+    else {
229
+        return false;
230
+    }
231
+
232
+    // pas de taille mesurable
233
+    if (!($ret["hauteur"] or $ret["largeur"])) {
234
+        return false;
235
+    }
236
+
237
+    // les images calculees dependent du chemin du fichier source
238
+    // 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
239
+    // ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
240
+    // qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
241
+    // la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
242
+    // alors que ca concerne peu de site au final
243
+    // la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
244
+    $identifiant = $fichier;
245
+
246
+    // cas general :
247
+    // on a un dossier cache commun et un nom de fichier qui varie avec l'effet
248
+    // cas particulier de reduire :
249
+    // un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
250
+    $cache = "cache-gd2";
251
+    if (substr($effet, 0, 7) == 'reduire') {
252
+        list(, $maxWidth, $maxHeight) = explode('-', $effet);
253
+        list($destWidth, $destHeight) = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
254
+        $ret['largeur_dest'] = $destWidth;
255
+        $ret['hauteur_dest'] = $destHeight;
256
+        $effet = "L{$destWidth}xH$destHeight";
257
+        $cache = "cache-vignettes";
258
+        $fichier_dest = basename($fichier_dest);
259
+        if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
260
+            // on garde la terminaison initiale car image simplement copiee
261
+            // et on postfixe son nom avec un md5 du path
262
+            $terminaison_dest = $terminaison;
263
+            $fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
264
+        } else {
265
+            $fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
266
+        }
267
+        $cache = sous_repertoire(_DIR_VAR, $cache);
268
+        $cache = sous_repertoire($cache, $effet);
269
+    } else {
270
+        $fichier_dest = md5("$identifiant-$effet");
271
+        $cache = sous_repertoire(_DIR_VAR, $cache);
272
+        $cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
273
+        $fichier_dest = substr($fichier_dest, 2);
274
+    }
275
+
276
+    $fichier_dest = $cache . $fichier_dest . "." . $terminaison_dest;
277
+
278
+    $GLOBALS["images_calculees"][] = $fichier_dest;
279
+
280
+    $creer = true;
281
+    // si recalcul des images demande, recalculer chaque image une fois
282
+    if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
283
+        $images_recalcul[$fichier_dest] = true;
284
+    } else {
285
+        if (@file_exists($f = $fichier_dest)) {
286
+            if (filemtime($f) >= $date_src) {
287
+                $creer = false;
288
+            }
289
+        } else {
290
+            if (@file_exists($f = "$fichier_dest.src")
291
+                and lire_fichier($f, $valeurs)
292
+                and $valeurs = unserialize($valeurs)
293
+                and $valeurs["date"] >= $date_src
294
+            ) {
295
+                $creer = false;
296
+            }
297
+        }
298
+    }
299
+    if ($creer) {
300
+        if (!@file_exists($fichier)) {
301
+            if (!@file_exists("$fichier.src")) {
302
+                spip_log("Image absente : $fichier");
303
+
304
+                return false;
305
+            }
306
+            # on reconstruit l'image source absente a partir de la chaine des .src
307
+            reconstruire_image_intermediaire($fichier);
308
+        }
309
+    }
310
+
311
+    if ($creer) {
312
+        spip_log("filtre image " . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
313
+            "images" . _LOG_DEBUG);
314
+    }
315
+
316
+    $term_fonction = _image_trouver_extension_pertinente($fichier);
317
+    $ret["fonction_imagecreatefrom"] = "_imagecreatefrom" . $term_fonction;
318
+    $ret["fichier"] = $fichier;
319
+    $ret["fonction_image"] = "_image_image" . $terminaison_dest;
320
+    $ret["fichier_dest"] = $fichier_dest;
321
+    $ret["format_source"] = _image_extension_normalisee($terminaison);
322
+    $ret["format_dest"] = $terminaison_dest;
323
+    $ret["date_src"] = $date_src;
324
+    $ret["creer"] = $creer;
325
+    $ret["class"] = extraire_attribut($img, 'class');
326
+    $ret["alt"] = extraire_attribut($img, 'alt');
327
+    $ret["style"] = extraire_attribut($img, 'style');
328
+    $ret["tag"] = $img;
329
+    if ($fonction_creation) {
330
+        $ret["reconstruction"] = $fonction_creation;
331
+        # ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement 
332
+        # cas de image_reduire qui finalement ne reduit pas l'image source
333
+        # ca evite d'essayer de le creer au prochain hit si il n'est pas la
334
+        #ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
335
+    }
336
+
337
+    $ret = pipeline('image_preparer_filtre', array(
338
+            'args' => array(
339
+                'img' => $img,
340
+                'effet' => $effet,
341
+                'forcer_format' => $forcer_format,
342
+                'fonction_creation' => $fonction_creation,
343
+                'find_in_path' => $find_in_path,
344
+            ),
345
+            'data' => $ret
346
+        )
347
+    );
348
+
349
+    // une globale pour le debug en cas de crash memoire
350
+    $GLOBALS["derniere_image_calculee"] = $ret;
351
+
352
+    // traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
353
+    if ($term_fonction === 'svg') {
354
+        if ($creer and !$support_svg) {
355
+            process_image_svg_identite($ret);
356
+            $ret['creer'] = false;
357
+        }
358
+    }
359
+    else {
360
+        if (!function_exists($ret["fonction_imagecreatefrom"])) {
361
+            return false;
362
+        }
363
+    }
364
+
365
+    return $ret;
366 366
 }
367 367
 
368 368
 
@@ -371,50 +371,50 @@  discard block
 block discarded – undo
371 371
  * @return array
372 372
  */
373 373
 function _image_extensions_acceptees_en_entree() {
374
-	static $extensions = null;
375
-	if (empty($extensions)) {
376
-		$extensions = ['png', 'gif', 'jpg', 'jpeg', 'svg'];
377
-		if (!empty($GLOBALS['meta']['gd_formats'])) {
378
-			// action=tester renseigne gd_formats et detecte le support de webp
379
-			$extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
380
-			$extensions = array_map('trim', $extensions);
381
-			$extensions = array_filter($extensions);
382
-			$extensions = array_unique($extensions);
383
-		}
384
-	}
385
-
386
-	return $extensions;
374
+    static $extensions = null;
375
+    if (empty($extensions)) {
376
+        $extensions = ['png', 'gif', 'jpg', 'jpeg', 'svg'];
377
+        if (!empty($GLOBALS['meta']['gd_formats'])) {
378
+            // action=tester renseigne gd_formats et detecte le support de webp
379
+            $extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
380
+            $extensions = array_map('trim', $extensions);
381
+            $extensions = array_filter($extensions);
382
+            $extensions = array_unique($extensions);
383
+        }
384
+    }
385
+
386
+    return $extensions;
387 387
 }
388 388
 
389 389
 /**
390 390
  * @return array|string[]|null
391 391
  */
392 392
 function _image_extensions_acceptees_en_sortie(){
393
-	static $extensions = null;
394
-	if (empty($extensions)){
395
-		$extensions = _image_extensions_acceptees_en_entree();
396
-		$extensions = array_diff($extensions, ['jpeg']);
397
-		if (in_array('gif', $extensions) and !function_exists('imagegif')) {
398
-			$extensions = array_diff($extensions, ['gif']);
399
-		}
400
-		if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
401
-			$extensions = array_diff($extensions, ['webp']);
402
-		}
403
-	}
404
-
405
-	return $extensions;
393
+    static $extensions = null;
394
+    if (empty($extensions)){
395
+        $extensions = _image_extensions_acceptees_en_entree();
396
+        $extensions = array_diff($extensions, ['jpeg']);
397
+        if (in_array('gif', $extensions) and !function_exists('imagegif')) {
398
+            $extensions = array_diff($extensions, ['gif']);
399
+        }
400
+        if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
401
+            $extensions = array_diff($extensions, ['webp']);
402
+        }
403
+    }
404
+
405
+    return $extensions;
406 406
 }
407 407
 
408 408
 function _image_extension_normalisee($extension){
409
-	$extension = strtolower($extension);
410
-	if ($extension === 'jpeg') {
411
-		$extension = 'jpg';
412
-	}
413
-	return $extension;
409
+    $extension = strtolower($extension);
410
+    if ($extension === 'jpeg') {
411
+        $extension = 'jpg';
412
+    }
413
+    return $extension;
414 414
 }
415 415
 
416 416
 function _image_extensions_conservent_transparence(){
417
-	return ['png', 'webp'];
417
+    return ['png', 'webp'];
418 418
 }
419 419
 
420 420
 
@@ -424,12 +424,12 @@  discard block
 block discarded – undo
424 424
  * @return string
425 425
  */
426 426
 function _image_trouver_extension($path) {
427
-	$preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
428
-	if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
429
-		$terminaison = strtolower($regs[1]);
430
-		return $terminaison;
431
-	}
432
-	return '';
427
+    $preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
428
+    if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
429
+        $terminaison = strtolower($regs[1]);
430
+        return $terminaison;
431
+    }
432
+    return '';
433 433
 }
434 434
 
435 435
 /**
@@ -440,33 +440,33 @@  discard block
 block discarded – undo
440 440
  * @return string Extension, dans le format attendu par les fonctions 'gd' ('jpeg' pour les .jpg par exemple)
441 441
  */
442 442
 function _image_trouver_extension_pertinente($path) {
443
-	$path = supprimer_timestamp($path);
444
-	$terminaison = _image_trouver_extension($path);
445
-	if ($terminaison == 'jpg') {
446
-		$terminaison = 'jpeg';
447
-	}
448
-
449
-	if (!file_exists($path)) {
450
-		return $terminaison;
451
-	}
452
-
453
-	if (!$info = @spip_getimagesize($path)) {
454
-		return $terminaison;
455
-	}
456
-
457
-	if (isset($info['mime'])) {
458
-		$mime = $info['mime'];
459
-	}
460
-	else {
461
-		$mime = image_type_to_mime_type($info[2]);
462
-	}
463
-
464
-	$_terminaison = _image_trouver_extension_depuis_mime($mime);
465
-	if ($_terminaison and $_terminaison !== $terminaison) {
466
-		spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", "images." . _LOG_INFO_IMPORTANTE);
467
-		$terminaison = $_terminaison;
468
-	}
469
-	return $terminaison;
443
+    $path = supprimer_timestamp($path);
444
+    $terminaison = _image_trouver_extension($path);
445
+    if ($terminaison == 'jpg') {
446
+        $terminaison = 'jpeg';
447
+    }
448
+
449
+    if (!file_exists($path)) {
450
+        return $terminaison;
451
+    }
452
+
453
+    if (!$info = @spip_getimagesize($path)) {
454
+        return $terminaison;
455
+    }
456
+
457
+    if (isset($info['mime'])) {
458
+        $mime = $info['mime'];
459
+    }
460
+    else {
461
+        $mime = image_type_to_mime_type($info[2]);
462
+    }
463
+
464
+    $_terminaison = _image_trouver_extension_depuis_mime($mime);
465
+    if ($_terminaison and $_terminaison !== $terminaison) {
466
+        spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", "images." . _LOG_INFO_IMPORTANTE);
467
+        $terminaison = $_terminaison;
468
+    }
469
+    return $terminaison;
470 470
 }
471 471
 
472 472
 /**
@@ -474,36 +474,36 @@  discard block
 block discarded – undo
474 474
  * @return string
475 475
  */
476 476
 function _image_trouver_extension_depuis_mime($mime) {
477
-	switch (strtolower($mime)) {
478
-		case 'image/png':
479
-		case 'image/x-png':
480
-			$terminaison = 'png';
481
-			break;
482
-
483
-		case 'image/jpg':
484
-		case 'image/jpeg':
485
-		case 'image/pjpeg':
486
-			$terminaison = 'jpeg';
487
-			break;
488
-
489
-		case 'image/gif':
490
-			$terminaison = 'gif';
491
-			break;
492
-
493
-		case 'image/webp':
494
-		case 'image/x-webp':
495
-			$terminaison = 'webp';
496
-			break;
497
-
498
-		case 'image/svg+xml':
499
-			$terminaison = 'svg';
500
-			break;
501
-
502
-		default:
503
-			$terminaison = '';
504
-	}
505
-
506
-	return $terminaison;
477
+    switch (strtolower($mime)) {
478
+        case 'image/png':
479
+        case 'image/x-png':
480
+            $terminaison = 'png';
481
+            break;
482
+
483
+        case 'image/jpg':
484
+        case 'image/jpeg':
485
+        case 'image/pjpeg':
486
+            $terminaison = 'jpeg';
487
+            break;
488
+
489
+        case 'image/gif':
490
+            $terminaison = 'gif';
491
+            break;
492
+
493
+        case 'image/webp':
494
+        case 'image/x-webp':
495
+            $terminaison = 'webp';
496
+            break;
497
+
498
+        case 'image/svg+xml':
499
+            $terminaison = 'svg';
500
+            break;
501
+
502
+        default:
503
+            $terminaison = '';
504
+    }
505
+
506
+    return $terminaison;
507 507
 }
508 508
 
509 509
 /**
@@ -518,14 +518,14 @@  discard block
 block discarded – undo
518 518
  *     Une ressource de type Image GD.
519 519
  */
520 520
 function _imagecreatefromjpeg($filename) {
521
-	$img = @imagecreatefromjpeg($filename);
522
-	if (!$img) {
523
-		spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
524
-		erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
525
-		$img = imagecreate(10, 10);
526
-	}
527
-
528
-	return $img;
521
+    $img = @imagecreatefromjpeg($filename);
522
+    if (!$img) {
523
+        spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
524
+        erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
525
+        $img = imagecreate(10, 10);
526
+    }
527
+
528
+    return $img;
529 529
 }
530 530
 
531 531
 /**
@@ -540,14 +540,14 @@  discard block
 block discarded – undo
540 540
  *     Une ressource de type Image GD.
541 541
  */
542 542
 function _imagecreatefrompng($filename) {
543
-	$img = @imagecreatefrompng($filename);
544
-	if (!$img) {
545
-		spip_log("Erreur lecture imagecreatefrompng $filename", _LOG_CRITIQUE);
546
-		erreur_squelette("Erreur lecture imagecreatefrompng $filename");
547
-		$img = imagecreate(10, 10);
548
-	}
549
-
550
-	return $img;
543
+    $img = @imagecreatefrompng($filename);
544
+    if (!$img) {
545
+        spip_log("Erreur lecture imagecreatefrompng $filename", _LOG_CRITIQUE);
546
+        erreur_squelette("Erreur lecture imagecreatefrompng $filename");
547
+        $img = imagecreate(10, 10);
548
+    }
549
+
550
+    return $img;
551 551
 }
552 552
 
553 553
 /**
@@ -562,14 +562,14 @@  discard block
 block discarded – undo
562 562
  *     Une ressource de type Image GD.
563 563
  */
564 564
 function _imagecreatefromgif($filename) {
565
-	$img = @imagecreatefromgif($filename);
566
-	if (!$img) {
567
-		spip_log("Erreur lecture imagecreatefromgif $filename", _LOG_CRITIQUE);
568
-		erreur_squelette("Erreur lecture imagecreatefromgif $filename");
569
-		$img = imagecreate(10, 10);
570
-	}
571
-
572
-	return $img;
565
+    $img = @imagecreatefromgif($filename);
566
+    if (!$img) {
567
+        spip_log("Erreur lecture imagecreatefromgif $filename", _LOG_CRITIQUE);
568
+        erreur_squelette("Erreur lecture imagecreatefromgif $filename");
569
+        $img = imagecreate(10, 10);
570
+    }
571
+
572
+    return $img;
573 573
 }
574 574
 
575 575
 
@@ -585,14 +585,14 @@  discard block
 block discarded – undo
585 585
  *     Une ressource de type Image GD.
586 586
  */
587 587
 function _imagecreatefromwebp($filename) {
588
-	$img = @imagecreatefromwebp($filename);
589
-	if (!$img) {
590
-		spip_log("Erreur lecture imagecreatefromwebp $filename", _LOG_CRITIQUE);
591
-		erreur_squelette("Erreur lecture imagecreatefrompng $filename");
592
-		$img = imagecreate(10, 10);
593
-	}
594
-
595
-	return $img;
588
+    $img = @imagecreatefromwebp($filename);
589
+    if (!$img) {
590
+        spip_log("Erreur lecture imagecreatefromwebp $filename", _LOG_CRITIQUE);
591
+        erreur_squelette("Erreur lecture imagecreatefrompng $filename");
592
+        $img = imagecreate(10, 10);
593
+    }
594
+
595
+    return $img;
596 596
 }
597 597
 
598 598
 /**
@@ -610,24 +610,24 @@  discard block
 block discarded – undo
610 610
  *     - true si une image est bien retournée.
611 611
  */
612 612
 function _image_imagepng($img, $fichier) {
613
-	if (!function_exists('imagepng')) {
614
-		return false;
615
-	}
616
-	$tmp = $fichier . ".tmp";
617
-	$ret = imagepng($img, $tmp);
618
-	if (file_exists($tmp)) {
619
-		$taille_test = getimagesize($tmp);
620
-		if ($taille_test[0] < 1) {
621
-			return false;
622
-		}
623
-
624
-		spip_unlink($fichier); // le fichier peut deja exister
625
-		@rename($tmp, $fichier);
626
-
627
-		return $ret;
628
-	}
629
-
630
-	return false;
613
+    if (!function_exists('imagepng')) {
614
+        return false;
615
+    }
616
+    $tmp = $fichier . ".tmp";
617
+    $ret = imagepng($img, $tmp);
618
+    if (file_exists($tmp)) {
619
+        $taille_test = getimagesize($tmp);
620
+        if ($taille_test[0] < 1) {
621
+            return false;
622
+        }
623
+
624
+        spip_unlink($fichier); // le fichier peut deja exister
625
+        @rename($tmp, $fichier);
626
+
627
+        return $ret;
628
+    }
629
+
630
+    return false;
631 631
 }
632 632
 
633 633
 /**
@@ -645,24 +645,24 @@  discard block
 block discarded – undo
645 645
  *     - true si une image est bien retournée.
646 646
  */
647 647
 function _image_imagegif($img, $fichier) {
648
-	if (!function_exists('imagegif')) {
649
-		return false;
650
-	}
651
-	$tmp = $fichier . ".tmp";
652
-	$ret = imagegif($img, $tmp);
653
-	if (file_exists($tmp)) {
654
-		$taille_test = getimagesize($tmp);
655
-		if ($taille_test[0] < 1) {
656
-			return false;
657
-		}
658
-
659
-		spip_unlink($fichier); // le fichier peut deja exister
660
-		@rename($tmp, $fichier);
661
-
662
-		return $ret;
663
-	}
664
-
665
-	return false;
648
+    if (!function_exists('imagegif')) {
649
+        return false;
650
+    }
651
+    $tmp = $fichier . ".tmp";
652
+    $ret = imagegif($img, $tmp);
653
+    if (file_exists($tmp)) {
654
+        $taille_test = getimagesize($tmp);
655
+        if ($taille_test[0] < 1) {
656
+            return false;
657
+        }
658
+
659
+        spip_unlink($fichier); // le fichier peut deja exister
660
+        @rename($tmp, $fichier);
661
+
662
+        return $ret;
663
+    }
664
+
665
+    return false;
666 666
 }
667 667
 
668 668
 /**
@@ -685,29 +685,29 @@  discard block
 block discarded – undo
685 685
  *     - true si une image est bien retournée.
686 686
  */
687 687
 function _image_imagejpg($img, $fichier, $qualite = _IMG_GD_QUALITE) {
688
-	if (!function_exists('imagejpeg')) {
689
-		return false;
690
-	}
691
-	$tmp = $fichier . ".tmp";
688
+    if (!function_exists('imagejpeg')) {
689
+        return false;
690
+    }
691
+    $tmp = $fichier . ".tmp";
692 692
 
693
-	// Enable interlancing
694
-	imageinterlace($img, true);
693
+    // Enable interlancing
694
+    imageinterlace($img, true);
695 695
 
696
-	$ret = imagejpeg($img, $tmp, $qualite);
696
+    $ret = imagejpeg($img, $tmp, $qualite);
697 697
 
698
-	if (file_exists($tmp)) {
699
-		$taille_test = getimagesize($tmp);
700
-		if ($taille_test[0] < 1) {
701
-			return false;
702
-		}
698
+    if (file_exists($tmp)) {
699
+        $taille_test = getimagesize($tmp);
700
+        if ($taille_test[0] < 1) {
701
+            return false;
702
+        }
703 703
 
704
-		spip_unlink($fichier); // le fichier peut deja exister
705
-		@rename($tmp, $fichier);
704
+        spip_unlink($fichier); // le fichier peut deja exister
705
+        @rename($tmp, $fichier);
706 706
 
707
-		return $ret;
708
-	}
707
+        return $ret;
708
+    }
709 709
 
710
-	return false;
710
+    return false;
711 711
 }
712 712
 
713 713
 /**
@@ -725,9 +725,9 @@  discard block
 block discarded – undo
725 725
  *     true si le fichier a bien été créé ; false sinon.
726 726
  */
727 727
 function _image_imageico($img, $fichier) {
728
-	$gd_image_array = array($img);
728
+    $gd_image_array = array($img);
729 729
 
730
-	return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
730
+    return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
731 731
 }
732 732
 
733 733
 
@@ -746,24 +746,24 @@  discard block
 block discarded – undo
746 746
  *     - true si une image est bien retournée.
747 747
  */
748 748
 function _image_imagewebp($img, $fichier, $qualite = _IMG_GD_QUALITE) {
749
-	if (!function_exists('imagewebp')) {
750
-		return false;
751
-	}
752
-	$tmp = $fichier . ".tmp";
753
-	$ret = imagewebp($img, $tmp, $qualite);
754
-	if (file_exists($tmp)) {
755
-		$taille_test = getimagesize($tmp);
756
-		if ($taille_test[0] < 1) {
757
-			return false;
758
-		}
759
-
760
-		spip_unlink($fichier); // le fichier peut deja exister
761
-		@rename($tmp, $fichier);
762
-
763
-		return $ret;
764
-	}
765
-
766
-	return false;
749
+    if (!function_exists('imagewebp')) {
750
+        return false;
751
+    }
752
+    $tmp = $fichier . ".tmp";
753
+    $ret = imagewebp($img, $tmp, $qualite);
754
+    if (file_exists($tmp)) {
755
+        $taille_test = getimagesize($tmp);
756
+        if ($taille_test[0] < 1) {
757
+            return false;
758
+        }
759
+
760
+        spip_unlink($fichier); // le fichier peut deja exister
761
+        @rename($tmp, $fichier);
762
+
763
+        return $ret;
764
+    }
765
+
766
+    return false;
767 767
 }
768 768
 
769 769
 /**
@@ -783,35 +783,35 @@  discard block
 block discarded – undo
783 783
  */
784 784
 function _image_imagesvg($img, $fichier) {
785 785
 
786
-	$tmp = $fichier . ".tmp";
787
-	if (strpos($img, "<") === false) {
788
-		$img = supprimer_timestamp($img);
789
-		if (!file_exists($img)) {
790
-			return false;
791
-		}
792
-		@copy($img, $tmp);
793
-		if (filesize($tmp) == filesize($img)) {
794
-			spip_unlink($fichier); // le fichier peut deja exister
795
-			@rename($tmp, $fichier);
796
-			return true;
797
-		}
798
-		return false;
799
-	}
800
-
801
-	file_put_contents($tmp, $img);
802
-	if (file_exists($tmp)) {
803
-		$taille_test = spip_getimagesize($tmp);
804
-		if ($taille_test[0] < 1) {
805
-			return false;
806
-		}
807
-
808
-		spip_unlink($fichier); // le fichier peut deja exister
809
-		@rename($tmp, $fichier);
810
-
811
-		return true;
812
-	}
813
-
814
-	return false;
786
+    $tmp = $fichier . ".tmp";
787
+    if (strpos($img, "<") === false) {
788
+        $img = supprimer_timestamp($img);
789
+        if (!file_exists($img)) {
790
+            return false;
791
+        }
792
+        @copy($img, $tmp);
793
+        if (filesize($tmp) == filesize($img)) {
794
+            spip_unlink($fichier); // le fichier peut deja exister
795
+            @rename($tmp, $fichier);
796
+            return true;
797
+        }
798
+        return false;
799
+    }
800
+
801
+    file_put_contents($tmp, $img);
802
+    if (file_exists($tmp)) {
803
+        $taille_test = spip_getimagesize($tmp);
804
+        if ($taille_test[0] < 1) {
805
+            return false;
806
+        }
807
+
808
+        spip_unlink($fichier); // le fichier peut deja exister
809
+        @rename($tmp, $fichier);
810
+
811
+        return true;
812
+    }
813
+
814
+    return false;
815 815
 }
816 816
 
817 817
 
@@ -839,27 +839,27 @@  discard block
 block discarded – undo
839 839
  *     - false sinon.
840 840
  */
841 841
 function _image_gd_output($img, $valeurs, $qualite = _IMG_GD_QUALITE) {
842
-	$fonction = "_image_image" . $valeurs['format_dest'];
843
-	$ret = false;
844
-	#un flag pour reperer les images gravees
845
-	$lock =
846
-		!statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
847
-	or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'));
848
-	if (
849
-		function_exists($fonction)
850
-		&& ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
851
-		&& isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
852
-		&& !$lock
853
-	) {
854
-		if (@file_exists($valeurs['fichier_dest'])) {
855
-			// dans tous les cas mettre a jour la taille de l'image finale
856
-			list($valeurs["hauteur_dest"], $valeurs["largeur_dest"]) = taille_image($valeurs['fichier_dest']);
857
-			$valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
858
-			ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
859
-		}
860
-	}
861
-
862
-	return $ret;
842
+    $fonction = "_image_image" . $valeurs['format_dest'];
843
+    $ret = false;
844
+    #un flag pour reperer les images gravees
845
+    $lock =
846
+        !statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
847
+    or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'));
848
+    if (
849
+        function_exists($fonction)
850
+        && ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
851
+        && isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
852
+        && !$lock
853
+    ) {
854
+        if (@file_exists($valeurs['fichier_dest'])) {
855
+            // dans tous les cas mettre a jour la taille de l'image finale
856
+            list($valeurs["hauteur_dest"], $valeurs["largeur_dest"]) = taille_image($valeurs['fichier_dest']);
857
+            $valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
858
+            ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
859
+        }
860
+    }
861
+
862
+    return $ret;
863 863
 }
864 864
 
865 865
 /**
@@ -872,26 +872,26 @@  discard block
 block discarded – undo
872 872
  *     Chemin vers le fichier manquant
873 873
  **/
874 874
 function reconstruire_image_intermediaire($fichier_manquant) {
875
-	$reconstruire = array();
876
-	$fichier = $fichier_manquant;
877
-	while (strpos($fichier,"://")===false
878
-		and !@file_exists($fichier)
879
-		and lire_fichier($src = "$fichier.src", $source)
880
-		and $valeurs = unserialize($source)
881
-		and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
882
-	) {
883
-		spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
884
-		$reconstruire[] = $valeurs['reconstruction'];
885
-	}
886
-	while (count($reconstruire)) {
887
-		$r = array_pop($reconstruire);
888
-		$fonction = $r[0];
889
-		$args = $r[1];
890
-		call_user_func_array($fonction, $args);
891
-	}
892
-	// cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
893
-	// mais l'on peut nettoyer les miettes de sa creation
894
-	ramasse_miettes($fichier_manquant);
875
+    $reconstruire = array();
876
+    $fichier = $fichier_manquant;
877
+    while (strpos($fichier,"://")===false
878
+        and !@file_exists($fichier)
879
+        and lire_fichier($src = "$fichier.src", $source)
880
+        and $valeurs = unserialize($source)
881
+        and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
882
+    ) {
883
+        spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
884
+        $reconstruire[] = $valeurs['reconstruction'];
885
+    }
886
+    while (count($reconstruire)) {
887
+        $r = array_pop($reconstruire);
888
+        $fonction = $r[0];
889
+        $args = $r[1];
890
+        call_user_func_array($fonction, $args);
891
+    }
892
+    // cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
893
+    // mais l'on peut nettoyer les miettes de sa creation
894
+    ramasse_miettes($fichier_manquant);
895 895
 }
896 896
 
897 897
 /**
@@ -911,25 +911,25 @@  discard block
 block discarded – undo
911 911
  *     Chemin du fichier d'image calculé
912 912
  **/
913 913
 function ramasse_miettes($fichier) {
914
-	if (strpos($fichier,"://")!==false
915
-		or !lire_fichier($src = "$fichier.src", $source)
916
-		or !$valeurs = unserialize($source)
917
-	) {
918
-		return;
919
-	}
920
-	spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
921
-	while (
922
-		($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
923
-		and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
924
-		and (lire_fichier($src = "$fichier.src",
925
-			$source)) # le fichier a une source connue (c'est donc une image calculee intermediaire)
926
-		and ($valeurs = unserialize($source))  # et valide
927
-	) {
928
-		# on efface le fichier
929
-		spip_unlink($fichier);
930
-		# mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
931
-		#spip_unlink($src);
932
-	}
914
+    if (strpos($fichier,"://")!==false
915
+        or !lire_fichier($src = "$fichier.src", $source)
916
+        or !$valeurs = unserialize($source)
917
+    ) {
918
+        return;
919
+    }
920
+    spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
921
+    while (
922
+        ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
923
+        and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
924
+        and (lire_fichier($src = "$fichier.src",
925
+            $source)) # le fichier a une source connue (c'est donc une image calculee intermediaire)
926
+        and ($valeurs = unserialize($source))  # et valide
927
+    ) {
928
+        # on efface le fichier
929
+        spip_unlink($fichier);
930
+        # mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
931
+        #spip_unlink($src);
932
+    }
933 933
 }
934 934
 
935 935
 
@@ -954,71 +954,71 @@  discard block
 block discarded – undo
954 954
  *     Code HTML de l'image
955 955
  **/
956 956
 function image_graver($img) {
957
-	// appeler le filtre post_image_filtrer qui permet de faire
958
-	// des traitements auto a la fin d'une serie de filtres
959
-	$img = pipeline('post_image_filtrer', $img);
960
-
961
-	$fichier_ori = $fichier = extraire_attribut($img, 'src');
962
-	if (($p = strpos($fichier, '?')) !== false) {
963
-		$fichier = substr($fichier, 0, $p);
964
-	}
965
-	if (strlen($fichier) < 1) {
966
-		$fichier = $img;
967
-	}
968
-	# si jamais le fichier final n'a pas ete calcule car suppose temporaire
969
-	# et qu'il ne s'agit pas d'une URL
970
-	if (strpos($fichier,"://")===false and !@file_exists($fichier)) {
971
-		reconstruire_image_intermediaire($fichier);
972
-	}
973
-	ramasse_miettes($fichier);
974
-
975
-	// ajouter le timestamp si besoin
976
-	if (strpos($fichier_ori, "?") === false) {
977
-		// on utilise str_replace pour attraper le onmouseover des logo si besoin
978
-		$img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
979
-	}
980
-
981
-	return $img;
957
+    // appeler le filtre post_image_filtrer qui permet de faire
958
+    // des traitements auto a la fin d'une serie de filtres
959
+    $img = pipeline('post_image_filtrer', $img);
960
+
961
+    $fichier_ori = $fichier = extraire_attribut($img, 'src');
962
+    if (($p = strpos($fichier, '?')) !== false) {
963
+        $fichier = substr($fichier, 0, $p);
964
+    }
965
+    if (strlen($fichier) < 1) {
966
+        $fichier = $img;
967
+    }
968
+    # si jamais le fichier final n'a pas ete calcule car suppose temporaire
969
+    # et qu'il ne s'agit pas d'une URL
970
+    if (strpos($fichier,"://")===false and !@file_exists($fichier)) {
971
+        reconstruire_image_intermediaire($fichier);
972
+    }
973
+    ramasse_miettes($fichier);
974
+
975
+    // ajouter le timestamp si besoin
976
+    if (strpos($fichier_ori, "?") === false) {
977
+        // on utilise str_replace pour attraper le onmouseover des logo si besoin
978
+        $img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
979
+    }
980
+
981
+    return $img;
982 982
 }
983 983
 
984 984
 
985 985
 if (!function_exists("imagepalettetotruecolor")) {
986
-	/**
987
-	 * Transforme une image à palette indexée (256 couleurs max) en "vraies" couleurs RGB
988
-	 *
989
-	 * @note Pour compatibilité avec PHP < 5.5
990
-	 *
991
-	 * @link http://php.net/manual/fr/function.imagepalettetotruecolor.php
992
-	 *
993
-	 * @param ressource $img
994
-	 * @return bool
995
-	 *     - true si l'image est déjà en vrai RGB ou peut être transformée
996
-	 *     - false si la transformation ne peut être faite.
997
-	 **/
998
-	function imagepalettetotruecolor(&$img) {
999
-		if (!$img or !function_exists('imagecreatetruecolor')) {
1000
-			return false;
1001
-		} elseif (!imageistruecolor($img)) {
1002
-			$w = imagesx($img);
1003
-			$h = imagesy($img);
1004
-			$img1 = imagecreatetruecolor($w, $h);
1005
-			//Conserver la transparence si possible
1006
-			if (function_exists('ImageCopyResampled')) {
1007
-				if (function_exists("imageAntiAlias")) {
1008
-					imageAntiAlias($img1, true);
1009
-				}
1010
-				@imagealphablending($img1, false);
1011
-				@imagesavealpha($img1, true);
1012
-				@ImageCopyResampled($img1, $img, 0, 0, 0, 0, $w, $h, $w, $h);
1013
-			} else {
1014
-				imagecopy($img1, $img, 0, 0, 0, 0, $w, $h);
1015
-			}
1016
-
1017
-			$img = $img1;
1018
-		}
1019
-
1020
-		return true;
1021
-	}
986
+    /**
987
+     * Transforme une image à palette indexée (256 couleurs max) en "vraies" couleurs RGB
988
+     *
989
+     * @note Pour compatibilité avec PHP < 5.5
990
+     *
991
+     * @link http://php.net/manual/fr/function.imagepalettetotruecolor.php
992
+     *
993
+     * @param ressource $img
994
+     * @return bool
995
+     *     - true si l'image est déjà en vrai RGB ou peut être transformée
996
+     *     - false si la transformation ne peut être faite.
997
+     **/
998
+    function imagepalettetotruecolor(&$img) {
999
+        if (!$img or !function_exists('imagecreatetruecolor')) {
1000
+            return false;
1001
+        } elseif (!imageistruecolor($img)) {
1002
+            $w = imagesx($img);
1003
+            $h = imagesy($img);
1004
+            $img1 = imagecreatetruecolor($w, $h);
1005
+            //Conserver la transparence si possible
1006
+            if (function_exists('ImageCopyResampled')) {
1007
+                if (function_exists("imageAntiAlias")) {
1008
+                    imageAntiAlias($img1, true);
1009
+                }
1010
+                @imagealphablending($img1, false);
1011
+                @imagesavealpha($img1, true);
1012
+                @ImageCopyResampled($img1, $img, 0, 0, 0, 0, $w, $h, $w, $h);
1013
+            } else {
1014
+                imagecopy($img1, $img, 0, 0, 0, 0, $w, $h);
1015
+            }
1016
+
1017
+            $img = $img1;
1018
+        }
1019
+
1020
+        return true;
1021
+    }
1022 1022
 }
1023 1023
 
1024 1024
 /**
@@ -1045,32 +1045,32 @@  discard block
 block discarded – undo
1045 1045
  *     Code html modifié de la balise.
1046 1046
  **/
1047 1047
 function _image_tag_changer_taille($tag, $width, $height, $style = false) {
1048
-	if ($style === false) {
1049
-		$style = extraire_attribut($tag, 'style');
1050
-	}
1051
-
1052
-	// enlever le width et height du style
1053
-	$style = preg_replace(",(^|;)\s*(width|height)\s*:\s*[^;]+,ims", "", $style);
1054
-	if ($style and $style[0] == ';') {
1055
-		$style = substr($style, 1);
1056
-	}
1057
-
1058
-	// mettre des attributs de width et height sur les images, 
1059
-	// ca accelere le rendu du navigateur
1060
-	// ca permet aux navigateurs de reserver la bonne taille 
1061
-	// quand on a desactive l'affichage des images.
1062
-	$tag = inserer_attribut($tag, 'width', round($width));
1063
-	$tag = inserer_attribut($tag, 'height', round($height));
1064
-
1065
-	// attributs deprecies. Transformer en CSS
1066
-	if ($espace = extraire_attribut($tag, 'hspace')) {
1067
-		$style = "margin:${espace}px;" . $style;
1068
-		$tag = inserer_attribut($tag, 'hspace', '');
1069
-	}
1070
-
1071
-	$tag = inserer_attribut($tag, 'style', $style, true, $style ? false : true);
1072
-
1073
-	return $tag;
1048
+    if ($style === false) {
1049
+        $style = extraire_attribut($tag, 'style');
1050
+    }
1051
+
1052
+    // enlever le width et height du style
1053
+    $style = preg_replace(",(^|;)\s*(width|height)\s*:\s*[^;]+,ims", "", $style);
1054
+    if ($style and $style[0] == ';') {
1055
+        $style = substr($style, 1);
1056
+    }
1057
+
1058
+    // mettre des attributs de width et height sur les images, 
1059
+    // ca accelere le rendu du navigateur
1060
+    // ca permet aux navigateurs de reserver la bonne taille 
1061
+    // quand on a desactive l'affichage des images.
1062
+    $tag = inserer_attribut($tag, 'width', round($width));
1063
+    $tag = inserer_attribut($tag, 'height', round($height));
1064
+
1065
+    // attributs deprecies. Transformer en CSS
1066
+    if ($espace = extraire_attribut($tag, 'hspace')) {
1067
+        $style = "margin:${espace}px;" . $style;
1068
+        $tag = inserer_attribut($tag, 'hspace', '');
1069
+    }
1070
+
1071
+    $tag = inserer_attribut($tag, 'style', $style, true, $style ? false : true);
1072
+
1073
+    return $tag;
1074 1074
 }
1075 1075
 
1076 1076
 
@@ -1096,71 +1096,71 @@  discard block
 block discarded – undo
1096 1096
  *     Retourne le code HTML de l'image
1097 1097
  **/
1098 1098
 function _image_ecrire_tag($valeurs, $surcharge = array()) {
1099
-	$valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1100
-
1101
-	// fermer les tags img pas bien fermes;
1102
-	$tag = str_replace(">", "/>", str_replace("/>", ">", $valeurs['tag']));
1103
-
1104
-	// le style
1105
-	$style = $valeurs['style'];
1106
-	if (isset($surcharge['style'])) {
1107
-		$style = $surcharge['style'];
1108
-		unset($surcharge['style']);
1109
-	}
1110
-
1111
-	// traiter specifiquement la largeur et la hauteur
1112
-	$width = $valeurs['largeur'];
1113
-	if (isset($surcharge['width'])) {
1114
-		$width = $surcharge['width'];
1115
-		unset($surcharge['width']);
1116
-	}
1117
-	$height = $valeurs['hauteur'];
1118
-	if (isset($surcharge['height'])) {
1119
-		$height = $surcharge['height'];
1120
-		unset($surcharge['height']);
1121
-	}
1122
-
1123
-	$tag = _image_tag_changer_taille($tag, $width, $height, $style);
1124
-	// traiter specifiquement le src qui peut etre repris dans un onmouseout
1125
-	// on remplace toute les ref a src dans le tag
1126
-	$src = extraire_attribut($tag, 'src');
1127
-	if (isset($surcharge['src'])) {
1128
-		$tag = str_replace($src, $surcharge['src'], $tag);
1129
-		// si il y a des & dans src, alors ils peuvent provenir d'un &amp
1130
-		// pas garanti comme methode, mais mieux que rien
1131
-		if (strpos($src, '&') !== false) {
1132
-			$tag = str_replace(str_replace("&", "&amp;", $src), $surcharge['src'], $tag);
1133
-		}
1134
-		$src = $surcharge['src'];
1135
-		unset($surcharge['src']);
1136
-	}
1137
-
1138
-	$class = $valeurs['class'];
1139
-	if (isset($surcharge['class'])) {
1140
-		$class = $surcharge['class'];
1141
-		unset($surcharge['class']);
1142
-	}
1143
-	if (strlen($class)) {
1144
-		$tag = inserer_attribut($tag, 'class', $class);
1145
-	}
1146
-
1147
-	if (count($surcharge)) {
1148
-		foreach ($surcharge as $attribut => $valeur) {
1149
-			$tag = inserer_attribut($tag, $attribut, $valeur);
1150
-		}
1151
-	}
1152
-
1153
-	$tag = pipeline('image_ecrire_tag_finir',
1154
-		array(
1155
-			'args' => array(
1156
-				'valeurs' => $valeurs,
1157
-				'surcharge' => $surcharge,
1158
-			),
1159
-			'data' => $tag
1160
-		)
1161
-	);
1162
-
1163
-	return $tag;
1099
+    $valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1100
+
1101
+    // fermer les tags img pas bien fermes;
1102
+    $tag = str_replace(">", "/>", str_replace("/>", ">", $valeurs['tag']));
1103
+
1104
+    // le style
1105
+    $style = $valeurs['style'];
1106
+    if (isset($surcharge['style'])) {
1107
+        $style = $surcharge['style'];
1108
+        unset($surcharge['style']);
1109
+    }
1110
+
1111
+    // traiter specifiquement la largeur et la hauteur
1112
+    $width = $valeurs['largeur'];
1113
+    if (isset($surcharge['width'])) {
1114
+        $width = $surcharge['width'];
1115
+        unset($surcharge['width']);
1116
+    }
1117
+    $height = $valeurs['hauteur'];
1118
+    if (isset($surcharge['height'])) {
1119
+        $height = $surcharge['height'];
1120
+        unset($surcharge['height']);
1121
+    }
1122
+
1123
+    $tag = _image_tag_changer_taille($tag, $width, $height, $style);
1124
+    // traiter specifiquement le src qui peut etre repris dans un onmouseout
1125
+    // on remplace toute les ref a src dans le tag
1126
+    $src = extraire_attribut($tag, 'src');
1127
+    if (isset($surcharge['src'])) {
1128
+        $tag = str_replace($src, $surcharge['src'], $tag);
1129
+        // si il y a des & dans src, alors ils peuvent provenir d'un &amp
1130
+        // pas garanti comme methode, mais mieux que rien
1131
+        if (strpos($src, '&') !== false) {
1132
+            $tag = str_replace(str_replace("&", "&amp;", $src), $surcharge['src'], $tag);
1133
+        }
1134
+        $src = $surcharge['src'];
1135
+        unset($surcharge['src']);
1136
+    }
1137
+
1138
+    $class = $valeurs['class'];
1139
+    if (isset($surcharge['class'])) {
1140
+        $class = $surcharge['class'];
1141
+        unset($surcharge['class']);
1142
+    }
1143
+    if (strlen($class)) {
1144
+        $tag = inserer_attribut($tag, 'class', $class);
1145
+    }
1146
+
1147
+    if (count($surcharge)) {
1148
+        foreach ($surcharge as $attribut => $valeur) {
1149
+            $tag = inserer_attribut($tag, $attribut, $valeur);
1150
+        }
1151
+    }
1152
+
1153
+    $tag = pipeline('image_ecrire_tag_finir',
1154
+        array(
1155
+            'args' => array(
1156
+                'valeurs' => $valeurs,
1157
+                'surcharge' => $surcharge,
1158
+            ),
1159
+            'data' => $tag
1160
+        )
1161
+    );
1162
+
1163
+    return $tag;
1164 1164
 }
1165 1165
 
1166 1166
 /**
@@ -1183,253 +1183,253 @@  discard block
 block discarded – undo
1183 1183
  *     Description de l'image, sinon null.
1184 1184
  **/
1185 1185
 function _image_creer_vignette($valeurs, $maxWidth, $maxHeight, $process = 'AUTO', $force = false) {
1186
-	// ordre de preference des formats graphiques pour creer les vignettes
1187
-	// le premier format disponible, selon la methode demandee, est utilise
1188
-	$image = $valeurs['fichier'];
1189
-	$format = $valeurs['format_source'];
1190
-	$destdir = dirname($valeurs['fichier_dest']);
1191
-	$destfile = basename($valeurs['fichier_dest'], "." . $valeurs["format_dest"]);
1192
-
1193
-	$format_sortie = $valeurs['format_dest'];
1194
-
1195
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1196
-		$process = $GLOBALS['meta']['image_process'];
1197
-	}
1198
-
1199
-	// si le doc n'est pas une image dans un format accetpable, refuser
1200
-	if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1201
-		return;
1202
-	}
1203
-	$destination = "$destdir/$destfile";
1204
-
1205
-	// calculer la taille
1206
-	if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1207
-		if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1208
-			list($destWidth, $destHeight) = _image_ratio($valeurs['largeur'], $valeurs['hauteur'], $maxWidth, $maxHeight);
1209
-		}
1210
-	} elseif ($process == 'convert' or $process == 'imagick') {
1211
-		$destWidth = $maxWidth;
1212
-		$destHeight = $maxHeight;
1213
-	} else {
1214
-		spip_log("echec $process sur $image");
1215
-
1216
-		return;
1217
-	}
1218
-
1219
-	$vignette = '';
1220
-
1221
-	// Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1222
-	if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1223
-		$vignette = $destination . '.' . $format;
1224
-		@copy($image, $vignette);
1225
-	}
1226
-
1227
-	elseif ($valeurs["format_source"] === 'svg') {
1228
-		if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)){
1229
-			$format_sortie = 'svg';
1230
-			$vignette = $destination . "." . $format_sortie;
1231
-			$valeurs['fichier_dest'] = $vignette;
1232
-			_image_gd_output($svg, $valeurs);
1233
-		}
1234
-	}
1235
-
1236
-	// imagemagick en ligne de commande
1237
-	elseif ($process == 'convert') {
1238
-		if (!defined('_CONVERT_COMMAND')) {
1239
-			define('_CONVERT_COMMAND', 'convert');
1240
-		} // Securite : mes_options.php peut preciser le chemin absolu
1241
-		if (!defined('_RESIZE_COMMAND')) {
1242
-			define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1243
-		}
1244
-		$vignette = $destination . "." . $format_sortie;
1245
-		$commande = str_replace(
1246
-			array('%x', '%y', '%src', '%dest'),
1247
-			array(
1248
-				$destWidth,
1249
-				$destHeight,
1250
-				escapeshellcmd($image),
1251
-				escapeshellcmd($vignette)
1252
-			),
1253
-			_RESIZE_COMMAND);
1254
-		spip_log($commande);
1255
-		exec($commande);
1256
-		if (!@file_exists($vignette)) {
1257
-			spip_log("echec convert sur $vignette");
1258
-
1259
-			return;  // echec commande
1260
-		}
1261
-	}
1262
-
1263
-	// php5 imagemagick
1264
-	elseif ($process == 'imagick') {
1265
-		$vignette = "$destination." . $format_sortie;
1266
-
1267
-		if (!class_exists('Imagick')) {
1268
-			spip_log("Classe Imagick absente !", _LOG_ERREUR);
1269
-
1270
-			return;
1271
-		}
1272
-		$imagick = new Imagick();
1273
-		$imagick->readImage($image);
1274
-		$imagick->resizeImage($destWidth, $destHeight, Imagick::FILTER_LANCZOS,
1275
-			1);//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1276
-		$imagick->writeImage($vignette);
1277
-
1278
-		if (!@file_exists($vignette)) {
1279
-			spip_log("echec imagick sur $vignette");
1280
-
1281
-			return;
1282
-		}
1283
-	}
1284
-
1285
-	// netpbm
1286
-	elseif ($process == "netpbm") {
1287
-		if (!defined('_PNMSCALE_COMMAND')) {
1288
-			define('_PNMSCALE_COMMAND', 'pnmscale');
1289
-		} // Securite : mes_options.php peut preciser le chemin absolu
1290
-		if (_PNMSCALE_COMMAND == '') {
1291
-			return;
1292
-		}
1293
-		$vignette = $destination . "." . $format_sortie;
1294
-		$pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
1295
-		if ($format == "jpg") {
1296
-
1297
-			$jpegtopnm_command = str_replace("pnmscale", "jpegtopnm", _PNMSCALE_COMMAND);
1298
-			exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1299
-			if (!($s = @filesize($vignette))) {
1300
-				spip_unlink($vignette);
1301
-			}
1302
-			if (!@file_exists($vignette)) {
1303
-				spip_log("echec netpbm-jpg sur $vignette");
1304
-
1305
-				return;
1306
-			}
1307
-		} else {
1308
-			if ($format == "gif") {
1309
-				$giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
1310
-				exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1311
-				if (!($s = @filesize($vignette))) {
1312
-					spip_unlink($vignette);
1313
-				}
1314
-				if (!@file_exists($vignette)) {
1315
-					spip_log("echec netpbm-gif sur $vignette");
1316
-
1317
-					return;
1318
-				}
1319
-			} else {
1320
-				if ($format == "png") {
1321
-					$pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
1322
-					exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1323
-					if (!($s = @filesize($vignette))) {
1324
-						spip_unlink($vignette);
1325
-					}
1326
-					if (!@file_exists($vignette)) {
1327
-						spip_log("echec netpbm-png sur $vignette");
1328
-
1329
-						return;
1330
-					}
1331
-				}
1332
-			}
1333
-		}
1334
-	}
1335
-
1336
-	// gd ou gd2
1337
-	elseif ($process == 'gd1' or $process == 'gd2') {
1338
-		if (!function_exists('gd_info')) {
1339
-			spip_log("Librairie GD absente !", _LOG_ERREUR);
1340
-
1341
-			return;
1342
-		}
1343
-		if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1344
-			spip_log("vignette gd1/gd2 impossible : " . $srcWidth * $srcHeight . "pixels");
1345
-
1346
-			return;
1347
-		}
1348
-		$destFormat = $format_sortie;
1349
-		if (!$destFormat) {
1350
-			spip_log("pas de format pour $image");
1351
-
1352
-			return;
1353
-		}
1354
-
1355
-		$fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1356
-		if (!function_exists($fonction_imagecreatefrom)) {
1357
-			return '';
1358
-		}
1359
-		$srcImage = @$fonction_imagecreatefrom($image);
1360
-		if (!$srcImage) {
1361
-			spip_log("echec gd1/gd2");
1362
-
1363
-			return;
1364
-		}
1365
-
1366
-		// Initialisation de l'image destination
1367
-		$destImage = null;
1368
-		if ($process == 'gd2' and $destFormat != "gif") {
1369
-			$destImage = ImageCreateTrueColor($destWidth, $destHeight);
1370
-		}
1371
-		if (!$destImage) {
1372
-			$destImage = ImageCreate($destWidth, $destHeight);
1373
-		}
1374
-
1375
-		// Recopie de l'image d'origine avec adaptation de la taille 
1376
-		$ok = false;
1377
-		if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1378
-			if ($format == "gif") {
1379
-				// Si un GIF est transparent, 
1380
-				// fabriquer un PNG transparent  
1381
-				$transp = imagecolortransparent($srcImage);
1382
-				if ($transp > 0) {
1383
-					$destFormat = "png";
1384
-				}
1385
-			}
1386
-			if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1387
-				// Conserver la transparence 
1388
-				if (function_exists("imageAntiAlias")) {
1389
-					imageAntiAlias($destImage, true);
1390
-				}
1391
-				@imagealphablending($destImage, false);
1392
-				@imagesavealpha($destImage, true);
1393
-			}
1394
-			$ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1395
-		}
1396
-		if (!$ok) {
1397
-			$ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1398
-		}
1399
-
1400
-		// Sauvegarde de l'image destination
1401
-		$valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1402
-		$valeurs['format_dest'] = $format = $destFormat;
1403
-		_image_gd_output($destImage, $valeurs);
1404
-
1405
-		if ($srcImage) {
1406
-			ImageDestroy($srcImage);
1407
-		}
1408
-		ImageDestroy($destImage);
1409
-	}
1410
-
1411
-	if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1412
-		$size = array($destWidth, $destHeight);
1413
-	}
1414
-
1415
-	// Gaffe: en safe mode, pas d'acces a la vignette,
1416
-	// donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1417
-	if ($size[0] < 1) {
1418
-		$size[0] = $destWidth;
1419
-	}
1420
-	if ($size[1] < 1) {
1421
-		$size[1] = $destHeight;
1422
-	}
1423
-
1424
-	$retour['width'] = $largeur = $size[0];
1425
-	$retour['height'] = $hauteur = $size[1];
1426
-
1427
-	$retour['fichier'] = $vignette;
1428
-	$retour['format'] = $format;
1429
-	$retour['date'] = @filemtime($vignette);
1430
-
1431
-	// renvoyer l'image
1432
-	return $retour;
1186
+    // ordre de preference des formats graphiques pour creer les vignettes
1187
+    // le premier format disponible, selon la methode demandee, est utilise
1188
+    $image = $valeurs['fichier'];
1189
+    $format = $valeurs['format_source'];
1190
+    $destdir = dirname($valeurs['fichier_dest']);
1191
+    $destfile = basename($valeurs['fichier_dest'], "." . $valeurs["format_dest"]);
1192
+
1193
+    $format_sortie = $valeurs['format_dest'];
1194
+
1195
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1196
+        $process = $GLOBALS['meta']['image_process'];
1197
+    }
1198
+
1199
+    // si le doc n'est pas une image dans un format accetpable, refuser
1200
+    if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1201
+        return;
1202
+    }
1203
+    $destination = "$destdir/$destfile";
1204
+
1205
+    // calculer la taille
1206
+    if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1207
+        if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1208
+            list($destWidth, $destHeight) = _image_ratio($valeurs['largeur'], $valeurs['hauteur'], $maxWidth, $maxHeight);
1209
+        }
1210
+    } elseif ($process == 'convert' or $process == 'imagick') {
1211
+        $destWidth = $maxWidth;
1212
+        $destHeight = $maxHeight;
1213
+    } else {
1214
+        spip_log("echec $process sur $image");
1215
+
1216
+        return;
1217
+    }
1218
+
1219
+    $vignette = '';
1220
+
1221
+    // Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1222
+    if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1223
+        $vignette = $destination . '.' . $format;
1224
+        @copy($image, $vignette);
1225
+    }
1226
+
1227
+    elseif ($valeurs["format_source"] === 'svg') {
1228
+        if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)){
1229
+            $format_sortie = 'svg';
1230
+            $vignette = $destination . "." . $format_sortie;
1231
+            $valeurs['fichier_dest'] = $vignette;
1232
+            _image_gd_output($svg, $valeurs);
1233
+        }
1234
+    }
1235
+
1236
+    // imagemagick en ligne de commande
1237
+    elseif ($process == 'convert') {
1238
+        if (!defined('_CONVERT_COMMAND')) {
1239
+            define('_CONVERT_COMMAND', 'convert');
1240
+        } // Securite : mes_options.php peut preciser le chemin absolu
1241
+        if (!defined('_RESIZE_COMMAND')) {
1242
+            define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1243
+        }
1244
+        $vignette = $destination . "." . $format_sortie;
1245
+        $commande = str_replace(
1246
+            array('%x', '%y', '%src', '%dest'),
1247
+            array(
1248
+                $destWidth,
1249
+                $destHeight,
1250
+                escapeshellcmd($image),
1251
+                escapeshellcmd($vignette)
1252
+            ),
1253
+            _RESIZE_COMMAND);
1254
+        spip_log($commande);
1255
+        exec($commande);
1256
+        if (!@file_exists($vignette)) {
1257
+            spip_log("echec convert sur $vignette");
1258
+
1259
+            return;  // echec commande
1260
+        }
1261
+    }
1262
+
1263
+    // php5 imagemagick
1264
+    elseif ($process == 'imagick') {
1265
+        $vignette = "$destination." . $format_sortie;
1266
+
1267
+        if (!class_exists('Imagick')) {
1268
+            spip_log("Classe Imagick absente !", _LOG_ERREUR);
1269
+
1270
+            return;
1271
+        }
1272
+        $imagick = new Imagick();
1273
+        $imagick->readImage($image);
1274
+        $imagick->resizeImage($destWidth, $destHeight, Imagick::FILTER_LANCZOS,
1275
+            1);//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1276
+        $imagick->writeImage($vignette);
1277
+
1278
+        if (!@file_exists($vignette)) {
1279
+            spip_log("echec imagick sur $vignette");
1280
+
1281
+            return;
1282
+        }
1283
+    }
1284
+
1285
+    // netpbm
1286
+    elseif ($process == "netpbm") {
1287
+        if (!defined('_PNMSCALE_COMMAND')) {
1288
+            define('_PNMSCALE_COMMAND', 'pnmscale');
1289
+        } // Securite : mes_options.php peut preciser le chemin absolu
1290
+        if (_PNMSCALE_COMMAND == '') {
1291
+            return;
1292
+        }
1293
+        $vignette = $destination . "." . $format_sortie;
1294
+        $pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
1295
+        if ($format == "jpg") {
1296
+
1297
+            $jpegtopnm_command = str_replace("pnmscale", "jpegtopnm", _PNMSCALE_COMMAND);
1298
+            exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1299
+            if (!($s = @filesize($vignette))) {
1300
+                spip_unlink($vignette);
1301
+            }
1302
+            if (!@file_exists($vignette)) {
1303
+                spip_log("echec netpbm-jpg sur $vignette");
1304
+
1305
+                return;
1306
+            }
1307
+        } else {
1308
+            if ($format == "gif") {
1309
+                $giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
1310
+                exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1311
+                if (!($s = @filesize($vignette))) {
1312
+                    spip_unlink($vignette);
1313
+                }
1314
+                if (!@file_exists($vignette)) {
1315
+                    spip_log("echec netpbm-gif sur $vignette");
1316
+
1317
+                    return;
1318
+                }
1319
+            } else {
1320
+                if ($format == "png") {
1321
+                    $pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
1322
+                    exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1323
+                    if (!($s = @filesize($vignette))) {
1324
+                        spip_unlink($vignette);
1325
+                    }
1326
+                    if (!@file_exists($vignette)) {
1327
+                        spip_log("echec netpbm-png sur $vignette");
1328
+
1329
+                        return;
1330
+                    }
1331
+                }
1332
+            }
1333
+        }
1334
+    }
1335
+
1336
+    // gd ou gd2
1337
+    elseif ($process == 'gd1' or $process == 'gd2') {
1338
+        if (!function_exists('gd_info')) {
1339
+            spip_log("Librairie GD absente !", _LOG_ERREUR);
1340
+
1341
+            return;
1342
+        }
1343
+        if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1344
+            spip_log("vignette gd1/gd2 impossible : " . $srcWidth * $srcHeight . "pixels");
1345
+
1346
+            return;
1347
+        }
1348
+        $destFormat = $format_sortie;
1349
+        if (!$destFormat) {
1350
+            spip_log("pas de format pour $image");
1351
+
1352
+            return;
1353
+        }
1354
+
1355
+        $fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1356
+        if (!function_exists($fonction_imagecreatefrom)) {
1357
+            return '';
1358
+        }
1359
+        $srcImage = @$fonction_imagecreatefrom($image);
1360
+        if (!$srcImage) {
1361
+            spip_log("echec gd1/gd2");
1362
+
1363
+            return;
1364
+        }
1365
+
1366
+        // Initialisation de l'image destination
1367
+        $destImage = null;
1368
+        if ($process == 'gd2' and $destFormat != "gif") {
1369
+            $destImage = ImageCreateTrueColor($destWidth, $destHeight);
1370
+        }
1371
+        if (!$destImage) {
1372
+            $destImage = ImageCreate($destWidth, $destHeight);
1373
+        }
1374
+
1375
+        // Recopie de l'image d'origine avec adaptation de la taille 
1376
+        $ok = false;
1377
+        if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1378
+            if ($format == "gif") {
1379
+                // Si un GIF est transparent, 
1380
+                // fabriquer un PNG transparent  
1381
+                $transp = imagecolortransparent($srcImage);
1382
+                if ($transp > 0) {
1383
+                    $destFormat = "png";
1384
+                }
1385
+            }
1386
+            if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1387
+                // Conserver la transparence 
1388
+                if (function_exists("imageAntiAlias")) {
1389
+                    imageAntiAlias($destImage, true);
1390
+                }
1391
+                @imagealphablending($destImage, false);
1392
+                @imagesavealpha($destImage, true);
1393
+            }
1394
+            $ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1395
+        }
1396
+        if (!$ok) {
1397
+            $ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1398
+        }
1399
+
1400
+        // Sauvegarde de l'image destination
1401
+        $valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1402
+        $valeurs['format_dest'] = $format = $destFormat;
1403
+        _image_gd_output($destImage, $valeurs);
1404
+
1405
+        if ($srcImage) {
1406
+            ImageDestroy($srcImage);
1407
+        }
1408
+        ImageDestroy($destImage);
1409
+    }
1410
+
1411
+    if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1412
+        $size = array($destWidth, $destHeight);
1413
+    }
1414
+
1415
+    // Gaffe: en safe mode, pas d'acces a la vignette,
1416
+    // donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1417
+    if ($size[0] < 1) {
1418
+        $size[0] = $destWidth;
1419
+    }
1420
+    if ($size[1] < 1) {
1421
+        $size[1] = $destHeight;
1422
+    }
1423
+
1424
+    $retour['width'] = $largeur = $size[0];
1425
+    $retour['height'] = $hauteur = $size[1];
1426
+
1427
+    $retour['fichier'] = $vignette;
1428
+    $retour['format'] = $format;
1429
+    $retour['date'] = @filemtime($vignette);
1430
+
1431
+    // renvoyer l'image
1432
+    return $retour;
1433 1433
 }
1434 1434
 
1435 1435
 /**
@@ -1449,25 +1449,25 @@  discard block
 block discarded – undo
1449 1449
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1450 1450
  **/
1451 1451
 function _image_ratio($srcWidth, $srcHeight, $maxWidth, $maxHeight) {
1452
-	$ratioWidth = $srcWidth / $maxWidth;
1453
-	$ratioHeight = $srcHeight / $maxHeight;
1454
-
1455
-	if ($ratioWidth <= 1 and $ratioHeight <= 1) {
1456
-		$destWidth = $srcWidth;
1457
-		$destHeight = $srcHeight;
1458
-	} elseif ($ratioWidth < $ratioHeight) {
1459
-		$destWidth = $srcWidth / $ratioHeight;
1460
-		$destHeight = $maxHeight;
1461
-	} else {
1462
-		$destWidth = $maxWidth;
1463
-		$destHeight = $srcHeight / $ratioWidth;
1464
-	}
1465
-
1466
-	return array(
1467
-		ceil($destWidth),
1468
-		ceil($destHeight),
1469
-		max($ratioWidth, $ratioHeight)
1470
-	);
1452
+    $ratioWidth = $srcWidth / $maxWidth;
1453
+    $ratioHeight = $srcHeight / $maxHeight;
1454
+
1455
+    if ($ratioWidth <= 1 and $ratioHeight <= 1) {
1456
+        $destWidth = $srcWidth;
1457
+        $destHeight = $srcHeight;
1458
+    } elseif ($ratioWidth < $ratioHeight) {
1459
+        $destWidth = $srcWidth / $ratioHeight;
1460
+        $destHeight = $maxHeight;
1461
+    } else {
1462
+        $destWidth = $maxWidth;
1463
+        $destHeight = $srcHeight / $ratioWidth;
1464
+    }
1465
+
1466
+    return array(
1467
+        ceil($destWidth),
1468
+        ceil($destHeight),
1469
+        max($ratioWidth, $ratioHeight)
1470
+    );
1471 1471
 }
1472 1472
 
1473 1473
 /**
@@ -1487,25 +1487,25 @@  discard block
 block discarded – undo
1487 1487
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1488 1488
  **/
1489 1489
 function ratio_passe_partout($srcWidth, $srcHeight, $maxWidth, $maxHeight) {
1490
-	$ratioWidth = $srcWidth / $maxWidth;
1491
-	$ratioHeight = $srcHeight / $maxHeight;
1492
-
1493
-	if ($ratioWidth <= 1 and $ratioHeight <= 1) {
1494
-		$destWidth = $srcWidth;
1495
-		$destHeight = $srcHeight;
1496
-	} elseif ($ratioWidth > $ratioHeight) {
1497
-		$destWidth = $srcWidth / $ratioHeight;
1498
-		$destHeight = $maxHeight;
1499
-	} else {
1500
-		$destWidth = $maxWidth;
1501
-		$destHeight = $srcHeight / $ratioWidth;
1502
-	}
1503
-
1504
-	return array(
1505
-		ceil($destWidth),
1506
-		ceil($destHeight),
1507
-		min($ratioWidth, $ratioHeight)
1508
-	);
1490
+    $ratioWidth = $srcWidth / $maxWidth;
1491
+    $ratioHeight = $srcHeight / $maxHeight;
1492
+
1493
+    if ($ratioWidth <= 1 and $ratioHeight <= 1) {
1494
+        $destWidth = $srcWidth;
1495
+        $destHeight = $srcHeight;
1496
+    } elseif ($ratioWidth > $ratioHeight) {
1497
+        $destWidth = $srcWidth / $ratioHeight;
1498
+        $destHeight = $maxHeight;
1499
+    } else {
1500
+        $destWidth = $maxWidth;
1501
+        $destHeight = $srcHeight / $ratioWidth;
1502
+    }
1503
+
1504
+    return array(
1505
+        ceil($destWidth),
1506
+        ceil($destHeight),
1507
+        min($ratioWidth, $ratioHeight)
1508
+    );
1509 1509
 }
1510 1510
 
1511 1511
 
@@ -1518,12 +1518,12 @@  discard block
 block discarded – undo
1518 1518
  * @return string
1519 1519
  */
1520 1520
 function process_image_svg_identite($image) {
1521
-	if ($image['creer']) {
1522
-		$source = $image['fichier'];
1523
-		_image_gd_output($source, $image);
1524
-	}
1521
+    if ($image['creer']) {
1522
+        $source = $image['fichier'];
1523
+        _image_gd_output($source, $image);
1524
+    }
1525 1525
 
1526
-	return _image_ecrire_tag($image, array('src' => $image['fichier_dest']));
1526
+    return _image_ecrire_tag($image, array('src' => $image['fichier_dest']));
1527 1527
 }
1528 1528
 
1529 1529
 
@@ -1556,104 +1556,104 @@  discard block
 block discarded – undo
1556 1556
  *     Code HTML de la balise img produite
1557 1557
  **/
1558 1558
 function process_image_reduire($fonction, $img, $taille, $taille_y, $force, $process = 'AUTO') {
1559
-	$image = false;
1560
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1561
-		$process = $GLOBALS['meta']['image_process'];
1562
-	}
1563
-	# determiner le format de sortie
1564
-	$format_sortie = false; // le choix par defaut sera bon
1565
-	if ($process == "netpbm") {
1566
-		$format_sortie = "jpg";
1567
-	} elseif ($process == 'gd1' or $process == 'gd2') {
1568
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1569
-		// on verifie que l'extension choisie est bonne (en principe oui)
1570
-		$gd_formats = formats_image_acceptables(true);
1571
-		if (is_array($image)
1572
-			and (!in_array($image['format_dest'], $gd_formats)
1573
-				or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1574
-			)
1575
-		) {
1576
-			if ($image['format_source'] == 'jpg') {
1577
-				$formats_sortie = array('jpg', 'png', 'gif');
1578
-			} else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1579
-			{
1580
-				$formats_sortie = array('png', 'jpg', 'gif');
1581
-			}
1582
-			// Choisir le format destination
1583
-			// - on sauve de preference en JPEG (meilleure compression)
1584
-			// - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1585
-			# bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1586
-			# pas *ecrire*
1587
-			$format_sortie = "";
1588
-			foreach ($formats_sortie as $fmt) {
1589
-				if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1590
-					$format_sortie = $fmt;
1591
-					break;
1592
-				}
1593
-			}
1594
-			$image = false;
1595
-		}
1596
-	}
1597
-
1598
-	if (!is_array($image)) {
1599
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1600
-	}
1601
-
1602
-	if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1603
-		spip_log("image_reduire_src:pas de version locale de $img");
1604
-		// on peut resizer en mode html si on dispose des elements
1605
-		if ($srcw = extraire_attribut($img, 'width')
1606
-			and $srch = extraire_attribut($img, 'height')
1607
-		) {
1608
-			list($w, $h) = _image_ratio($srcw, $srch, $taille, $taille_y);
1609
-
1610
-			return _image_tag_changer_taille($img, $w, $h);
1611
-		}
1612
-		// la on n'a pas d'infos sur l'image source... on refile le truc a css
1613
-		// sous la forme style='max-width: NNpx;'
1614
-		return inserer_attribut($img, 'style',
1615
-			"max-width: ${taille}px; max-height: ${taille_y}px");
1616
-	}
1617
-
1618
-	// si l'image est plus petite que la cible retourner une copie cachee de l'image
1619
-	if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1620
-		if ($image['creer']) {
1621
-			@copy($image['fichier'], $image['fichier_dest']);
1622
-		}
1623
-
1624
-		return _image_ecrire_tag($image, array('src' => $image['fichier_dest']));
1625
-	}
1626
-
1627
-	if ($image['creer'] == false && !$force) {
1628
-		return _image_ecrire_tag($image,
1629
-			array('src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']));
1630
-	}
1631
-
1632
-	if (in_array($image["format_source"], _image_extensions_acceptees_en_entree())) {
1633
-		$destWidth = $image['largeur_dest'];
1634
-		$destHeight = $image['hauteur_dest'];
1635
-		$logo = $image['fichier'];
1636
-		$date = $image["date_src"];
1637
-		$preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1638
-
1639
-		if ($preview && $preview['fichier']) {
1640
-			$logo = $preview['fichier'];
1641
-			$destWidth = $preview['width'];
1642
-			$destHeight = $preview['height'];
1643
-			$date = $preview['date'];
1644
-		}
1645
-		// dans l'espace prive mettre un timestamp sur l'adresse 
1646
-		// de l'image, de facon a tromper le cache du navigateur
1647
-		// quand on fait supprimer/reuploader un logo
1648
-		// (pas de filemtime si SAFE MODE)
1649
-		$date = test_espace_prive() ? ('?' . $date) : '';
1650
-
1651
-		return _image_ecrire_tag($image, array('src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight));
1652
-	}
1653
-	else {
1654
-		# BMP, tiff ... les redacteurs osent tout!
1655
-		return $img;
1656
-	}
1559
+    $image = false;
1560
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1561
+        $process = $GLOBALS['meta']['image_process'];
1562
+    }
1563
+    # determiner le format de sortie
1564
+    $format_sortie = false; // le choix par defaut sera bon
1565
+    if ($process == "netpbm") {
1566
+        $format_sortie = "jpg";
1567
+    } elseif ($process == 'gd1' or $process == 'gd2') {
1568
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1569
+        // on verifie que l'extension choisie est bonne (en principe oui)
1570
+        $gd_formats = formats_image_acceptables(true);
1571
+        if (is_array($image)
1572
+            and (!in_array($image['format_dest'], $gd_formats)
1573
+                or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1574
+            )
1575
+        ) {
1576
+            if ($image['format_source'] == 'jpg') {
1577
+                $formats_sortie = array('jpg', 'png', 'gif');
1578
+            } else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1579
+            {
1580
+                $formats_sortie = array('png', 'jpg', 'gif');
1581
+            }
1582
+            // Choisir le format destination
1583
+            // - on sauve de preference en JPEG (meilleure compression)
1584
+            // - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1585
+            # bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1586
+            # pas *ecrire*
1587
+            $format_sortie = "";
1588
+            foreach ($formats_sortie as $fmt) {
1589
+                if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1590
+                    $format_sortie = $fmt;
1591
+                    break;
1592
+                }
1593
+            }
1594
+            $image = false;
1595
+        }
1596
+    }
1597
+
1598
+    if (!is_array($image)) {
1599
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1600
+    }
1601
+
1602
+    if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1603
+        spip_log("image_reduire_src:pas de version locale de $img");
1604
+        // on peut resizer en mode html si on dispose des elements
1605
+        if ($srcw = extraire_attribut($img, 'width')
1606
+            and $srch = extraire_attribut($img, 'height')
1607
+        ) {
1608
+            list($w, $h) = _image_ratio($srcw, $srch, $taille, $taille_y);
1609
+
1610
+            return _image_tag_changer_taille($img, $w, $h);
1611
+        }
1612
+        // la on n'a pas d'infos sur l'image source... on refile le truc a css
1613
+        // sous la forme style='max-width: NNpx;'
1614
+        return inserer_attribut($img, 'style',
1615
+            "max-width: ${taille}px; max-height: ${taille_y}px");
1616
+    }
1617
+
1618
+    // si l'image est plus petite que la cible retourner une copie cachee de l'image
1619
+    if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1620
+        if ($image['creer']) {
1621
+            @copy($image['fichier'], $image['fichier_dest']);
1622
+        }
1623
+
1624
+        return _image_ecrire_tag($image, array('src' => $image['fichier_dest']));
1625
+    }
1626
+
1627
+    if ($image['creer'] == false && !$force) {
1628
+        return _image_ecrire_tag($image,
1629
+            array('src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']));
1630
+    }
1631
+
1632
+    if (in_array($image["format_source"], _image_extensions_acceptees_en_entree())) {
1633
+        $destWidth = $image['largeur_dest'];
1634
+        $destHeight = $image['hauteur_dest'];
1635
+        $logo = $image['fichier'];
1636
+        $date = $image["date_src"];
1637
+        $preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1638
+
1639
+        if ($preview && $preview['fichier']) {
1640
+            $logo = $preview['fichier'];
1641
+            $destWidth = $preview['width'];
1642
+            $destHeight = $preview['height'];
1643
+            $date = $preview['date'];
1644
+        }
1645
+        // dans l'espace prive mettre un timestamp sur l'adresse 
1646
+        // de l'image, de facon a tromper le cache du navigateur
1647
+        // quand on fait supprimer/reuploader un logo
1648
+        // (pas de filemtime si SAFE MODE)
1649
+        $date = test_espace_prive() ? ('?' . $date) : '';
1650
+
1651
+        return _image_ecrire_tag($image, array('src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight));
1652
+    }
1653
+    else {
1654
+        # BMP, tiff ... les redacteurs osent tout!
1655
+        return $img;
1656
+    }
1657 1657
 }
1658 1658
 
1659 1659
 /**
@@ -1668,144 +1668,144 @@  discard block
 block discarded – undo
1668 1668
  */
1669 1669
 class phpthumb_functions {
1670 1670
 
1671
-	/**
1672
-	 * Retourne la couleur d'un pixel dans une image
1673
-	 *
1674
-	 * @param ressource $img
1675
-	 * @param int $x
1676
-	 * @param int $y
1677
-	 * @return array|bool
1678
-	 */
1679
-	public static function GetPixelColor(&$img, $x, $y) {
1680
-		if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1681
-			return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1682
-		}
1683
-		return false;
1684
-	}
1685
-
1686
-	/**
1687
-	 * Retourne un nombre dans une représentation en Little Endian
1688
-	 *
1689
-	 * @param int $number
1690
-	 * @param int $minbytes
1691
-	 * @return string
1692
-	 */
1693
-	public static function LittleEndian2String($number, $minbytes = 1) {
1694
-		$intstring = '';
1695
-		while ($number > 0) {
1696
-			$intstring = $intstring . chr($number & 255);
1697
-			$number >>= 8;
1698
-		}
1699
-
1700
-		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1701
-	}
1702
-
1703
-	/**
1704
-	 * Transforme une ressource GD en image au format ICO
1705
-	 *
1706
-	 * @param array $gd_image_array
1707
-	 *     Tableau de ressources d'images GD
1708
-	 * @return string
1709
-	 *     Image au format ICO
1710
-	 */
1711
-	public static function GD2ICOstring(&$gd_image_array) {
1712
-		foreach ($gd_image_array as $key => $gd_image) {
1713
-
1714
-			$ImageWidths[$key] = ImageSX($gd_image);
1715
-			$ImageHeights[$key] = ImageSY($gd_image);
1716
-			$bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1717
-			$totalcolors[$key] = ImageColorsTotal($gd_image);
1718
-
1719
-			$icXOR[$key] = '';
1720
-			for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1721
-				for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1722
-					$argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1723
-					$a = round(255 * ((127 - $argb['alpha']) / 127));
1724
-					$r = $argb['red'];
1725
-					$g = $argb['green'];
1726
-					$b = $argb['blue'];
1727
-
1728
-					if ($bpp[$key] == 32) {
1729
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1730
-					} elseif ($bpp[$key] == 24) {
1731
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r);
1732
-					}
1733
-
1734
-					if ($a < 128) {
1735
-						@$icANDmask[$key][$y] .= '1';
1736
-					} else {
1737
-						@$icANDmask[$key][$y] .= '0';
1738
-					}
1739
-				}
1740
-				// mask bits are 32-bit aligned per scanline
1741
-				while (strlen($icANDmask[$key][$y]) % 32) {
1742
-					$icANDmask[$key][$y] .= '0';
1743
-				}
1744
-			}
1745
-			$icAND[$key] = '';
1746
-			foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1747
-				for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1748
-					$icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1749
-				}
1750
-			}
1751
-
1752
-		}
1753
-
1754
-		foreach ($gd_image_array as $key => $gd_image) {
1755
-			$biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1756
-
1757
-			// BITMAPINFOHEADER - 40 bytes
1758
-			$BitmapInfoHeader[$key] = '';
1759
-			$BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1760
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1761
-			// The biHeight member specifies the combined
1762
-			// height of the XOR and AND masks.
1763
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1764
-			$BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1765
-			$BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1766
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1767
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1768
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1769
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1770
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1771
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1772
-		}
1773
-
1774
-
1775
-		$icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1776
-		$icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1777
-		$icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1778
-
1779
-		$dwImageOffset = 6 + (count($gd_image_array) * 16);
1780
-		foreach ($gd_image_array as $key => $gd_image) {
1781
-			// ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1782
-
1783
-			$icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1784
-			$icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1785
-			$icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1786
-			$icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1787
-
1788
-			$icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
1789
-			$icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
1790
-
1791
-			$dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
1792
-			$icondata .= phpthumb_functions::LittleEndian2String($dwBytesInRes,
1793
-				4);     // dwBytesInRes;	// How many bytes in this resource?
1794
-
1795
-			$icondata .= phpthumb_functions::LittleEndian2String($dwImageOffset,
1796
-				4);    // dwImageOffset;   // Where in the file is this image?
1797
-			$dwImageOffset += strlen($BitmapInfoHeader[$key]);
1798
-			$dwImageOffset += strlen($icXOR[$key]);
1799
-			$dwImageOffset += strlen($icAND[$key]);
1800
-		}
1801
-
1802
-		foreach ($gd_image_array as $key => $gd_image) {
1803
-			$icondata .= $BitmapInfoHeader[$key];
1804
-			$icondata .= $icXOR[$key];
1805
-			$icondata .= $icAND[$key];
1806
-		}
1807
-
1808
-		return $icondata;
1809
-	}
1671
+    /**
1672
+     * Retourne la couleur d'un pixel dans une image
1673
+     *
1674
+     * @param ressource $img
1675
+     * @param int $x
1676
+     * @param int $y
1677
+     * @return array|bool
1678
+     */
1679
+    public static function GetPixelColor(&$img, $x, $y) {
1680
+        if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1681
+            return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1682
+        }
1683
+        return false;
1684
+    }
1685
+
1686
+    /**
1687
+     * Retourne un nombre dans une représentation en Little Endian
1688
+     *
1689
+     * @param int $number
1690
+     * @param int $minbytes
1691
+     * @return string
1692
+     */
1693
+    public static function LittleEndian2String($number, $minbytes = 1) {
1694
+        $intstring = '';
1695
+        while ($number > 0) {
1696
+            $intstring = $intstring . chr($number & 255);
1697
+            $number >>= 8;
1698
+        }
1699
+
1700
+        return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1701
+    }
1702
+
1703
+    /**
1704
+     * Transforme une ressource GD en image au format ICO
1705
+     *
1706
+     * @param array $gd_image_array
1707
+     *     Tableau de ressources d'images GD
1708
+     * @return string
1709
+     *     Image au format ICO
1710
+     */
1711
+    public static function GD2ICOstring(&$gd_image_array) {
1712
+        foreach ($gd_image_array as $key => $gd_image) {
1713
+
1714
+            $ImageWidths[$key] = ImageSX($gd_image);
1715
+            $ImageHeights[$key] = ImageSY($gd_image);
1716
+            $bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1717
+            $totalcolors[$key] = ImageColorsTotal($gd_image);
1718
+
1719
+            $icXOR[$key] = '';
1720
+            for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1721
+                for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1722
+                    $argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1723
+                    $a = round(255 * ((127 - $argb['alpha']) / 127));
1724
+                    $r = $argb['red'];
1725
+                    $g = $argb['green'];
1726
+                    $b = $argb['blue'];
1727
+
1728
+                    if ($bpp[$key] == 32) {
1729
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1730
+                    } elseif ($bpp[$key] == 24) {
1731
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r);
1732
+                    }
1733
+
1734
+                    if ($a < 128) {
1735
+                        @$icANDmask[$key][$y] .= '1';
1736
+                    } else {
1737
+                        @$icANDmask[$key][$y] .= '0';
1738
+                    }
1739
+                }
1740
+                // mask bits are 32-bit aligned per scanline
1741
+                while (strlen($icANDmask[$key][$y]) % 32) {
1742
+                    $icANDmask[$key][$y] .= '0';
1743
+                }
1744
+            }
1745
+            $icAND[$key] = '';
1746
+            foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1747
+                for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1748
+                    $icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1749
+                }
1750
+            }
1751
+
1752
+        }
1753
+
1754
+        foreach ($gd_image_array as $key => $gd_image) {
1755
+            $biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1756
+
1757
+            // BITMAPINFOHEADER - 40 bytes
1758
+            $BitmapInfoHeader[$key] = '';
1759
+            $BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1760
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1761
+            // The biHeight member specifies the combined
1762
+            // height of the XOR and AND masks.
1763
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1764
+            $BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1765
+            $BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1766
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1767
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1768
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1769
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1770
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1771
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1772
+        }
1773
+
1774
+
1775
+        $icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1776
+        $icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1777
+        $icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1778
+
1779
+        $dwImageOffset = 6 + (count($gd_image_array) * 16);
1780
+        foreach ($gd_image_array as $key => $gd_image) {
1781
+            // ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1782
+
1783
+            $icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1784
+            $icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1785
+            $icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1786
+            $icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1787
+
1788
+            $icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
1789
+            $icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
1790
+
1791
+            $dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
1792
+            $icondata .= phpthumb_functions::LittleEndian2String($dwBytesInRes,
1793
+                4);     // dwBytesInRes;	// How many bytes in this resource?
1794
+
1795
+            $icondata .= phpthumb_functions::LittleEndian2String($dwImageOffset,
1796
+                4);    // dwImageOffset;   // Where in the file is this image?
1797
+            $dwImageOffset += strlen($BitmapInfoHeader[$key]);
1798
+            $dwImageOffset += strlen($icXOR[$key]);
1799
+            $dwImageOffset += strlen($icAND[$key]);
1800
+        }
1801
+
1802
+        foreach ($gd_image_array as $key => $gd_image) {
1803
+            $icondata .= $BitmapInfoHeader[$key];
1804
+            $icondata .= $icXOR[$key];
1805
+            $icondata .= $icAND[$key];
1806
+        }
1807
+
1808
+        return $icondata;
1809
+    }
1810 1810
 
1811 1811
 }
Please login to merge, or discard this patch.
Spacing   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -44,13 +44,13 @@  discard block
 block discarded – undo
44 44
 	$blue = dechex($blue);
45 45
 
46 46
 	if (strlen($red) == 1) {
47
-		$red = "0" . $red;
47
+		$red = "0".$red;
48 48
 	}
49 49
 	if (strlen($green) == 1) {
50
-		$green = "0" . $green;
50
+		$green = "0".$green;
51 51
 	}
52 52
 	if (strlen($blue) == 1) {
53
-		$blue = "0" . $blue;
53
+		$blue = "0".$blue;
54 54
 	}
55 55
 
56 56
 	return "$red$green$blue";
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	$couleur = couleur_html_to_hex($couleur);
69 69
 	$couleur = ltrim($couleur, '#');
70 70
 	if (strlen($couleur) === 3) {
71
-		$couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
71
+		$couleur = $couleur[0].$couleur[0].$couleur[1].$couleur[1].$couleur[2].$couleur[2];
72 72
 	}
73 73
 	$retour["red"] = hexdec(substr($couleur, 0, 2));
74 74
 	$retour["green"] = hexdec(substr($couleur, 2, 2));
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 	  and $extension = _image_trouver_extension_depuis_mime("image/".$regs[1])
160 160
 		and in_array($extension, _image_extensions_acceptees_en_entree())
161 161
 	) {
162
-		$local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
162
+		$local = sous_repertoire(_DIR_VAR, 'image-data').md5($regs[2]).'.'._image_extension_normalisee($extension);
163 163
 		if (!file_exists($local)) {
164 164
 			ecrire_fichier($local, base64_decode($regs[2]));
165 165
 		}
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	// les protocoles web prennent au moins 3 lettres
174 174
 	if (tester_url_absolue($source)) {
175 175
 		include_spip('inc/distant');
176
-		$fichier = _DIR_RACINE . copie_locale($source);
176
+		$fichier = _DIR_RACINE.copie_locale($source);
177 177
 		if (!$fichier) {
178 178
 			return "";
179 179
 		}
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 
199 199
 	if ($forcer_format !== false
200 200
 		// 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
201
-		and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format,_image_extensions_acceptees_en_sortie()))) {
201
+		and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format, _image_extensions_acceptees_en_sortie()))) {
202 202
 		$terminaison_dest = $forcer_format;
203 203
 	}
204 204
 
@@ -260,9 +260,9 @@  discard block
 block discarded – undo
260 260
 			// on garde la terminaison initiale car image simplement copiee
261 261
 			// et on postfixe son nom avec un md5 du path
262 262
 			$terminaison_dest = $terminaison;
263
-			$fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
263
+			$fichier_dest .= '-'.substr(md5("$identifiant"), 0, 5);
264 264
 		} else {
265
-			$fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
265
+			$fichier_dest .= '-'.substr(md5("$identifiant-$effet"), 0, 5);
266 266
 		}
267 267
 		$cache = sous_repertoire(_DIR_VAR, $cache);
268 268
 		$cache = sous_repertoire($cache, $effet);
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 		$fichier_dest = substr($fichier_dest, 2);
274 274
 	}
275 275
 
276
-	$fichier_dest = $cache . $fichier_dest . "." . $terminaison_dest;
276
+	$fichier_dest = $cache.$fichier_dest.".".$terminaison_dest;
277 277
 
278 278
 	$GLOBALS["images_calculees"][] = $fichier_dest;
279 279
 
@@ -309,14 +309,14 @@  discard block
 block discarded – undo
309 309
 	}
310 310
 
311 311
 	if ($creer) {
312
-		spip_log("filtre image " . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
313
-			"images" . _LOG_DEBUG);
312
+		spip_log("filtre image ".($fonction_creation ? reset($fonction_creation) : '')."[$effet] sur $fichier",
313
+			"images"._LOG_DEBUG);
314 314
 	}
315 315
 
316 316
 	$term_fonction = _image_trouver_extension_pertinente($fichier);
317
-	$ret["fonction_imagecreatefrom"] = "_imagecreatefrom" . $term_fonction;
317
+	$ret["fonction_imagecreatefrom"] = "_imagecreatefrom".$term_fonction;
318 318
 	$ret["fichier"] = $fichier;
319
-	$ret["fonction_image"] = "_image_image" . $terminaison_dest;
319
+	$ret["fonction_image"] = "_image_image".$terminaison_dest;
320 320
 	$ret["fichier_dest"] = $fichier_dest;
321 321
 	$ret["format_source"] = _image_extension_normalisee($terminaison);
322 322
 	$ret["format_dest"] = $terminaison_dest;
@@ -389,9 +389,9 @@  discard block
 block discarded – undo
389 389
 /**
390 390
  * @return array|string[]|null
391 391
  */
392
-function _image_extensions_acceptees_en_sortie(){
392
+function _image_extensions_acceptees_en_sortie() {
393 393
 	static $extensions = null;
394
-	if (empty($extensions)){
394
+	if (empty($extensions)) {
395 395
 		$extensions = _image_extensions_acceptees_en_entree();
396 396
 		$extensions = array_diff($extensions, ['jpeg']);
397 397
 		if (in_array('gif', $extensions) and !function_exists('imagegif')) {
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 	return $extensions;
406 406
 }
407 407
 
408
-function _image_extension_normalisee($extension){
408
+function _image_extension_normalisee($extension) {
409 409
 	$extension = strtolower($extension);
410 410
 	if ($extension === 'jpeg') {
411 411
 		$extension = 'jpg';
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 	return $extension;
414 414
 }
415 415
 
416
-function _image_extensions_conservent_transparence(){
416
+function _image_extensions_conservent_transparence() {
417 417
 	return ['png', 'webp'];
418 418
 }
419 419
 
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 
464 464
 	$_terminaison = _image_trouver_extension_depuis_mime($mime);
465 465
 	if ($_terminaison and $_terminaison !== $terminaison) {
466
-		spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", "images." . _LOG_INFO_IMPORTANTE);
466
+		spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", "images."._LOG_INFO_IMPORTANTE);
467 467
 		$terminaison = $_terminaison;
468 468
 	}
469 469
 	return $terminaison;
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
 	if (!function_exists('imagepng')) {
614 614
 		return false;
615 615
 	}
616
-	$tmp = $fichier . ".tmp";
616
+	$tmp = $fichier.".tmp";
617 617
 	$ret = imagepng($img, $tmp);
618 618
 	if (file_exists($tmp)) {
619 619
 		$taille_test = getimagesize($tmp);
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 	if (!function_exists('imagegif')) {
649 649
 		return false;
650 650
 	}
651
-	$tmp = $fichier . ".tmp";
651
+	$tmp = $fichier.".tmp";
652 652
 	$ret = imagegif($img, $tmp);
653 653
 	if (file_exists($tmp)) {
654 654
 		$taille_test = getimagesize($tmp);
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 	if (!function_exists('imagejpeg')) {
689 689
 		return false;
690 690
 	}
691
-	$tmp = $fichier . ".tmp";
691
+	$tmp = $fichier.".tmp";
692 692
 
693 693
 	// Enable interlancing
694 694
 	imageinterlace($img, true);
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 	if (!function_exists('imagewebp')) {
750 750
 		return false;
751 751
 	}
752
-	$tmp = $fichier . ".tmp";
752
+	$tmp = $fichier.".tmp";
753 753
 	$ret = imagewebp($img, $tmp, $qualite);
754 754
 	if (file_exists($tmp)) {
755 755
 		$taille_test = getimagesize($tmp);
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
  */
784 784
 function _image_imagesvg($img, $fichier) {
785 785
 
786
-	$tmp = $fichier . ".tmp";
786
+	$tmp = $fichier.".tmp";
787 787
 	if (strpos($img, "<") === false) {
788 788
 		$img = supprimer_timestamp($img);
789 789
 		if (!file_exists($img)) {
@@ -839,12 +839,12 @@  discard block
 block discarded – undo
839 839
  *     - false sinon.
840 840
  */
841 841
 function _image_gd_output($img, $valeurs, $qualite = _IMG_GD_QUALITE) {
842
-	$fonction = "_image_image" . $valeurs['format_dest'];
842
+	$fonction = "_image_image".$valeurs['format_dest'];
843 843
 	$ret = false;
844 844
 	#un flag pour reperer les images gravees
845 845
 	$lock =
846 846
 		!statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
847
-	or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'));
847
+	or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'].'.src'));
848 848
 	if (
849 849
 		function_exists($fonction)
850 850
 		&& ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
@@ -855,7 +855,7 @@  discard block
 block discarded – undo
855 855
 			// dans tous les cas mettre a jour la taille de l'image finale
856 856
 			list($valeurs["hauteur_dest"], $valeurs["largeur_dest"]) = taille_image($valeurs['fichier_dest']);
857 857
 			$valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
858
-			ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
858
+			ecrire_fichier($valeurs['fichier_dest'].'.src', serialize($valeurs), true);
859 859
 		}
860 860
 	}
861 861
 
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
 function reconstruire_image_intermediaire($fichier_manquant) {
875 875
 	$reconstruire = array();
876 876
 	$fichier = $fichier_manquant;
877
-	while (strpos($fichier,"://")===false
877
+	while (strpos($fichier, "://") === false
878 878
 		and !@file_exists($fichier)
879 879
 		and lire_fichier($src = "$fichier.src", $source)
880 880
 		and $valeurs = unserialize($source)
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
  *     Chemin du fichier d'image calculé
912 912
  **/
913 913
 function ramasse_miettes($fichier) {
914
-	if (strpos($fichier,"://")!==false
914
+	if (strpos($fichier, "://") !== false
915 915
 		or !lire_fichier($src = "$fichier.src", $source)
916 916
 		or !$valeurs = unserialize($source)
917 917
 	) {
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
 	}
968 968
 	# si jamais le fichier final n'a pas ete calcule car suppose temporaire
969 969
 	# et qu'il ne s'agit pas d'une URL
970
-	if (strpos($fichier,"://")===false and !@file_exists($fichier)) {
970
+	if (strpos($fichier, "://") === false and !@file_exists($fichier)) {
971 971
 		reconstruire_image_intermediaire($fichier);
972 972
 	}
973 973
 	ramasse_miettes($fichier);
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
 
1065 1065
 	// attributs deprecies. Transformer en CSS
1066 1066
 	if ($espace = extraire_attribut($tag, 'hspace')) {
1067
-		$style = "margin:${espace}px;" . $style;
1067
+		$style = "margin:${espace}px;".$style;
1068 1068
 		$tag = inserer_attribut($tag, 'hspace', '');
1069 1069
 	}
1070 1070
 
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
 	$image = $valeurs['fichier'];
1189 1189
 	$format = $valeurs['format_source'];
1190 1190
 	$destdir = dirname($valeurs['fichier_dest']);
1191
-	$destfile = basename($valeurs['fichier_dest'], "." . $valeurs["format_dest"]);
1191
+	$destfile = basename($valeurs['fichier_dest'], ".".$valeurs["format_dest"]);
1192 1192
 
1193 1193
 	$format_sortie = $valeurs['format_dest'];
1194 1194
 
@@ -1220,14 +1220,14 @@  discard block
 block discarded – undo
1220 1220
 
1221 1221
 	// Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1222 1222
 	if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1223
-		$vignette = $destination . '.' . $format;
1223
+		$vignette = $destination.'.'.$format;
1224 1224
 		@copy($image, $vignette);
1225 1225
 	}
1226 1226
 
1227 1227
 	elseif ($valeurs["format_source"] === 'svg') {
1228
-		if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)){
1228
+		if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)) {
1229 1229
 			$format_sortie = 'svg';
1230
-			$vignette = $destination . "." . $format_sortie;
1230
+			$vignette = $destination.".".$format_sortie;
1231 1231
 			$valeurs['fichier_dest'] = $vignette;
1232 1232
 			_image_gd_output($svg, $valeurs);
1233 1233
 		}
@@ -1239,9 +1239,9 @@  discard block
 block discarded – undo
1239 1239
 			define('_CONVERT_COMMAND', 'convert');
1240 1240
 		} // Securite : mes_options.php peut preciser le chemin absolu
1241 1241
 		if (!defined('_RESIZE_COMMAND')) {
1242
-			define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1242
+			define('_RESIZE_COMMAND', _CONVERT_COMMAND.' -quality '._IMG_CONVERT_QUALITE.' -resize %xx%y! %src %dest');
1243 1243
 		}
1244
-		$vignette = $destination . "." . $format_sortie;
1244
+		$vignette = $destination.".".$format_sortie;
1245 1245
 		$commande = str_replace(
1246 1246
 			array('%x', '%y', '%src', '%dest'),
1247 1247
 			array(
@@ -1256,13 +1256,13 @@  discard block
 block discarded – undo
1256 1256
 		if (!@file_exists($vignette)) {
1257 1257
 			spip_log("echec convert sur $vignette");
1258 1258
 
1259
-			return;  // echec commande
1259
+			return; // echec commande
1260 1260
 		}
1261 1261
 	}
1262 1262
 
1263 1263
 	// php5 imagemagick
1264 1264
 	elseif ($process == 'imagick') {
1265
-		$vignette = "$destination." . $format_sortie;
1265
+		$vignette = "$destination.".$format_sortie;
1266 1266
 
1267 1267
 		if (!class_exists('Imagick')) {
1268 1268
 			spip_log("Classe Imagick absente !", _LOG_ERREUR);
@@ -1272,7 +1272,7 @@  discard block
 block discarded – undo
1272 1272
 		$imagick = new Imagick();
1273 1273
 		$imagick->readImage($image);
1274 1274
 		$imagick->resizeImage($destWidth, $destHeight, Imagick::FILTER_LANCZOS,
1275
-			1);//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1275
+			1); //, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1276 1276
 		$imagick->writeImage($vignette);
1277 1277
 
1278 1278
 		if (!@file_exists($vignette)) {
@@ -1290,12 +1290,12 @@  discard block
 block discarded – undo
1290 1290
 		if (_PNMSCALE_COMMAND == '') {
1291 1291
 			return;
1292 1292
 		}
1293
-		$vignette = $destination . "." . $format_sortie;
1293
+		$vignette = $destination.".".$format_sortie;
1294 1294
 		$pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
1295 1295
 		if ($format == "jpg") {
1296 1296
 
1297 1297
 			$jpegtopnm_command = str_replace("pnmscale", "jpegtopnm", _PNMSCALE_COMMAND);
1298
-			exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1298
+			exec("$jpegtopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette");
1299 1299
 			if (!($s = @filesize($vignette))) {
1300 1300
 				spip_unlink($vignette);
1301 1301
 			}
@@ -1307,7 +1307,7 @@  discard block
 block discarded – undo
1307 1307
 		} else {
1308 1308
 			if ($format == "gif") {
1309 1309
 				$giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
1310
-				exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1310
+				exec("$giftopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette");
1311 1311
 				if (!($s = @filesize($vignette))) {
1312 1312
 					spip_unlink($vignette);
1313 1313
 				}
@@ -1319,7 +1319,7 @@  discard block
 block discarded – undo
1319 1319
 			} else {
1320 1320
 				if ($format == "png") {
1321 1321
 					$pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
1322
-					exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1322
+					exec("$pngtopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette");
1323 1323
 					if (!($s = @filesize($vignette))) {
1324 1324
 						spip_unlink($vignette);
1325 1325
 					}
@@ -1341,7 +1341,7 @@  discard block
 block discarded – undo
1341 1341
 			return;
1342 1342
 		}
1343 1343
 		if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1344
-			spip_log("vignette gd1/gd2 impossible : " . $srcWidth * $srcHeight . "pixels");
1344
+			spip_log("vignette gd1/gd2 impossible : ".$srcWidth * $srcHeight."pixels");
1345 1345
 
1346 1346
 			return;
1347 1347
 		}
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
 		// de l'image, de facon a tromper le cache du navigateur
1647 1647
 		// quand on fait supprimer/reuploader un logo
1648 1648
 		// (pas de filemtime si SAFE MODE)
1649
-		$date = test_espace_prive() ? ('?' . $date) : '';
1649
+		$date = test_espace_prive() ? ('?'.$date) : '';
1650 1650
 
1651 1651
 		return _image_ecrire_tag($image, array('src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight));
1652 1652
 	}
@@ -1693,7 +1693,7 @@  discard block
 block discarded – undo
1693 1693
 	public static function LittleEndian2String($number, $minbytes = 1) {
1694 1694
 		$intstring = '';
1695 1695
 		while ($number > 0) {
1696
-			$intstring = $intstring . chr($number & 255);
1696
+			$intstring = $intstring.chr($number & 255);
1697 1697
 			$number >>= 8;
1698 1698
 		}
1699 1699
 
@@ -1726,9 +1726,9 @@  discard block
 block discarded – undo
1726 1726
 					$b = $argb['blue'];
1727 1727
 
1728 1728
 					if ($bpp[$key] == 32) {
1729
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1729
+						$icXOR[$key] .= chr($b).chr($g).chr($r).chr($a);
1730 1730
 					} elseif ($bpp[$key] == 24) {
1731
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r);
1731
+						$icXOR[$key] .= chr($b).chr($g).chr($r);
1732 1732
 					}
1733 1733
 
1734 1734
 					if ($a < 128) {
@@ -1756,44 +1756,44 @@  discard block
 block discarded – undo
1756 1756
 
1757 1757
 			// BITMAPINFOHEADER - 40 bytes
1758 1758
 			$BitmapInfoHeader[$key] = '';
1759
-			$BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1760
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1759
+			$BitmapInfoHeader[$key] .= "\x28\x00\x00\x00"; // DWORD  biSize;
1760
+			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4); // LONG   biWidth;
1761 1761
 			// The biHeight member specifies the combined
1762 1762
 			// height of the XOR and AND masks.
1763 1763
 			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1764
-			$BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1765
-			$BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1766
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1767
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1768
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1769
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1770
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1771
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1764
+			$BitmapInfoHeader[$key] .= "\x01\x00"; // WORD   biPlanes;
1765
+			$BitmapInfoHeader[$key] .= chr($bpp[$key])."\x00"; // wBitCount;
1766
+			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00"; // DWORD  biCompression;
1767
+			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4); // DWORD  biSizeImage;
1768
+			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00"; // LONG   biXPelsPerMeter;
1769
+			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00"; // LONG   biYPelsPerMeter;
1770
+			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00"; // DWORD  biClrUsed;
1771
+			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00"; // DWORD  biClrImportant;
1772 1772
 		}
1773 1773
 
1774 1774
 
1775
-		$icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1776
-		$icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1777
-		$icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1775
+		$icondata = "\x00\x00"; // idReserved;   // Reserved (must be 0)
1776
+		$icondata .= "\x01\x00"; // idType;	   // Resource Type (1 for icons)
1777
+		$icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2); // idCount;	  // How many images?
1778 1778
 
1779 1779
 		$dwImageOffset = 6 + (count($gd_image_array) * 16);
1780 1780
 		foreach ($gd_image_array as $key => $gd_image) {
1781 1781
 			// ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1782 1782
 
1783
-			$icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1784
-			$icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1785
-			$icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1786
-			$icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1783
+			$icondata .= chr($ImageWidths[$key]); // bWidth;		  // Width, in pixels, of the image
1784
+			$icondata .= chr($ImageHeights[$key]); // bHeight;		 // Height, in pixels, of the image
1785
+			$icondata .= chr($totalcolors[$key]); // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1786
+			$icondata .= "\x00"; // bReserved;	   // Reserved ( must be 0)
1787 1787
 
1788
-			$icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
1789
-			$icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
1788
+			$icondata .= "\x01\x00"; // wPlanes;		 // Color Planes
1789
+			$icondata .= chr($bpp[$key])."\x00"; // wBitCount;	   // Bits per pixel
1790 1790
 
1791 1791
 			$dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
1792 1792
 			$icondata .= phpthumb_functions::LittleEndian2String($dwBytesInRes,
1793
-				4);     // dwBytesInRes;	// How many bytes in this resource?
1793
+				4); // dwBytesInRes;	// How many bytes in this resource?
1794 1794
 
1795 1795
 			$icondata .= phpthumb_functions::LittleEndian2String($dwImageOffset,
1796
-				4);    // dwImageOffset;   // Where in the file is this image?
1796
+				4); // dwImageOffset;   // Where in the file is this image?
1797 1797
 			$dwImageOffset += strlen($BitmapInfoHeader[$key]);
1798 1798
 			$dwImageOffset += strlen($icXOR[$key]);
1799 1799
 			$dwImageOffset += strlen($icAND[$key]);
Please login to merge, or discard this patch.
prive/formulaires/configurer_reducteur.php 1 patch
Indentation   +86 added lines, -86 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
 
24 24
 /**
@@ -28,22 +28,22 @@  discard block
 block discarded – undo
28 28
  *     Environnement du formulaire
29 29
  **/
30 30
 function formulaires_configurer_reducteur_charger_dist() {
31
-	$valeurs = array();
32
-	foreach (array(
33
-		'image_process',
34
-		'formats_graphiques',
35
-		'creer_preview',
36
-		'taille_preview',
37
-	) as $m) {
38
-		$valeurs[$m] = isset($GLOBALS['meta'][$m]) ? $GLOBALS['meta'][$m] : null;
39
-	}
31
+    $valeurs = array();
32
+    foreach (array(
33
+        'image_process',
34
+        'formats_graphiques',
35
+        'creer_preview',
36
+        'taille_preview',
37
+    ) as $m) {
38
+        $valeurs[$m] = isset($GLOBALS['meta'][$m]) ? $GLOBALS['meta'][$m] : null;
39
+    }
40 40
 
41
-	$valeurs['taille_preview'] = intval($valeurs['taille_preview']);
42
-	if ($valeurs['taille_preview'] < 10) {
43
-		$valeurs['taille_preview'] = 120;
44
-	}
41
+    $valeurs['taille_preview'] = intval($valeurs['taille_preview']);
42
+    if ($valeurs['taille_preview'] < 10) {
43
+        $valeurs['taille_preview'] = 120;
44
+    }
45 45
 
46
-	return $valeurs;
46
+    return $valeurs;
47 47
 }
48 48
 
49 49
 
@@ -54,51 +54,51 @@  discard block
 block discarded – undo
54 54
  *     Retours des traitements
55 55
  **/
56 56
 function formulaires_configurer_reducteur_traiter_dist() {
57
-	$res = array('editable' => true);
57
+    $res = array('editable' => true);
58 58
 
59
-	if (is_array($image_process = _request('image_process_'))) {
60
-		$image_process = array_keys($image_process);
61
-		$image_process = reset($image_process);
59
+    if (is_array($image_process = _request('image_process_'))) {
60
+        $image_process = array_keys($image_process);
61
+        $image_process = reset($image_process);
62 62
 
63
-		// application du choix de vignette
64
-		if ($image_process) {
65
-			// mettre a jour les formats graphiques lisibles
66
-			switch ($image_process) {
67
-				case 'gd1':
68
-				case 'gd2':
69
-					$formats_graphiques = $GLOBALS['meta']['gd_formats_read'];
70
-					break;
71
-				case 'netpbm':
72
-					$formats_graphiques = $GLOBALS['meta']['netpbm_formats'];
73
-					break;
74
-				case 'convert':
75
-				case 'imagick':
76
-					$formats_graphiques = 'gif,jpg,png,webp';
77
-					break;
78
-				default: #debug
79
-					$formats_graphiques = '';
80
-					$image_process = 'non';
81
-					break;
82
-			}
83
-			ecrire_meta('formats_graphiques', $formats_graphiques, 'non');
84
-			ecrire_meta('image_process', $image_process, 'non');
85
-		}
86
-	}
63
+        // application du choix de vignette
64
+        if ($image_process) {
65
+            // mettre a jour les formats graphiques lisibles
66
+            switch ($image_process) {
67
+                case 'gd1':
68
+                case 'gd2':
69
+                    $formats_graphiques = $GLOBALS['meta']['gd_formats_read'];
70
+                    break;
71
+                case 'netpbm':
72
+                    $formats_graphiques = $GLOBALS['meta']['netpbm_formats'];
73
+                    break;
74
+                case 'convert':
75
+                case 'imagick':
76
+                    $formats_graphiques = 'gif,jpg,png,webp';
77
+                    break;
78
+                default: #debug
79
+                    $formats_graphiques = '';
80
+                    $image_process = 'non';
81
+                    break;
82
+            }
83
+            ecrire_meta('formats_graphiques', $formats_graphiques, 'non');
84
+            ecrire_meta('image_process', $image_process, 'non');
85
+        }
86
+    }
87 87
 
88
-	foreach (array(
89
-		'creer_preview'
90
-	) as $m) {
91
-		if (!is_null($v = _request($m))) {
92
-			ecrire_meta($m, $v == 'oui' ? 'oui' : 'non');
93
-		}
94
-	}
95
-	if (!is_null($v = _request('taille_preview'))) {
96
-		ecrire_meta('taille_preview', intval($v));
97
-	}
88
+    foreach (array(
89
+        'creer_preview'
90
+    ) as $m) {
91
+        if (!is_null($v = _request($m))) {
92
+            ecrire_meta($m, $v == 'oui' ? 'oui' : 'non');
93
+        }
94
+    }
95
+    if (!is_null($v = _request('taille_preview'))) {
96
+        ecrire_meta('taille_preview', intval($v));
97
+    }
98 98
 
99
-	$res['message_ok'] = _T('config_info_enregistree');
99
+    $res['message_ok'] = _T('config_info_enregistree');
100 100
 
101
-	return $res;
101
+    return $res;
102 102
 }
103 103
 
104 104
 /**
@@ -111,36 +111,36 @@  discard block
 block discarded – undo
111 111
  *     URL d'action pour tester la librairie graphique en créant une vignette
112 112
  **/
113 113
 function url_vignette_choix($process) {
114
-	switch ($process) {
115
-		case 'gd2':
116
-			if (!function_exists('ImageCreateTrueColor')) {
117
-				return '';
118
-			}
119
-			break;
120
-		case 'gd1':
121
-			if (!function_exists('ImageGif')
122
-				and !function_exists('ImageJpeg')
123
-				and !function_exists('ImagePng')
124
-			) {
125
-				return '';
126
-			}
127
-			break;
128
-		case 'netpbm':
129
-			if (defined('_PNMSCALE_COMMAND') and _PNMSCALE_COMMAND == '') {
130
-				return '';
131
-			}
132
-			break;
133
-		case 'imagick':
134
-			if (!method_exists('Imagick', 'readImage')) {
135
-				return '';
136
-			}
137
-			break;
138
-		case 'convert':
139
-			if (defined('_CONVERT_COMMAND') and _CONVERT_COMMAND == '') {
140
-				return '';
141
-			}
142
-			break;
143
-	}
114
+    switch ($process) {
115
+        case 'gd2':
116
+            if (!function_exists('ImageCreateTrueColor')) {
117
+                return '';
118
+            }
119
+            break;
120
+        case 'gd1':
121
+            if (!function_exists('ImageGif')
122
+                and !function_exists('ImageJpeg')
123
+                and !function_exists('ImagePng')
124
+            ) {
125
+                return '';
126
+            }
127
+            break;
128
+        case 'netpbm':
129
+            if (defined('_PNMSCALE_COMMAND') and _PNMSCALE_COMMAND == '') {
130
+                return '';
131
+            }
132
+            break;
133
+        case 'imagick':
134
+            if (!method_exists('Imagick', 'readImage')) {
135
+                return '';
136
+            }
137
+            break;
138
+        case 'convert':
139
+            if (defined('_CONVERT_COMMAND') and _CONVERT_COMMAND == '') {
140
+                return '';
141
+            }
142
+            break;
143
+    }
144 144
 
145
-	return generer_url_action('tester', "arg=$process&time=" . time());
145
+    return generer_url_action('tester', "arg=$process&time=" . time());
146 146
 }
Please login to merge, or discard this patch.
ecrire/action/tester.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -30,154 +30,154 @@  discard block
 block discarded – undo
30 30
  * redirige sur l'image ainsi créée (sinon sur une image d'echec).
31 31
  **/
32 32
 function action_tester_dist() {
33
-	$arg = _request('arg');
34
-
35
-	$gd_formats = array();
36
-	$gd_formats_read_gif = "";
37
-	// verifier les formats acceptes par GD
38
-	if ($arg == "gd1") {
39
-		// Si GD est installe et php >= 4.0.2
40
-		if (function_exists('imagetypes')) {
41
-			if (imagetypes() & IMG_GIF) {
42
-				$gd_formats[] = "gif";
43
-			} else {
44
-				# Attention GD sait lire le gif mais pas forcement l'ecrire
45
-				if (function_exists('ImageCreateFromGIF')) {
46
-					$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
47
-					if ($srcImage) {
48
-						$gd_formats_read_gif = ",gif";
49
-						ImageDestroy($srcImage);
50
-					}
51
-				}
52
-			}
53
-
54
-			if (imagetypes() & IMG_JPG) {
55
-				$gd_formats[] = "jpg";
56
-			}
57
-			if (imagetypes() & IMG_PNG) {
58
-				$gd_formats[] = "png";
59
-			}
60
-			if (imagetypes() & IMG_WEBP) {
61
-				$gd_formats[] = "webp";
62
-			}
63
-		} else {
64
-			# ancienne methode de detection des formats, qui en plus
65
-			# est bugguee car elle teste les formats en lecture
66
-			# alors que la valeur deduite sert a identifier
67
-			# les formats disponibles en ecriture... (cf. inc_logos)
68
-
69
-			if (function_exists('ImageCreateFromJPEG')) {
70
-				$srcImage = @ImageCreateFromJPEG(_ROOT_IMG_PACK . "test.jpg");
71
-				if ($srcImage) {
72
-					$gd_formats[] = "jpg";
73
-					ImageDestroy($srcImage);
74
-				}
75
-			}
76
-			if (function_exists('ImageCreateFromGIF')) {
77
-				$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
78
-				if ($srcImage) {
79
-					$gd_formats[] = "gif";
80
-					ImageDestroy($srcImage);
81
-				}
82
-			}
83
-			if (function_exists('ImageCreateFromPNG')) {
84
-				$srcImage = @ImageCreateFromPNG(_ROOT_IMG_PACK . "test.png");
85
-				if ($srcImage) {
86
-					$gd_formats[] = "png";
87
-					ImageDestroy($srcImage);
88
-				}
89
-			}
90
-			if (function_exists('ImageCreateFromWEBP')) {
91
-				$srcImage = @ImageCreateFromWEBP(_ROOT_IMG_PACK . "test.webp");
92
-				if ($srcImage) {
93
-					$gd_formats[] = "webp";
94
-					ImageDestroy($srcImage);
95
-				}
96
-			}
97
-		}
98
-
99
-		if (! empty($gd_formats)) {
100
-			$gd_formats = join(",", $gd_formats);
101
-		}
102
-		ecrire_meta("gd_formats_read", $gd_formats . $gd_formats_read_gif);
103
-		ecrire_meta("gd_formats", $gd_formats);
104
-	} // verifier les formats netpbm
105
-	else {
106
-		if ($arg == "netpbm") {
107
-			if (!defined('_PNMSCALE_COMMAND')) {
108
-				define('_PNMSCALE_COMMAND', 'pnmscale');
109
-			} // Securite : mes_options.php peut preciser le chemin absolu
110
-			if (_PNMSCALE_COMMAND == '') {
111
-				return;
112
-			}
113
-			$netpbm_formats = array();
114
-
115
-			$jpegtopnm_command = str_replace("pnmscale",
116
-				"jpegtopnm", _PNMSCALE_COMMAND);
117
-			$pnmtojpeg_command = str_replace("pnmscale",
118
-				"pnmtojpeg", _PNMSCALE_COMMAND);
119
-
120
-			$vignette = _ROOT_IMG_PACK . "test.jpg";
121
-			$dest = _DIR_VAR . "test-jpg.jpg";
122
-			$commande = "$jpegtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
123
-			spip_log($commande);
124
-			exec($commande);
125
-			if ($taille = @getimagesize($dest)) {
126
-				if ($taille[1] == 10) {
127
-					$netpbm_formats[] = "jpg";
128
-				}
129
-			}
130
-			$giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
131
-			$pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
132
-			$vignette = _ROOT_IMG_PACK . "test.gif";
133
-			$dest = _DIR_VAR . "test-gif.jpg";
134
-			$commande = "$giftopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
135
-			spip_log($commande);
136
-			exec($commande);
137
-			if ($taille = @getimagesize($dest)) {
138
-				if ($taille[1] == 10) {
139
-					$netpbm_formats[] = "gif";
140
-				}
141
-			}
142
-
143
-			$pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
144
-			$vignette = _ROOT_IMG_PACK . "test.png";
145
-			$dest = _DIR_VAR . "test-gif.jpg";
146
-			$commande = "$pngtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
147
-			spip_log($commande);
148
-			exec($commande);
149
-			if ($taille = @getimagesize($dest)) {
150
-				if ($taille[1] == 10) {
151
-					$netpbm_formats[] = "png";
152
-				}
153
-			}
154
-
155
-
156
-			if ($netpbm_formats) {
157
-				$netpbm_formats = join(",", $netpbm_formats);
158
-			} else {
159
-				$netpbm_formats = '';
160
-			}
161
-			ecrire_meta("netpbm_formats", $netpbm_formats);
162
-		}
163
-	}
164
-
165
-	// et maintenant envoyer la vignette de tests
166
-	if (in_array($arg, array("gd1", "gd2", "imagick", "convert", "netpbm"))) {
167
-		include_spip('inc/filtres');
168
-		include_spip('inc/filtres_images_mini');
169
-		$taille_preview = 150;
170
-		$image = _image_valeurs_trans(_DIR_IMG_PACK . 'test_image.jpg', "reduire-$taille_preview-$taille_preview", 'jpg');
171
-
172
-		$image['fichier_dest'] = _DIR_VAR . "test_$arg";
173
-
174
-		if ($preview = _image_creer_vignette($image, $taille_preview, $taille_preview, $arg, true)
175
-			and ($preview['width'] * $preview['height'] > 0)
176
-		) {
177
-			redirige_par_entete($preview['fichier']);
178
-		}
179
-	}
180
-
181
-	# image echec
182
-	redirige_par_entete(chemin_image('puce-rouge-anim.gif'));
33
+    $arg = _request('arg');
34
+
35
+    $gd_formats = array();
36
+    $gd_formats_read_gif = "";
37
+    // verifier les formats acceptes par GD
38
+    if ($arg == "gd1") {
39
+        // Si GD est installe et php >= 4.0.2
40
+        if (function_exists('imagetypes')) {
41
+            if (imagetypes() & IMG_GIF) {
42
+                $gd_formats[] = "gif";
43
+            } else {
44
+                # Attention GD sait lire le gif mais pas forcement l'ecrire
45
+                if (function_exists('ImageCreateFromGIF')) {
46
+                    $srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
47
+                    if ($srcImage) {
48
+                        $gd_formats_read_gif = ",gif";
49
+                        ImageDestroy($srcImage);
50
+                    }
51
+                }
52
+            }
53
+
54
+            if (imagetypes() & IMG_JPG) {
55
+                $gd_formats[] = "jpg";
56
+            }
57
+            if (imagetypes() & IMG_PNG) {
58
+                $gd_formats[] = "png";
59
+            }
60
+            if (imagetypes() & IMG_WEBP) {
61
+                $gd_formats[] = "webp";
62
+            }
63
+        } else {
64
+            # ancienne methode de detection des formats, qui en plus
65
+            # est bugguee car elle teste les formats en lecture
66
+            # alors que la valeur deduite sert a identifier
67
+            # les formats disponibles en ecriture... (cf. inc_logos)
68
+
69
+            if (function_exists('ImageCreateFromJPEG')) {
70
+                $srcImage = @ImageCreateFromJPEG(_ROOT_IMG_PACK . "test.jpg");
71
+                if ($srcImage) {
72
+                    $gd_formats[] = "jpg";
73
+                    ImageDestroy($srcImage);
74
+                }
75
+            }
76
+            if (function_exists('ImageCreateFromGIF')) {
77
+                $srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
78
+                if ($srcImage) {
79
+                    $gd_formats[] = "gif";
80
+                    ImageDestroy($srcImage);
81
+                }
82
+            }
83
+            if (function_exists('ImageCreateFromPNG')) {
84
+                $srcImage = @ImageCreateFromPNG(_ROOT_IMG_PACK . "test.png");
85
+                if ($srcImage) {
86
+                    $gd_formats[] = "png";
87
+                    ImageDestroy($srcImage);
88
+                }
89
+            }
90
+            if (function_exists('ImageCreateFromWEBP')) {
91
+                $srcImage = @ImageCreateFromWEBP(_ROOT_IMG_PACK . "test.webp");
92
+                if ($srcImage) {
93
+                    $gd_formats[] = "webp";
94
+                    ImageDestroy($srcImage);
95
+                }
96
+            }
97
+        }
98
+
99
+        if (! empty($gd_formats)) {
100
+            $gd_formats = join(",", $gd_formats);
101
+        }
102
+        ecrire_meta("gd_formats_read", $gd_formats . $gd_formats_read_gif);
103
+        ecrire_meta("gd_formats", $gd_formats);
104
+    } // verifier les formats netpbm
105
+    else {
106
+        if ($arg == "netpbm") {
107
+            if (!defined('_PNMSCALE_COMMAND')) {
108
+                define('_PNMSCALE_COMMAND', 'pnmscale');
109
+            } // Securite : mes_options.php peut preciser le chemin absolu
110
+            if (_PNMSCALE_COMMAND == '') {
111
+                return;
112
+            }
113
+            $netpbm_formats = array();
114
+
115
+            $jpegtopnm_command = str_replace("pnmscale",
116
+                "jpegtopnm", _PNMSCALE_COMMAND);
117
+            $pnmtojpeg_command = str_replace("pnmscale",
118
+                "pnmtojpeg", _PNMSCALE_COMMAND);
119
+
120
+            $vignette = _ROOT_IMG_PACK . "test.jpg";
121
+            $dest = _DIR_VAR . "test-jpg.jpg";
122
+            $commande = "$jpegtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
123
+            spip_log($commande);
124
+            exec($commande);
125
+            if ($taille = @getimagesize($dest)) {
126
+                if ($taille[1] == 10) {
127
+                    $netpbm_formats[] = "jpg";
128
+                }
129
+            }
130
+            $giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
131
+            $pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
132
+            $vignette = _ROOT_IMG_PACK . "test.gif";
133
+            $dest = _DIR_VAR . "test-gif.jpg";
134
+            $commande = "$giftopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
135
+            spip_log($commande);
136
+            exec($commande);
137
+            if ($taille = @getimagesize($dest)) {
138
+                if ($taille[1] == 10) {
139
+                    $netpbm_formats[] = "gif";
140
+                }
141
+            }
142
+
143
+            $pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
144
+            $vignette = _ROOT_IMG_PACK . "test.png";
145
+            $dest = _DIR_VAR . "test-gif.jpg";
146
+            $commande = "$pngtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
147
+            spip_log($commande);
148
+            exec($commande);
149
+            if ($taille = @getimagesize($dest)) {
150
+                if ($taille[1] == 10) {
151
+                    $netpbm_formats[] = "png";
152
+                }
153
+            }
154
+
155
+
156
+            if ($netpbm_formats) {
157
+                $netpbm_formats = join(",", $netpbm_formats);
158
+            } else {
159
+                $netpbm_formats = '';
160
+            }
161
+            ecrire_meta("netpbm_formats", $netpbm_formats);
162
+        }
163
+    }
164
+
165
+    // et maintenant envoyer la vignette de tests
166
+    if (in_array($arg, array("gd1", "gd2", "imagick", "convert", "netpbm"))) {
167
+        include_spip('inc/filtres');
168
+        include_spip('inc/filtres_images_mini');
169
+        $taille_preview = 150;
170
+        $image = _image_valeurs_trans(_DIR_IMG_PACK . 'test_image.jpg', "reduire-$taille_preview-$taille_preview", 'jpg');
171
+
172
+        $image['fichier_dest'] = _DIR_VAR . "test_$arg";
173
+
174
+        if ($preview = _image_creer_vignette($image, $taille_preview, $taille_preview, $arg, true)
175
+            and ($preview['width'] * $preview['height'] > 0)
176
+        ) {
177
+            redirige_par_entete($preview['fichier']);
178
+        }
179
+    }
180
+
181
+    # image echec
182
+    redirige_par_entete(chemin_image('puce-rouge-anim.gif'));
183 183
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 			} else {
44 44
 				# Attention GD sait lire le gif mais pas forcement l'ecrire
45 45
 				if (function_exists('ImageCreateFromGIF')) {
46
-					$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
46
+					$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK."test.gif");
47 47
 					if ($srcImage) {
48 48
 						$gd_formats_read_gif = ",gif";
49 49
 						ImageDestroy($srcImage);
@@ -67,28 +67,28 @@  discard block
 block discarded – undo
67 67
 			# les formats disponibles en ecriture... (cf. inc_logos)
68 68
 
69 69
 			if (function_exists('ImageCreateFromJPEG')) {
70
-				$srcImage = @ImageCreateFromJPEG(_ROOT_IMG_PACK . "test.jpg");
70
+				$srcImage = @ImageCreateFromJPEG(_ROOT_IMG_PACK."test.jpg");
71 71
 				if ($srcImage) {
72 72
 					$gd_formats[] = "jpg";
73 73
 					ImageDestroy($srcImage);
74 74
 				}
75 75
 			}
76 76
 			if (function_exists('ImageCreateFromGIF')) {
77
-				$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK . "test.gif");
77
+				$srcImage = @ImageCreateFromGIF(_ROOT_IMG_PACK."test.gif");
78 78
 				if ($srcImage) {
79 79
 					$gd_formats[] = "gif";
80 80
 					ImageDestroy($srcImage);
81 81
 				}
82 82
 			}
83 83
 			if (function_exists('ImageCreateFromPNG')) {
84
-				$srcImage = @ImageCreateFromPNG(_ROOT_IMG_PACK . "test.png");
84
+				$srcImage = @ImageCreateFromPNG(_ROOT_IMG_PACK."test.png");
85 85
 				if ($srcImage) {
86 86
 					$gd_formats[] = "png";
87 87
 					ImageDestroy($srcImage);
88 88
 				}
89 89
 			}
90 90
 			if (function_exists('ImageCreateFromWEBP')) {
91
-				$srcImage = @ImageCreateFromWEBP(_ROOT_IMG_PACK . "test.webp");
91
+				$srcImage = @ImageCreateFromWEBP(_ROOT_IMG_PACK."test.webp");
92 92
 				if ($srcImage) {
93 93
 					$gd_formats[] = "webp";
94 94
 					ImageDestroy($srcImage);
@@ -96,10 +96,10 @@  discard block
 block discarded – undo
96 96
 			}
97 97
 		}
98 98
 
99
-		if (! empty($gd_formats)) {
99
+		if (!empty($gd_formats)) {
100 100
 			$gd_formats = join(",", $gd_formats);
101 101
 		}
102
-		ecrire_meta("gd_formats_read", $gd_formats . $gd_formats_read_gif);
102
+		ecrire_meta("gd_formats_read", $gd_formats.$gd_formats_read_gif);
103 103
 		ecrire_meta("gd_formats", $gd_formats);
104 104
 	} // verifier les formats netpbm
105 105
 	else {
@@ -117,9 +117,9 @@  discard block
 block discarded – undo
117 117
 			$pnmtojpeg_command = str_replace("pnmscale",
118 118
 				"pnmtojpeg", _PNMSCALE_COMMAND);
119 119
 
120
-			$vignette = _ROOT_IMG_PACK . "test.jpg";
121
-			$dest = _DIR_VAR . "test-jpg.jpg";
122
-			$commande = "$jpegtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
120
+			$vignette = _ROOT_IMG_PACK."test.jpg";
121
+			$dest = _DIR_VAR."test-jpg.jpg";
122
+			$commande = "$jpegtopnm_command $vignette | "._PNMSCALE_COMMAND." -width 10 | $pnmtojpeg_command > $dest";
123 123
 			spip_log($commande);
124 124
 			exec($commande);
125 125
 			if ($taille = @getimagesize($dest)) {
@@ -129,9 +129,9 @@  discard block
 block discarded – undo
129 129
 			}
130 130
 			$giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND);
131 131
 			$pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND);
132
-			$vignette = _ROOT_IMG_PACK . "test.gif";
133
-			$dest = _DIR_VAR . "test-gif.jpg";
134
-			$commande = "$giftopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
132
+			$vignette = _ROOT_IMG_PACK."test.gif";
133
+			$dest = _DIR_VAR."test-gif.jpg";
134
+			$commande = "$giftopnm_command $vignette | "._PNMSCALE_COMMAND." -width 10 | $pnmtojpeg_command > $dest";
135 135
 			spip_log($commande);
136 136
 			exec($commande);
137 137
 			if ($taille = @getimagesize($dest)) {
@@ -141,9 +141,9 @@  discard block
 block discarded – undo
141 141
 			}
142 142
 
143 143
 			$pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND);
144
-			$vignette = _ROOT_IMG_PACK . "test.png";
145
-			$dest = _DIR_VAR . "test-gif.jpg";
146
-			$commande = "$pngtopnm_command $vignette | " . _PNMSCALE_COMMAND . " -width 10 | $pnmtojpeg_command > $dest";
144
+			$vignette = _ROOT_IMG_PACK."test.png";
145
+			$dest = _DIR_VAR."test-gif.jpg";
146
+			$commande = "$pngtopnm_command $vignette | "._PNMSCALE_COMMAND." -width 10 | $pnmtojpeg_command > $dest";
147 147
 			spip_log($commande);
148 148
 			exec($commande);
149 149
 			if ($taille = @getimagesize($dest)) {
@@ -167,9 +167,9 @@  discard block
 block discarded – undo
167 167
 		include_spip('inc/filtres');
168 168
 		include_spip('inc/filtres_images_mini');
169 169
 		$taille_preview = 150;
170
-		$image = _image_valeurs_trans(_DIR_IMG_PACK . 'test_image.jpg', "reduire-$taille_preview-$taille_preview", 'jpg');
170
+		$image = _image_valeurs_trans(_DIR_IMG_PACK.'test_image.jpg', "reduire-$taille_preview-$taille_preview", 'jpg');
171 171
 
172
-		$image['fichier_dest'] = _DIR_VAR . "test_$arg";
172
+		$image['fichier_dest'] = _DIR_VAR."test_$arg";
173 173
 
174 174
 		if ($preview = _image_creer_vignette($image, $taille_preview, $taille_preview, $arg, true)
175 175
 			and ($preview['width'] * $preview['height'] > 0)
Please login to merge, or discard this patch.
ecrire/inc/distant.php 2 patches
Indentation   +1075 added lines, -1075 removed lines patch added patch discarded remove patch
@@ -16,32 +16,32 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Distant
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
23
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
23
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24 24
 }
25 25
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
26
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
26
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32
-	define('_INC_DISTANT_MAX_SIZE', 2097152);
32
+    define('_INC_DISTANT_MAX_SIZE', 2097152);
33 33
 }
34 34
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
35
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
35
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38 38
 define('_REGEXP_COPIE_LOCALE', ',' 	.
39
-	preg_replace(
40
-		'@^https?:@',
41
-		'https?:',
42
-		(isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
-	)
44
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
39
+    preg_replace(
40
+        '@^https?:@',
41
+        'https?:',
42
+        (isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
+    )
44
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
45 45
 
46 46
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
47 47
 
@@ -68,77 +68,77 @@  discard block
 block discarded – undo
68 68
  */
69 69
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null) {
70 70
 
71
-	// si c'est la protection de soi-meme, retourner le path
72
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
-
75
-		return @file_exists($source) ? $source : false;
76
-	}
77
-
78
-	if (is_null($local)) {
79
-		$local = fichier_copie_locale($source);
80
-	} else {
81
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
-			$local = substr($local, strlen(_DIR_RACINE));
83
-		}
84
-	}
85
-
86
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
-	// par exemple un fichier qui ne figure pas dans nos documents ;
88
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
-	if (!$local) {
90
-		return false;
91
-	}
92
-
93
-	$localrac = _DIR_RACINE . $local;
94
-	$t = ($mode == 'force') ? false : @file_exists($localrac);
95
-
96
-	// test d'existence du fichier
97
-	if ($mode == 'test') {
98
-		return $t ? $local : '';
99
-	}
100
-
101
-	// sinon voir si on doit/peut le telecharger
102
-	if ($local == $source or !tester_url_absolue($source)) {
103
-		return $local;
104
-	}
105
-
106
-	if ($mode == 'modif' or !$t) {
107
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
-		// et des eventuelles recuperations concurantes
109
-		include_spip('inc/acces');
110
-		if (!$taille_max) {
111
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
112
-		}
113
-		$res = recuperer_url(
114
-			$source,
115
-			array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
-		);
117
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
-		}
120
-		if (!$res['length']) {
121
-			// si $t c'est sans doute juste un not-modified-since
122
-			return $t ? $local : false;
123
-		}
124
-		spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
-
126
-		// pour une eventuelle indexation
127
-		pipeline(
128
-			'post_edition',
129
-			array(
130
-				'args' => array(
131
-					'operation' => 'copie_locale',
132
-					'source' => $source,
133
-					'fichier' => $local,
134
-					'http_res' => $res['length'],
135
-				),
136
-				'data' => null
137
-			)
138
-		);
139
-	}
140
-
141
-	return $local;
71
+    // si c'est la protection de soi-meme, retourner le path
72
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
+
75
+        return @file_exists($source) ? $source : false;
76
+    }
77
+
78
+    if (is_null($local)) {
79
+        $local = fichier_copie_locale($source);
80
+    } else {
81
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
+            $local = substr($local, strlen(_DIR_RACINE));
83
+        }
84
+    }
85
+
86
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
+    // par exemple un fichier qui ne figure pas dans nos documents ;
88
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
+    if (!$local) {
90
+        return false;
91
+    }
92
+
93
+    $localrac = _DIR_RACINE . $local;
94
+    $t = ($mode == 'force') ? false : @file_exists($localrac);
95
+
96
+    // test d'existence du fichier
97
+    if ($mode == 'test') {
98
+        return $t ? $local : '';
99
+    }
100
+
101
+    // sinon voir si on doit/peut le telecharger
102
+    if ($local == $source or !tester_url_absolue($source)) {
103
+        return $local;
104
+    }
105
+
106
+    if ($mode == 'modif' or !$t) {
107
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
+        // et des eventuelles recuperations concurantes
109
+        include_spip('inc/acces');
110
+        if (!$taille_max) {
111
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
112
+        }
113
+        $res = recuperer_url(
114
+            $source,
115
+            array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
+        );
117
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
+            spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
+        }
120
+        if (!$res['length']) {
121
+            // si $t c'est sans doute juste un not-modified-since
122
+            return $t ? $local : false;
123
+        }
124
+        spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
+
126
+        // pour une eventuelle indexation
127
+        pipeline(
128
+            'post_edition',
129
+            array(
130
+                'args' => array(
131
+                    'operation' => 'copie_locale',
132
+                    'source' => $source,
133
+                    'fichier' => $local,
134
+                    'http_res' => $res['length'],
135
+                ),
136
+                'data' => null
137
+            )
138
+        );
139
+    }
140
+
141
+    return $local;
142 142
 }
143 143
 
144 144
 /**
@@ -153,88 +153,88 @@  discard block
 block discarded – undo
153 153
  *   url ou false en cas d'echec
154 154
  */
155 155
 function valider_url_distante($url, $known_hosts = array()) {
156
-	if (!function_exists('protocole_verifier')){
157
-		include_spip('inc/filtres_mini');
158
-	}
156
+    if (!function_exists('protocole_verifier')){
157
+        include_spip('inc/filtres_mini');
158
+    }
159 159
 
160
-	if (!protocole_verifier($url, array('http', 'https'))) {
161
-		return false;
162
-	}
160
+    if (!protocole_verifier($url, array('http', 'https'))) {
161
+        return false;
162
+    }
163 163
 	
164
-	$parsed_url = parse_url($url);
165
-	if (!$parsed_url or empty($parsed_url['host']) ) {
166
-		return false;
167
-	}
168
-
169
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
-		return false;
171
-	}
172
-
173
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
-		return false;
175
-	}
176
-
177
-	if (!is_array($known_hosts)) {
178
-		$known_hosts = array($known_hosts);
179
-	}
180
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
-	$known_hosts[] = url_de_base();
182
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
-
184
-	$is_known_host = false;
185
-	foreach ($known_hosts as $known_host) {
186
-		$parse_known = parse_url($known_host);
187
-		if ($parse_known
188
-		  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
-			$is_known_host = true;
190
-			break;
191
-		}
192
-	}
193
-
194
-	if (!$is_known_host) {
195
-		$host = trim($parsed_url['host'], '.');
196
-		if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
-			$ip = $host;
198
-		} else {
199
-			$ip = gethostbyname($host);
200
-			if ($ip === $host) {
201
-				// Error condition for gethostbyname()
202
-				$ip = false;
203
-			}
204
-		}
205
-		if ($ip) {
206
-			$parts = array_map('intval', explode( '.', $ip ));
207
-			if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
-			  or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
-			  or ( 192 === $parts[0] && 168 === $parts[1] )
210
-			) {
211
-				return false;
212
-			}
213
-		}
214
-	}
215
-
216
-	if (empty($parsed_url['port'])) {
217
-		return $url;
218
-	}
219
-
220
-	$port = $parsed_url['port'];
221
-	if ($port === 80  or $port === 443  or $port === 8080) {
222
-		return $url;
223
-	}
224
-
225
-	if ($is_known_host) {
226
-		foreach ($known_hosts as $known_host) {
227
-			$parse_known = parse_url($known_host);
228
-			if ($parse_known
229
-				and !empty($parse_known['port'])
230
-			  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
-			  and $parse_known['port'] == $port) {
232
-				return $url;
233
-			}
234
-		}
235
-	}
236
-
237
-	return false;
164
+    $parsed_url = parse_url($url);
165
+    if (!$parsed_url or empty($parsed_url['host']) ) {
166
+        return false;
167
+    }
168
+
169
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
+        return false;
171
+    }
172
+
173
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
+        return false;
175
+    }
176
+
177
+    if (!is_array($known_hosts)) {
178
+        $known_hosts = array($known_hosts);
179
+    }
180
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
+    $known_hosts[] = url_de_base();
182
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
+
184
+    $is_known_host = false;
185
+    foreach ($known_hosts as $known_host) {
186
+        $parse_known = parse_url($known_host);
187
+        if ($parse_known
188
+          and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
+            $is_known_host = true;
190
+            break;
191
+        }
192
+    }
193
+
194
+    if (!$is_known_host) {
195
+        $host = trim($parsed_url['host'], '.');
196
+        if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
+            $ip = $host;
198
+        } else {
199
+            $ip = gethostbyname($host);
200
+            if ($ip === $host) {
201
+                // Error condition for gethostbyname()
202
+                $ip = false;
203
+            }
204
+        }
205
+        if ($ip) {
206
+            $parts = array_map('intval', explode( '.', $ip ));
207
+            if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
+              or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
+              or ( 192 === $parts[0] && 168 === $parts[1] )
210
+            ) {
211
+                return false;
212
+            }
213
+        }
214
+    }
215
+
216
+    if (empty($parsed_url['port'])) {
217
+        return $url;
218
+    }
219
+
220
+    $port = $parsed_url['port'];
221
+    if ($port === 80  or $port === 443  or $port === 8080) {
222
+        return $url;
223
+    }
224
+
225
+    if ($is_known_host) {
226
+        foreach ($known_hosts as $known_host) {
227
+            $parse_known = parse_url($known_host);
228
+            if ($parse_known
229
+                and !empty($parse_known['port'])
230
+              and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
+              and $parse_known['port'] == $port) {
232
+                return $url;
233
+            }
234
+        }
235
+    }
236
+
237
+    return false;
238 238
 }
239 239
 
240 240
 /**
@@ -253,86 +253,86 @@  discard block
 block discarded – undo
253 253
  */
254 254
 function prepare_donnees_post($donnees, $boundary = '') {
255 255
 
256
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
257
-	// pour un appel soap par exemple
258
-	// l'entete est separe des donnees par un double retour a la ligne
259
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
260
-	if (is_string($donnees) && strlen($donnees)) {
261
-		$entete = '';
262
-		// on repasse tous les \r\n et \r en simples \n
263
-		$donnees = str_replace("\r\n", "\n", $donnees);
264
-		$donnees = str_replace("\r", "\n", $donnees);
265
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
266
-		$p = strpos($donnees, "\n\n");
267
-		if ($p !== false) {
268
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
269
-			$donnees = substr($donnees, $p + 2);
270
-		}
271
-		$chaine = str_replace("\n", "\r\n", $donnees);
272
-	} else {
273
-		/* boundary automatique */
274
-		// Si on a plus de 500 octects de donnees, on "boundarise"
275
-		if ($boundary === '') {
276
-			$taille = 0;
277
-			foreach ($donnees as $cle => $valeur) {
278
-				if (is_array($valeur)) {
279
-					foreach ($valeur as $val2) {
280
-						$taille += strlen($val2);
281
-					}
282
-				} else {
283
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
284
-					$taille += strlen($valeur);
285
-				}
286
-			}
287
-			if ($taille > 500) {
288
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
289
-			}
290
-		}
291
-
292
-		if (is_string($boundary) and strlen($boundary)) {
293
-			// fabrique une chaine HTTP pour un POST avec boundary
294
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
295
-			$chaine = '';
296
-			if (is_array($donnees)) {
297
-				foreach ($donnees as $cle => $valeur) {
298
-					if (is_array($valeur)) {
299
-						foreach ($valeur as $val2) {
300
-							$chaine .= "\r\n--$boundary\r\n";
301
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
302
-							$chaine .= "\r\n";
303
-							$chaine .= $val2;
304
-						}
305
-					} else {
306
-						$chaine .= "\r\n--$boundary\r\n";
307
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
308
-						$chaine .= "\r\n";
309
-						$chaine .= $valeur;
310
-					}
311
-				}
312
-				$chaine .= "\r\n--$boundary\r\n";
313
-			}
314
-		} else {
315
-			// fabrique une chaine HTTP simple pour un POST
316
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
317
-			$chaine = array();
318
-			if (is_array($donnees)) {
319
-				foreach ($donnees as $cle => $valeur) {
320
-					if (is_array($valeur)) {
321
-						foreach ($valeur as $val2) {
322
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
323
-						}
324
-					} else {
325
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
326
-					}
327
-				}
328
-				$chaine = implode('&', $chaine);
329
-			} else {
330
-				$chaine = $donnees;
331
-			}
332
-		}
333
-	}
334
-
335
-	return array($entete, $chaine);
256
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
257
+    // pour un appel soap par exemple
258
+    // l'entete est separe des donnees par un double retour a la ligne
259
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
260
+    if (is_string($donnees) && strlen($donnees)) {
261
+        $entete = '';
262
+        // on repasse tous les \r\n et \r en simples \n
263
+        $donnees = str_replace("\r\n", "\n", $donnees);
264
+        $donnees = str_replace("\r", "\n", $donnees);
265
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
266
+        $p = strpos($donnees, "\n\n");
267
+        if ($p !== false) {
268
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
269
+            $donnees = substr($donnees, $p + 2);
270
+        }
271
+        $chaine = str_replace("\n", "\r\n", $donnees);
272
+    } else {
273
+        /* boundary automatique */
274
+        // Si on a plus de 500 octects de donnees, on "boundarise"
275
+        if ($boundary === '') {
276
+            $taille = 0;
277
+            foreach ($donnees as $cle => $valeur) {
278
+                if (is_array($valeur)) {
279
+                    foreach ($valeur as $val2) {
280
+                        $taille += strlen($val2);
281
+                    }
282
+                } else {
283
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
284
+                    $taille += strlen($valeur);
285
+                }
286
+            }
287
+            if ($taille > 500) {
288
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
289
+            }
290
+        }
291
+
292
+        if (is_string($boundary) and strlen($boundary)) {
293
+            // fabrique une chaine HTTP pour un POST avec boundary
294
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
295
+            $chaine = '';
296
+            if (is_array($donnees)) {
297
+                foreach ($donnees as $cle => $valeur) {
298
+                    if (is_array($valeur)) {
299
+                        foreach ($valeur as $val2) {
300
+                            $chaine .= "\r\n--$boundary\r\n";
301
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
302
+                            $chaine .= "\r\n";
303
+                            $chaine .= $val2;
304
+                        }
305
+                    } else {
306
+                        $chaine .= "\r\n--$boundary\r\n";
307
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
308
+                        $chaine .= "\r\n";
309
+                        $chaine .= $valeur;
310
+                    }
311
+                }
312
+                $chaine .= "\r\n--$boundary\r\n";
313
+            }
314
+        } else {
315
+            // fabrique une chaine HTTP simple pour un POST
316
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
317
+            $chaine = array();
318
+            if (is_array($donnees)) {
319
+                foreach ($donnees as $cle => $valeur) {
320
+                    if (is_array($valeur)) {
321
+                        foreach ($valeur as $val2) {
322
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
323
+                        }
324
+                    } else {
325
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
326
+                    }
327
+                }
328
+                $chaine = implode('&', $chaine);
329
+            } else {
330
+                $chaine = $donnees;
331
+            }
332
+        }
333
+    }
334
+
335
+    return array($entete, $chaine);
336 336
 }
337 337
 
338 338
 /**
@@ -346,18 +346,18 @@  discard block
 block discarded – undo
346 346
  */
347 347
 function url_to_ascii($url_idn) {
348 348
 
349
-	if ($parts = parse_url($url_idn)) {
350
-		$host = $parts['host'];
351
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
352
-			include_spip('inc/idna_convert.class');
353
-			$IDN = new idna_convert();
354
-			$host_ascii = $IDN->encode($host);
355
-			$url_idn = explode($host, $url_idn, 2);
356
-			$url_idn = implode($host_ascii, $url_idn);
357
-		}
358
-	}
359
-
360
-	return $url_idn;
349
+    if ($parts = parse_url($url_idn)) {
350
+        $host = $parts['host'];
351
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
352
+            include_spip('inc/idna_convert.class');
353
+            $IDN = new idna_convert();
354
+            $host_ascii = $IDN->encode($host);
355
+            $url_idn = explode($host, $url_idn, 2);
356
+            $url_idn = implode($host_ascii, $url_idn);
357
+        }
358
+    }
359
+
360
+    return $url_idn;
361 361
 }
362 362
 
363 363
 /**
@@ -396,176 +396,176 @@  discard block
 block discarded – undo
396 396
  *     string file : nom du fichier si enregistre dans un fichier
397 397
  */
398 398
 function recuperer_url($url, $options = array()) {
399
-	$default = array(
400
-		'transcoder' => false,
401
-		'methode' => 'GET',
402
-		'taille_max' => null,
403
-		'datas' => '',
404
-		'boundary' => '',
405
-		'refuser_gz' => false,
406
-		'if_modified_since' => '',
407
-		'uri_referer' => '',
408
-		'file' => '',
409
-		'follow_location' => 10,
410
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
411
-	);
412
-	$options = array_merge($default, $options);
413
-	// copier directement dans un fichier ?
414
-	$copy = $options['file'];
415
-
416
-	if ($options['methode'] == 'HEAD') {
417
-		$options['taille_max'] = 0;
418
-	}
419
-	if (is_null($options['taille_max'])) {
420
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
421
-	}
422
-
423
-	if (!empty($options['datas'])) {
424
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
425
-		if (stripos($head, 'Content-Length:') === false) {
426
-			$head .= 'Content-Length: ' . strlen($postdata);
427
-		}
428
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
429
-		if (strlen($postdata)) {
430
-			$options['methode'] = 'POST';
431
-		}
432
-	}
433
-
434
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
435
-	$url = preg_replace(',^feed://,i', 'http://', $url);
436
-	if (!tester_url_absolue($url)) {
437
-		$url = 'http://' . $url;
438
-	} elseif (strncmp($url, '//', 2) == 0) {
439
-		$url = 'http:' . $url;
440
-	}
441
-
442
-	$url = url_to_ascii($url);
443
-
444
-	$result = array(
445
-		'status' => 0,
446
-		'headers' => '',
447
-		'page' => '',
448
-		'length' => 0,
449
-		'last_modified' => '',
450
-		'location' => '',
451
-		'url' => $url
452
-	);
453
-
454
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
455
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
456
-
457
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
458
-	list($handle, $fopen) = init_http(
459
-		$options['methode'],
460
-		$url,
461
-		$refuser_gz,
462
-		$options['uri_referer'],
463
-		$options['datas'],
464
-		$options['version_http'],
465
-		$options['if_modified_since']
466
-	);
467
-	if (!$handle) {
468
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
469
-
470
-		return false;
471
-	}
472
-
473
-	// Sauf en fopen, envoyer le flux d'entree
474
-	// et recuperer les en-tetes de reponses
475
-	if (!$fopen) {
476
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
477
-		if (!$res) {
478
-			fclose($handle);
479
-			$t = @parse_url($url);
480
-			$host = $t['host'];
481
-			// Chinoisierie inexplicable pour contrer
482
-			// les actions liberticides de l'empire du milieu
483
-			if (!need_proxy($host)
484
-				and $res = @file_get_contents($url)
485
-			) {
486
-				$result['length'] = strlen($res);
487
-				if ($copy) {
488
-					ecrire_fichier($copy, $res);
489
-					$result['file'] = $copy;
490
-				} else {
491
-					$result['page'] = $res;
492
-				}
493
-				$res = array(
494
-					'status' => 200,
495
-				);
496
-			} else {
497
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
498
-				return false;
499
-			}
500
-		} elseif ($res['location'] and $options['follow_location']) {
501
-			$options['follow_location']--;
502
-			fclose($handle);
503
-			include_spip('inc/filtres');
504
-			$url = suivre_lien($url, $res['location']);
505
-			spip_log("recuperer_url recommence sur $url", 'distant');
506
-
507
-			return recuperer_url($url, $options);
508
-		} elseif ($res['status'] !== 200) {
509
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
510
-		}
511
-		$result['status'] = $res['status'];
512
-		if (isset($res['headers'])) {
513
-			$result['headers'] = $res['headers'];
514
-		}
515
-		if (isset($res['last_modified'])) {
516
-			$result['last_modified'] = $res['last_modified'];
517
-		}
518
-		if (isset($res['location'])) {
519
-			$result['location'] = $res['location'];
520
-		}
521
-	}
522
-
523
-	// on ne veut que les entetes
524
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
525
-		return $result;
526
-	}
527
-
528
-
529
-	// s'il faut deballer, le faire via un fichier temporaire
530
-	// sinon la memoire explose pour les gros flux
531
-
532
-	$gz = false;
533
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
534
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
535
-	}
536
-
537
-	// si on a pas deja recuperer le contenu par une methode detournee
538
-	if (!$result['length']) {
539
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
540
-		fclose($handle);
541
-		if ($copy) {
542
-			$result['length'] = $res;
543
-			$result['file'] = $copy;
544
-		} elseif ($res) {
545
-			$result['page'] = &$res;
546
-			$result['length'] = strlen($result['page']);
547
-		}
548
-		if (!$result['status']) {
549
-			$result['status'] = 200; // on a reussi, donc !
550
-		}
551
-	}
552
-	if (!$result['page']) {
553
-		return $result;
554
-	}
555
-
556
-	// Decompresser au besoin
557
-	if ($gz) {
558
-		$result['page'] = implode('', gzfile($gz));
559
-		supprimer_fichier($gz);
560
-	}
561
-
562
-	// Faut-il l'importer dans notre charset local ?
563
-	if ($options['transcoder']) {
564
-		include_spip('inc/charsets');
565
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
566
-	}
567
-
568
-	return $result;
399
+    $default = array(
400
+        'transcoder' => false,
401
+        'methode' => 'GET',
402
+        'taille_max' => null,
403
+        'datas' => '',
404
+        'boundary' => '',
405
+        'refuser_gz' => false,
406
+        'if_modified_since' => '',
407
+        'uri_referer' => '',
408
+        'file' => '',
409
+        'follow_location' => 10,
410
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
411
+    );
412
+    $options = array_merge($default, $options);
413
+    // copier directement dans un fichier ?
414
+    $copy = $options['file'];
415
+
416
+    if ($options['methode'] == 'HEAD') {
417
+        $options['taille_max'] = 0;
418
+    }
419
+    if (is_null($options['taille_max'])) {
420
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
421
+    }
422
+
423
+    if (!empty($options['datas'])) {
424
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
425
+        if (stripos($head, 'Content-Length:') === false) {
426
+            $head .= 'Content-Length: ' . strlen($postdata);
427
+        }
428
+        $options['datas'] = $head . "\r\n\r\n" . $postdata;
429
+        if (strlen($postdata)) {
430
+            $options['methode'] = 'POST';
431
+        }
432
+    }
433
+
434
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
435
+    $url = preg_replace(',^feed://,i', 'http://', $url);
436
+    if (!tester_url_absolue($url)) {
437
+        $url = 'http://' . $url;
438
+    } elseif (strncmp($url, '//', 2) == 0) {
439
+        $url = 'http:' . $url;
440
+    }
441
+
442
+    $url = url_to_ascii($url);
443
+
444
+    $result = array(
445
+        'status' => 0,
446
+        'headers' => '',
447
+        'page' => '',
448
+        'length' => 0,
449
+        'last_modified' => '',
450
+        'location' => '',
451
+        'url' => $url
452
+    );
453
+
454
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
455
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
456
+
457
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
458
+    list($handle, $fopen) = init_http(
459
+        $options['methode'],
460
+        $url,
461
+        $refuser_gz,
462
+        $options['uri_referer'],
463
+        $options['datas'],
464
+        $options['version_http'],
465
+        $options['if_modified_since']
466
+    );
467
+    if (!$handle) {
468
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
469
+
470
+        return false;
471
+    }
472
+
473
+    // Sauf en fopen, envoyer le flux d'entree
474
+    // et recuperer les en-tetes de reponses
475
+    if (!$fopen) {
476
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
477
+        if (!$res) {
478
+            fclose($handle);
479
+            $t = @parse_url($url);
480
+            $host = $t['host'];
481
+            // Chinoisierie inexplicable pour contrer
482
+            // les actions liberticides de l'empire du milieu
483
+            if (!need_proxy($host)
484
+                and $res = @file_get_contents($url)
485
+            ) {
486
+                $result['length'] = strlen($res);
487
+                if ($copy) {
488
+                    ecrire_fichier($copy, $res);
489
+                    $result['file'] = $copy;
490
+                } else {
491
+                    $result['page'] = $res;
492
+                }
493
+                $res = array(
494
+                    'status' => 200,
495
+                );
496
+            } else {
497
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
498
+                return false;
499
+            }
500
+        } elseif ($res['location'] and $options['follow_location']) {
501
+            $options['follow_location']--;
502
+            fclose($handle);
503
+            include_spip('inc/filtres');
504
+            $url = suivre_lien($url, $res['location']);
505
+            spip_log("recuperer_url recommence sur $url", 'distant');
506
+
507
+            return recuperer_url($url, $options);
508
+        } elseif ($res['status'] !== 200) {
509
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
510
+        }
511
+        $result['status'] = $res['status'];
512
+        if (isset($res['headers'])) {
513
+            $result['headers'] = $res['headers'];
514
+        }
515
+        if (isset($res['last_modified'])) {
516
+            $result['last_modified'] = $res['last_modified'];
517
+        }
518
+        if (isset($res['location'])) {
519
+            $result['location'] = $res['location'];
520
+        }
521
+    }
522
+
523
+    // on ne veut que les entetes
524
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
525
+        return $result;
526
+    }
527
+
528
+
529
+    // s'il faut deballer, le faire via un fichier temporaire
530
+    // sinon la memoire explose pour les gros flux
531
+
532
+    $gz = false;
533
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
534
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
535
+    }
536
+
537
+    // si on a pas deja recuperer le contenu par une methode detournee
538
+    if (!$result['length']) {
539
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
540
+        fclose($handle);
541
+        if ($copy) {
542
+            $result['length'] = $res;
543
+            $result['file'] = $copy;
544
+        } elseif ($res) {
545
+            $result['page'] = &$res;
546
+            $result['length'] = strlen($result['page']);
547
+        }
548
+        if (!$result['status']) {
549
+            $result['status'] = 200; // on a reussi, donc !
550
+        }
551
+    }
552
+    if (!$result['page']) {
553
+        return $result;
554
+    }
555
+
556
+    // Decompresser au besoin
557
+    if ($gz) {
558
+        $result['page'] = implode('', gzfile($gz));
559
+        supprimer_fichier($gz);
560
+    }
561
+
562
+    // Faut-il l'importer dans notre charset local ?
563
+    if ($options['transcoder']) {
564
+        include_spip('inc/charsets');
565
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
566
+    }
567
+
568
+    return $result;
569 569
 }
570 570
 
571 571
 /**
@@ -581,72 +581,72 @@  discard block
 block discarded – undo
581 581
  * @return array|bool|mixed
582 582
  */
583 583
 function recuperer_url_cache($url, $options = array()) {
584
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
585
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
586
-	}
587
-	$default = array(
588
-		'transcoder' => false,
589
-		'methode' => 'GET',
590
-		'taille_max' => null,
591
-		'datas' => '',
592
-		'boundary' => '',
593
-		'refuser_gz' => false,
594
-		'if_modified_since' => '',
595
-		'uri_referer' => '',
596
-		'file' => '',
597
-		'follow_location' => 10,
598
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
599
-		'delai_cache' => _DELAI_RECUPERER_URL_CACHE,
600
-	);
601
-	$options = array_merge($default, $options);
602
-
603
-	// cas ou il n'est pas possible de cacher
604
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
605
-		return recuperer_url($url, $options);
606
-	}
607
-
608
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
609
-	static $errors = array();
610
-	if (isset($errors[$url])) {
611
-		return $errors[$url];
612
-	}
613
-
614
-	$sig = $options;
615
-	unset($sig['if_modified_since']);
616
-	unset($sig['delai_cache']);
617
-	$sig['url'] = $url;
618
-
619
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
620
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
621
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
622
-	$cache = "$sub$cache";
623
-
624
-	$res = false;
625
-	$is_cached = file_exists($cache);
626
-	if ($is_cached
627
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
628
-	) {
629
-		lire_fichier($cache, $res);
630
-		if ($res = unserialize($res)) {
631
-			// mettre le last_modified et le status=304 ?
632
-		}
633
-	}
634
-	if (!$res) {
635
-		$res = recuperer_url($url, $options);
636
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
637
-		if (!$res) {
638
-			if ($is_cached) {
639
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
640
-				lire_fichier($cache, $res);
641
-				$res = unserialize($res);
642
-			}
643
-
644
-			return $errors[$url] = $res;
645
-		}
646
-		ecrire_fichier($cache, serialize($res));
647
-	}
648
-
649
-	return $res;
584
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
585
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
586
+    }
587
+    $default = array(
588
+        'transcoder' => false,
589
+        'methode' => 'GET',
590
+        'taille_max' => null,
591
+        'datas' => '',
592
+        'boundary' => '',
593
+        'refuser_gz' => false,
594
+        'if_modified_since' => '',
595
+        'uri_referer' => '',
596
+        'file' => '',
597
+        'follow_location' => 10,
598
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
599
+        'delai_cache' => _DELAI_RECUPERER_URL_CACHE,
600
+    );
601
+    $options = array_merge($default, $options);
602
+
603
+    // cas ou il n'est pas possible de cacher
604
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
605
+        return recuperer_url($url, $options);
606
+    }
607
+
608
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
609
+    static $errors = array();
610
+    if (isset($errors[$url])) {
611
+        return $errors[$url];
612
+    }
613
+
614
+    $sig = $options;
615
+    unset($sig['if_modified_since']);
616
+    unset($sig['delai_cache']);
617
+    $sig['url'] = $url;
618
+
619
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
620
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
621
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
622
+    $cache = "$sub$cache";
623
+
624
+    $res = false;
625
+    $is_cached = file_exists($cache);
626
+    if ($is_cached
627
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
628
+    ) {
629
+        lire_fichier($cache, $res);
630
+        if ($res = unserialize($res)) {
631
+            // mettre le last_modified et le status=304 ?
632
+        }
633
+    }
634
+    if (!$res) {
635
+        $res = recuperer_url($url, $options);
636
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
637
+        if (!$res) {
638
+            if ($is_cached) {
639
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
640
+                lire_fichier($cache, $res);
641
+                $res = unserialize($res);
642
+            }
643
+
644
+            return $errors[$url] = $res;
645
+        }
646
+        ecrire_fichier($cache, serialize($res));
647
+    }
648
+
649
+    return $res;
650 650
 }
651 651
 
652 652
 /**
@@ -684,52 +684,52 @@  discard block
 block discarded – undo
684 684
  *     - false si la page n'a pu être récupérée (status different de 200)
685 685
  **/
686 686
 function recuperer_page(
687
-	$url,
688
-	$trans = false,
689
-	$get_headers = false,
690
-	$taille_max = null,
691
-	$datas = '',
692
-	$boundary = '',
693
-	$refuser_gz = false,
694
-	$date_verif = '',
695
-	$uri_referer = ''
687
+    $url,
688
+    $trans = false,
689
+    $get_headers = false,
690
+    $taille_max = null,
691
+    $datas = '',
692
+    $boundary = '',
693
+    $refuser_gz = false,
694
+    $date_verif = '',
695
+    $uri_referer = ''
696 696
 ) {
697
-	// $copy = copier le fichier ?
698
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
699
-
700
-	if (!is_null($taille_max) and ($taille_max == 0)) {
701
-		$get = 'HEAD';
702
-	} else {
703
-		$get = 'GET';
704
-	}
705
-
706
-	$options = array(
707
-		'transcoder' => $trans === true,
708
-		'methode' => $get,
709
-		'datas' => $datas,
710
-		'boundary' => $boundary,
711
-		'refuser_gz' => $refuser_gz,
712
-		'if_modified_since' => $date_verif,
713
-		'uri_referer' => $uri_referer,
714
-		'file' => $copy ? $trans : '',
715
-		'follow_location' => 10,
716
-	);
717
-	if (!is_null($taille_max)) {
718
-		$options['taille_max'] = $taille_max;
719
-	}
720
-	// dix tentatives maximum en cas d'entetes 301...
721
-	$res = recuperer_url($url, $options);
722
-	if (!$res) {
723
-		return false;
724
-	}
725
-	if ($res['status'] !== 200) {
726
-		return false;
727
-	}
728
-	if ($get_headers) {
729
-		return $res['headers'] . "\n" . $res['page'];
730
-	}
731
-
732
-	return $res['page'];
697
+    // $copy = copier le fichier ?
698
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
699
+
700
+    if (!is_null($taille_max) and ($taille_max == 0)) {
701
+        $get = 'HEAD';
702
+    } else {
703
+        $get = 'GET';
704
+    }
705
+
706
+    $options = array(
707
+        'transcoder' => $trans === true,
708
+        'methode' => $get,
709
+        'datas' => $datas,
710
+        'boundary' => $boundary,
711
+        'refuser_gz' => $refuser_gz,
712
+        'if_modified_since' => $date_verif,
713
+        'uri_referer' => $uri_referer,
714
+        'file' => $copy ? $trans : '',
715
+        'follow_location' => 10,
716
+    );
717
+    if (!is_null($taille_max)) {
718
+        $options['taille_max'] = $taille_max;
719
+    }
720
+    // dix tentatives maximum en cas d'entetes 301...
721
+    $res = recuperer_url($url, $options);
722
+    if (!$res) {
723
+        return false;
724
+    }
725
+    if ($res['status'] !== 200) {
726
+        return false;
727
+    }
728
+    if ($get_headers) {
729
+        return $res['headers'] . "\n" . $res['page'];
730
+    }
731
+
732
+    return $res['page'];
733 733
 }
734 734
 
735 735
 
@@ -766,48 +766,48 @@  discard block
 block discarded – undo
766 766
  *     - false sinon
767 767
  **/
768 768
 function recuperer_lapage(
769
-	$url,
770
-	$trans = false,
771
-	$get = 'GET',
772
-	$taille_max = 1048576,
773
-	$datas = '',
774
-	$refuser_gz = false,
775
-	$date_verif = '',
776
-	$uri_referer = ''
769
+    $url,
770
+    $trans = false,
771
+    $get = 'GET',
772
+    $taille_max = 1048576,
773
+    $datas = '',
774
+    $refuser_gz = false,
775
+    $date_verif = '',
776
+    $uri_referer = ''
777 777
 ) {
778
-	// $copy = copier le fichier ?
779
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
780
-
781
-	// si on ecrit directement dans un fichier, pour ne pas manipuler
782
-	// en memoire refuser gz
783
-	if ($copy) {
784
-		$refuser_gz = true;
785
-	}
786
-
787
-	$options = array(
788
-		'transcoder' => $trans === true,
789
-		'methode' => $get,
790
-		'datas' => $datas,
791
-		'refuser_gz' => $refuser_gz,
792
-		'if_modified_since' => $date_verif,
793
-		'uri_referer' => $uri_referer,
794
-		'file' => $copy ? $trans : '',
795
-		'follow_location' => false,
796
-	);
797
-	if (!is_null($taille_max)) {
798
-		$options['taille_max'] = $taille_max;
799
-	}
800
-	// dix tentatives maximum en cas d'entetes 301...
801
-	$res = recuperer_url($url, $options);
802
-
803
-	if (!$res) {
804
-		return false;
805
-	}
806
-	if ($res['status'] !== 200) {
807
-		return false;
808
-	}
809
-
810
-	return array($res['headers'], $res['page']);
778
+    // $copy = copier le fichier ?
779
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
780
+
781
+    // si on ecrit directement dans un fichier, pour ne pas manipuler
782
+    // en memoire refuser gz
783
+    if ($copy) {
784
+        $refuser_gz = true;
785
+    }
786
+
787
+    $options = array(
788
+        'transcoder' => $trans === true,
789
+        'methode' => $get,
790
+        'datas' => $datas,
791
+        'refuser_gz' => $refuser_gz,
792
+        'if_modified_since' => $date_verif,
793
+        'uri_referer' => $uri_referer,
794
+        'file' => $copy ? $trans : '',
795
+        'follow_location' => false,
796
+    );
797
+    if (!is_null($taille_max)) {
798
+        $options['taille_max'] = $taille_max;
799
+    }
800
+    // dix tentatives maximum en cas d'entetes 301...
801
+    $res = recuperer_url($url, $options);
802
+
803
+    if (!$res) {
804
+        return false;
805
+    }
806
+    if ($res['status'] !== 200) {
807
+        return false;
808
+    }
809
+
810
+    return array($res['headers'], $res['page']);
811 811
 }
812 812
 
813 813
 /**
@@ -825,41 +825,41 @@  discard block
 block discarded – undo
825 825
  *   string contenu de la resource
826 826
  */
827 827
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
828
-	$taille = 0;
829
-	$result = '';
830
-	$fp = false;
831
-	if ($fichier) {
832
-		include_spip('inc/acces');
833
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
834
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
835
-		if (!$fp and file_exists($fichier)) {
836
-			return filesize($fichier);
837
-		}
838
-		if (!$fp) {
839
-			return false;
840
-		}
841
-		$result = 0; // on renvoie la taille du fichier
842
-	}
843
-	while (!feof($handle) and $taille < $taille_max) {
844
-		$res = fread($handle, 16384);
845
-		$taille += strlen($res);
846
-		if ($fp) {
847
-			fwrite($fp, $res);
848
-			$result = $taille;
849
-		} else {
850
-			$result .= $res;
851
-		}
852
-	}
853
-	if ($fp) {
854
-		spip_fclose_unlock($fp);
855
-		spip_unlink($fichier);
856
-		@rename($tmpfile, $fichier);
857
-		if (!file_exists($fichier)) {
858
-			return false;
859
-		}
860
-	}
861
-
862
-	return $result;
828
+    $taille = 0;
829
+    $result = '';
830
+    $fp = false;
831
+    if ($fichier) {
832
+        include_spip('inc/acces');
833
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
834
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
835
+        if (!$fp and file_exists($fichier)) {
836
+            return filesize($fichier);
837
+        }
838
+        if (!$fp) {
839
+            return false;
840
+        }
841
+        $result = 0; // on renvoie la taille du fichier
842
+    }
843
+    while (!feof($handle) and $taille < $taille_max) {
844
+        $res = fread($handle, 16384);
845
+        $taille += strlen($res);
846
+        if ($fp) {
847
+            fwrite($fp, $res);
848
+            $result = $taille;
849
+        } else {
850
+            $result .= $res;
851
+        }
852
+    }
853
+    if ($fp) {
854
+        spip_fclose_unlock($fp);
855
+        spip_unlink($fichier);
856
+        @rename($tmpfile, $fichier);
857
+        if (!file_exists($fichier)) {
858
+            return false;
859
+        }
860
+    }
861
+
862
+    return $result;
863 863
 }
864 864
 
865 865
 /**
@@ -881,34 +881,34 @@  discard block
 block discarded – undo
881 881
  *   string location
882 882
  */
883 883
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
884
-	$result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
885
-
886
-	$s = @trim(fgets($handle, 16384));
887
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
888
-		return false;
889
-	}
890
-	$result['status'] = intval($r[1]);
891
-	while ($s = trim(fgets($handle, 16384))) {
892
-		$result['headers'][] = $s . "\n";
893
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
894
-		list(, $d, $v) = $r;
895
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
896
-			$result['location'] = $v;
897
-		} elseif ($d == 'Last-Modified') {
898
-			$result['last_modified'] = strtotime($v);
899
-		}
900
-	}
901
-	if ($if_modified_since
902
-		and $result['last_modified']
903
-		and $if_modified_since > $result['last_modified']
904
-		and $result['status'] == 200
905
-	) {
906
-		$result['status'] = 304;
907
-	}
908
-
909
-	$result['headers'] = implode('', $result['headers']);
910
-
911
-	return $result;
884
+    $result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
885
+
886
+    $s = @trim(fgets($handle, 16384));
887
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
888
+        return false;
889
+    }
890
+    $result['status'] = intval($r[1]);
891
+    while ($s = trim(fgets($handle, 16384))) {
892
+        $result['headers'][] = $s . "\n";
893
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
894
+        list(, $d, $v) = $r;
895
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
896
+            $result['location'] = $v;
897
+        } elseif ($d == 'Last-Modified') {
898
+            $result['last_modified'] = strtotime($v);
899
+        }
900
+    }
901
+    if ($if_modified_since
902
+        and $result['last_modified']
903
+        and $if_modified_since > $result['last_modified']
904
+        and $result['status'] == 200
905
+    ) {
906
+        $result['status'] = 304;
907
+    }
908
+
909
+    $result['headers'] = implode('', $result['headers']);
910
+
911
+    return $result;
912 912
 }
913 913
 
914 914
 /**
@@ -930,20 +930,20 @@  discard block
 block discarded – undo
930 930
  *     - le tableau des entetes dans tous les autres cas
931 931
  **/
932 932
 function recuperer_entetes($f, $date_verif = '') {
933
-	//Cas ou la page distante n'a pas bouge depuis
934
-	//la derniere visite
935
-	$res = recuperer_entetes_complets($f, $date_verif);
936
-	if (!$res) {
937
-		return false;
938
-	}
939
-	if ($res['location']) {
940
-		return $res['location'];
941
-	}
942
-	if ($res['status'] != 200) {
943
-		return $res['status'];
944
-	}
945
-
946
-	return explode("\n", $res['headers']);
933
+    //Cas ou la page distante n'a pas bouge depuis
934
+    //la derniere visite
935
+    $res = recuperer_entetes_complets($f, $date_verif);
936
+    if (!$res) {
937
+        return false;
938
+    }
939
+    if ($res['location']) {
940
+        return $res['location'];
941
+    }
942
+    if ($res['status'] != 200) {
943
+        return $res['status'];
944
+    }
945
+
946
+    return explode("\n", $res['headers']);
947 947
 }
948 948
 
949 949
 /**
@@ -965,22 +965,22 @@  discard block
 block discarded – undo
965 965
  *     Nom du fichier pour copie locale
966 966
  **/
967 967
 function nom_fichier_copie_locale($source, $extension) {
968
-	include_spip('inc/documents');
968
+    include_spip('inc/documents');
969 969
 
970
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
971
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
970
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
971
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
972 972
 
973
-	// on se place tout le temps comme si on etait a la racine
974
-	if (_DIR_RACINE) {
975
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
976
-	}
973
+    // on se place tout le temps comme si on etait a la racine
974
+    if (_DIR_RACINE) {
975
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
976
+    }
977 977
 
978
-	$m = md5($source);
978
+    $m = md5($source);
979 979
 
980
-	return $d
981
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
982
-	. substr($m, 0, 4)
983
-	. ".$extension";
980
+    return $d
981
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
982
+    . substr($m, 0, 4)
983
+    . ".$extension";
984 984
 }
985 985
 
986 986
 /**
@@ -998,68 +998,68 @@  discard block
 block discarded – undo
998 998
  *      Nom du fichier calculé
999 999
  **/
1000 1000
 function fichier_copie_locale($source) {
1001
-	// Si c'est deja local pas de souci
1002
-	if (!tester_url_absolue($source)) {
1003
-		if (_DIR_RACINE) {
1004
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1005
-		}
1006
-
1007
-		return $source;
1008
-	}
1009
-
1010
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1011
-	// a deja ete copie en local avec cette extension
1012
-	// dans ce cas elle est fiable, pas la peine de requeter en base
1013
-	$path_parts = pathinfo($source);
1014
-	if (!isset($path_parts['extension'])) {
1015
-		$path_parts['extension'] = '';
1016
-	}
1017
-	$ext = $path_parts ? $path_parts['extension'] : '';
1018
-	if ($ext
1019
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1020
-		and $f = nom_fichier_copie_locale($source, $ext)
1021
-		and file_exists(_DIR_RACINE . $f)
1022
-	) {
1023
-		return $f;
1024
-	}
1025
-
1026
-
1027
-	// Si c'est deja dans la table des documents,
1028
-	// ramener le nom de sa copie potentielle
1029
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1030
-
1031
-	if ($ext) {
1032
-		return nom_fichier_copie_locale($source, $ext);
1033
-	}
1034
-
1035
-	// voir si l'extension indiquee dans le nom du fichier est ok
1036
-	// et si il n'aurait pas deja ete rapatrie
1037
-
1038
-	$ext = $path_parts ? $path_parts['extension'] : '';
1039
-
1040
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1041
-		$f = nom_fichier_copie_locale($source, $ext);
1042
-		if (file_exists(_DIR_RACINE . $f)) {
1043
-			return $f;
1044
-		}
1045
-	}
1046
-
1047
-	// Ping  pour voir si son extension est connue et autorisee
1048
-	// avec mise en cache du resultat du ping
1049
-
1050
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1051
-	if (!@file_exists($cache)
1052
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1053
-		or _request('var_mode') == 'recalcul'
1054
-	) {
1055
-		$path_parts = recuperer_infos_distantes($source, 0, false);
1056
-		ecrire_fichier($cache, serialize($path_parts));
1057
-	}
1058
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1059
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1060
-		return nom_fichier_copie_locale($source, $ext);
1061
-	}
1062
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1001
+    // Si c'est deja local pas de souci
1002
+    if (!tester_url_absolue($source)) {
1003
+        if (_DIR_RACINE) {
1004
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1005
+        }
1006
+
1007
+        return $source;
1008
+    }
1009
+
1010
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1011
+    // a deja ete copie en local avec cette extension
1012
+    // dans ce cas elle est fiable, pas la peine de requeter en base
1013
+    $path_parts = pathinfo($source);
1014
+    if (!isset($path_parts['extension'])) {
1015
+        $path_parts['extension'] = '';
1016
+    }
1017
+    $ext = $path_parts ? $path_parts['extension'] : '';
1018
+    if ($ext
1019
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1020
+        and $f = nom_fichier_copie_locale($source, $ext)
1021
+        and file_exists(_DIR_RACINE . $f)
1022
+    ) {
1023
+        return $f;
1024
+    }
1025
+
1026
+
1027
+    // Si c'est deja dans la table des documents,
1028
+    // ramener le nom de sa copie potentielle
1029
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1030
+
1031
+    if ($ext) {
1032
+        return nom_fichier_copie_locale($source, $ext);
1033
+    }
1034
+
1035
+    // voir si l'extension indiquee dans le nom du fichier est ok
1036
+    // et si il n'aurait pas deja ete rapatrie
1037
+
1038
+    $ext = $path_parts ? $path_parts['extension'] : '';
1039
+
1040
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1041
+        $f = nom_fichier_copie_locale($source, $ext);
1042
+        if (file_exists(_DIR_RACINE . $f)) {
1043
+            return $f;
1044
+        }
1045
+    }
1046
+
1047
+    // Ping  pour voir si son extension est connue et autorisee
1048
+    // avec mise en cache du resultat du ping
1049
+
1050
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1051
+    if (!@file_exists($cache)
1052
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
1053
+        or _request('var_mode') == 'recalcul'
1054
+    ) {
1055
+        $path_parts = recuperer_infos_distantes($source, 0, false);
1056
+        ecrire_fichier($cache, serialize($path_parts));
1057
+    }
1058
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1059
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1060
+        return nom_fichier_copie_locale($source, $ext);
1061
+    }
1062
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1063 1063
 }
1064 1064
 
1065 1065
 
@@ -1087,144 +1087,144 @@  discard block
 block discarded – undo
1087 1087
  **/
1088 1088
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
1089 1089
 
1090
-	// pas la peine de perdre son temps
1091
-	if (!tester_url_absolue($source)) {
1092
-		return false;
1093
-	}
1094
-
1095
-	# charger les alias des types mime
1096
-	include_spip('base/typedoc');
1097
-
1098
-	$a = array();
1099
-	$mime_type = '';
1100
-	// On va directement charger le debut des images et des fichiers html,
1101
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1102
-	// ca echoue l'utilisateur devra les entrer...
1103
-	if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1104
-		list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1105
-
1106
-		if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1107
-			$mime_type = (trim($regs[1]));
1108
-		} else {
1109
-			$mime_type = '';
1110
-		} // inconnu
1111
-
1112
-		// Appliquer les alias
1113
-		while (isset($GLOBALS['mime_alias'][$mime_type])) {
1114
-			$mime_type = $GLOBALS['mime_alias'][$mime_type];
1115
-		}
1116
-
1117
-		// Si on a un mime-type insignifiant
1118
-		// text/plain,application/octet-stream ou vide
1119
-		// c'est peut-etre que le serveur ne sait pas
1120
-		// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1121
-		// ou le Content-Disposition: attachment; filename=...
1122
-		$t = null;
1123
-		if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1124
-			if (!$t
1125
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1126
-			) {
1127
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1128
-			}
1129
-			if (!$t
1130
-				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1131
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1132
-			) {
1133
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1134
-			}
1135
-		}
1136
-
1137
-		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1138
-		if (!$t) {
1139
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1140
-		}
1141
-
1142
-		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1143
-		// On essaie de nouveau avec l'extension
1144
-		if (!$t
1145
-			and $mime_type != 'text/plain'
1146
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1147
-		) {
1148
-			# eviter xxx.3 => 3gp (> SPIP 3)
1149
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1150
-		}
1151
-
1152
-		if ($t) {
1153
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1154
-			$a['extension'] = $t['extension'];
1155
-		} else {
1156
-			# par defaut on retombe sur '.bin' si c'est autorise
1157
-			spip_log("mime-type $mime_type inconnu", 'distant');
1158
-			$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1159
-			if (!$t) {
1160
-				return false;
1161
-			}
1162
-			$a['extension'] = $t['extension'];
1163
-		}
1164
-
1165
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1166
-			$a['taille'] = intval($regs[1]);
1167
-		}
1168
-	}
1169
-
1170
-	// Echec avec HEAD, on tente avec GET
1171
-	if (!$a and !$max) {
1172
-		spip_log("tenter GET $source", 'distant');
1173
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1174
-	}
1175
-
1176
-	// si on a rien trouve pas la peine d'insister
1177
-	if (!$a) {
1178
-		return false;
1179
-	}
1180
-
1181
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1182
-	// recharger le document en GET et recuperer des donnees supplementaires...
1183
-	include_spip('inc/filtres_images_lib_mini');
1184
-	if (strpos($mime_type, "image/") === 0
1185
-	  and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1186
-		if ($max == 0
1187
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1188
-			and in_array($extension, formats_image_acceptables())
1189
-			and $charger_si_petite_image
1190
-		) {
1191
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1192
-		} else {
1193
-			if ($a['body']) {
1194
-				$a['extension'] = $extension;
1195
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1196
-				ecrire_fichier($a['fichier'], $a['body']);
1197
-				$size_image = @spip_getimagesize($a['fichier']);
1198
-				$a['largeur'] = intval($size_image[0]);
1199
-				$a['hauteur'] = intval($size_image[1]);
1200
-				$a['type_image'] = true;
1201
-			}
1202
-		}
1203
-	}
1204
-
1205
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1206
-	// ce sera mieux que 0x0
1207
-	// Flash is dead!
1208
-	if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1209
-		and empty($a['largeur'])
1210
-	) {
1211
-		$a['largeur'] = 425;
1212
-		$a['hauteur'] = 350;
1213
-	}
1214
-
1215
-	if ($mime_type == 'text/html') {
1216
-		include_spip('inc/filtres');
1217
-		$page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1218
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1219
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1220
-		}
1221
-		if (!isset($a['taille']) or !$a['taille']) {
1222
-			$a['taille'] = strlen($page); # a peu pres
1223
-		}
1224
-	}
1225
-	$a['mime_type'] = $mime_type;
1226
-
1227
-	return $a;
1090
+    // pas la peine de perdre son temps
1091
+    if (!tester_url_absolue($source)) {
1092
+        return false;
1093
+    }
1094
+
1095
+    # charger les alias des types mime
1096
+    include_spip('base/typedoc');
1097
+
1098
+    $a = array();
1099
+    $mime_type = '';
1100
+    // On va directement charger le debut des images et des fichiers html,
1101
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1102
+    // ca echoue l'utilisateur devra les entrer...
1103
+    if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1104
+        list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1105
+
1106
+        if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1107
+            $mime_type = (trim($regs[1]));
1108
+        } else {
1109
+            $mime_type = '';
1110
+        } // inconnu
1111
+
1112
+        // Appliquer les alias
1113
+        while (isset($GLOBALS['mime_alias'][$mime_type])) {
1114
+            $mime_type = $GLOBALS['mime_alias'][$mime_type];
1115
+        }
1116
+
1117
+        // Si on a un mime-type insignifiant
1118
+        // text/plain,application/octet-stream ou vide
1119
+        // c'est peut-etre que le serveur ne sait pas
1120
+        // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1121
+        // ou le Content-Disposition: attachment; filename=...
1122
+        $t = null;
1123
+        if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1124
+            if (!$t
1125
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1126
+            ) {
1127
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1128
+            }
1129
+            if (!$t
1130
+                and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1131
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1132
+            ) {
1133
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1134
+            }
1135
+        }
1136
+
1137
+        // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1138
+        if (!$t) {
1139
+            $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1140
+        }
1141
+
1142
+        // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1143
+        // On essaie de nouveau avec l'extension
1144
+        if (!$t
1145
+            and $mime_type != 'text/plain'
1146
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1147
+        ) {
1148
+            # eviter xxx.3 => 3gp (> SPIP 3)
1149
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1150
+        }
1151
+
1152
+        if ($t) {
1153
+            spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1154
+            $a['extension'] = $t['extension'];
1155
+        } else {
1156
+            # par defaut on retombe sur '.bin' si c'est autorise
1157
+            spip_log("mime-type $mime_type inconnu", 'distant');
1158
+            $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1159
+            if (!$t) {
1160
+                return false;
1161
+            }
1162
+            $a['extension'] = $t['extension'];
1163
+        }
1164
+
1165
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1166
+            $a['taille'] = intval($regs[1]);
1167
+        }
1168
+    }
1169
+
1170
+    // Echec avec HEAD, on tente avec GET
1171
+    if (!$a and !$max) {
1172
+        spip_log("tenter GET $source", 'distant');
1173
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1174
+    }
1175
+
1176
+    // si on a rien trouve pas la peine d'insister
1177
+    if (!$a) {
1178
+        return false;
1179
+    }
1180
+
1181
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1182
+    // recharger le document en GET et recuperer des donnees supplementaires...
1183
+    include_spip('inc/filtres_images_lib_mini');
1184
+    if (strpos($mime_type, "image/") === 0
1185
+      and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1186
+        if ($max == 0
1187
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1188
+            and in_array($extension, formats_image_acceptables())
1189
+            and $charger_si_petite_image
1190
+        ) {
1191
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1192
+        } else {
1193
+            if ($a['body']) {
1194
+                $a['extension'] = $extension;
1195
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1196
+                ecrire_fichier($a['fichier'], $a['body']);
1197
+                $size_image = @spip_getimagesize($a['fichier']);
1198
+                $a['largeur'] = intval($size_image[0]);
1199
+                $a['hauteur'] = intval($size_image[1]);
1200
+                $a['type_image'] = true;
1201
+            }
1202
+        }
1203
+    }
1204
+
1205
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1206
+    // ce sera mieux que 0x0
1207
+    // Flash is dead!
1208
+    if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1209
+        and empty($a['largeur'])
1210
+    ) {
1211
+        $a['largeur'] = 425;
1212
+        $a['hauteur'] = 350;
1213
+    }
1214
+
1215
+    if ($mime_type == 'text/html') {
1216
+        include_spip('inc/filtres');
1217
+        $page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1218
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1219
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1220
+        }
1221
+        if (!isset($a['taille']) or !$a['taille']) {
1222
+            $a['taille'] = strlen($page); # a peu pres
1223
+        }
1224
+    }
1225
+    $a['mime_type'] = $mime_type;
1226
+
1227
+    return $a;
1228 1228
 }
1229 1229
 
1230 1230
 
@@ -1240,45 +1240,45 @@  discard block
 block discarded – undo
1240 1240
  * @return string
1241 1241
  */
1242 1242
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1243
-	if (is_null($http_proxy)) {
1244
-		$http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1245
-	}
1246
-	// rien a faire si pas de proxy :)
1247
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1248
-		return '';
1249
-	}
1250
-
1251
-	if (is_null($http_noproxy)) {
1252
-		$http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1253
-	}
1254
-	// si pas d'exception, on retourne le proxy
1255
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1256
-		return $http_proxy;
1257
-	}
1258
-
1259
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1260
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1261
-	$http_noproxy = str_replace("\n", " ", $http_noproxy);
1262
-	$http_noproxy = str_replace("\r", " ", $http_noproxy);
1263
-	$http_noproxy = " $http_noproxy ";
1264
-	$domain = $host;
1265
-	// si le domaine exact www.example.org est dans les exceptions
1266
-	if (strpos($http_noproxy, " $domain ") !== false)
1267
-		return '';
1268
-
1269
-	while (strpos($domain, '.') !== false) {
1270
-		$domain = explode('.', $domain);
1271
-		array_shift($domain);
1272
-		$domain = implode('.', $domain);
1273
-
1274
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1275
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1276
-			return '';
1277
-		}
1278
-	}
1279
-
1280
-	// ok c'est pas une exception
1281
-	return $http_proxy;
1243
+    if (is_null($http_proxy)) {
1244
+        $http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1245
+    }
1246
+    // rien a faire si pas de proxy :)
1247
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1248
+        return '';
1249
+    }
1250
+
1251
+    if (is_null($http_noproxy)) {
1252
+        $http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1253
+    }
1254
+    // si pas d'exception, on retourne le proxy
1255
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1256
+        return $http_proxy;
1257
+    }
1258
+
1259
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1260
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1261
+    $http_noproxy = str_replace("\n", " ", $http_noproxy);
1262
+    $http_noproxy = str_replace("\r", " ", $http_noproxy);
1263
+    $http_noproxy = " $http_noproxy ";
1264
+    $domain = $host;
1265
+    // si le domaine exact www.example.org est dans les exceptions
1266
+    if (strpos($http_noproxy, " $domain ") !== false)
1267
+        return '';
1268
+
1269
+    while (strpos($domain, '.') !== false) {
1270
+        $domain = explode('.', $domain);
1271
+        array_shift($domain);
1272
+        $domain = implode('.', $domain);
1273
+
1274
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1275
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1276
+            return '';
1277
+        }
1278
+    }
1279
+
1280
+    // ok c'est pas une exception
1281
+    return $http_proxy;
1282 1282
 }
1283 1283
 
1284 1284
 
@@ -1301,58 +1301,58 @@  discard block
 block discarded – undo
1301 1301
  * @return array
1302 1302
  */
1303 1303
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1304
-	$user = $via_proxy = $proxy_user = '';
1305
-	$fopen = false;
1306
-
1307
-	$t = @parse_url($url);
1308
-	$host = $t['host'];
1309
-	if ($t['scheme'] == 'http') {
1310
-		$scheme = 'http';
1311
-		$noproxy = '';
1312
-	} elseif ($t['scheme'] == 'https') {
1313
-		$scheme = 'ssl';
1314
-		$noproxy = 'ssl://';
1315
-		if (!isset($t['port']) || !($port = $t['port'])) {
1316
-			$t['port'] = 443;
1317
-		}
1318
-	} else {
1319
-		$scheme = $t['scheme'];
1320
-		$noproxy = $scheme . '://';
1321
-	}
1322
-	if (isset($t['user'])) {
1323
-		$user = array($t['user'], $t['pass']);
1324
-	}
1325
-
1326
-	if (!isset($t['port']) || !($port = $t['port'])) {
1327
-		$port = 80;
1328
-	}
1329
-	if (!isset($t['path']) || !($path = $t['path'])) {
1330
-		$path = '/';
1331
-	}
1332
-
1333
-	if (!empty($t['query'])) {
1334
-		$path .= '?' . $t['query'];
1335
-	}
1336
-
1337
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1338
-	if (!$f or !is_resource($f)) {
1339
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1340
-		// ce qui correspond a $f===110
1341
-		if ($f !== 110
1342
-			and !need_proxy($host)
1343
-			and !_request('tester_proxy')
1344
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1345
-		) {
1346
-			$f = @fopen($url, 'rb');
1347
-			spip_log("connexion vers $url par simple fopen", 'distant');
1348
-			$fopen = true;
1349
-		} else {
1350
-			// echec total
1351
-			$f = false;
1352
-		}
1353
-	}
1354
-
1355
-	return array($f, $fopen);
1304
+    $user = $via_proxy = $proxy_user = '';
1305
+    $fopen = false;
1306
+
1307
+    $t = @parse_url($url);
1308
+    $host = $t['host'];
1309
+    if ($t['scheme'] == 'http') {
1310
+        $scheme = 'http';
1311
+        $noproxy = '';
1312
+    } elseif ($t['scheme'] == 'https') {
1313
+        $scheme = 'ssl';
1314
+        $noproxy = 'ssl://';
1315
+        if (!isset($t['port']) || !($port = $t['port'])) {
1316
+            $t['port'] = 443;
1317
+        }
1318
+    } else {
1319
+        $scheme = $t['scheme'];
1320
+        $noproxy = $scheme . '://';
1321
+    }
1322
+    if (isset($t['user'])) {
1323
+        $user = array($t['user'], $t['pass']);
1324
+    }
1325
+
1326
+    if (!isset($t['port']) || !($port = $t['port'])) {
1327
+        $port = 80;
1328
+    }
1329
+    if (!isset($t['path']) || !($path = $t['path'])) {
1330
+        $path = '/';
1331
+    }
1332
+
1333
+    if (!empty($t['query'])) {
1334
+        $path .= '?' . $t['query'];
1335
+    }
1336
+
1337
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1338
+    if (!$f or !is_resource($f)) {
1339
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1340
+        // ce qui correspond a $f===110
1341
+        if ($f !== 110
1342
+            and !need_proxy($host)
1343
+            and !_request('tester_proxy')
1344
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1345
+        ) {
1346
+            $f = @fopen($url, 'rb');
1347
+            spip_log("connexion vers $url par simple fopen", 'distant');
1348
+            $fopen = true;
1349
+        } else {
1350
+            // echec total
1351
+            $f = false;
1352
+        }
1353
+    }
1354
+
1355
+    return array($f, $fopen);
1356 1356
 }
1357 1357
 
1358 1358
 /**
@@ -1387,127 +1387,127 @@  discard block
 block discarded – undo
1387 1387
  *   resource socket vers l'url demandee
1388 1388
  */
1389 1389
 function lance_requete(
1390
-	$method,
1391
-	$scheme,
1392
-	$user,
1393
-	$host,
1394
-	$path,
1395
-	$port,
1396
-	$noproxy,
1397
-	$refuse_gz = false,
1398
-	$referer = '',
1399
-	$datas = '',
1400
-	$vers = 'HTTP/1.0',
1401
-	$date = ''
1390
+    $method,
1391
+    $scheme,
1392
+    $user,
1393
+    $host,
1394
+    $path,
1395
+    $port,
1396
+    $noproxy,
1397
+    $refuse_gz = false,
1398
+    $referer = '',
1399
+    $datas = '',
1400
+    $vers = 'HTTP/1.0',
1401
+    $date = ''
1402 1402
 ) {
1403 1403
 
1404
-	$proxy_user = '';
1405
-	$http_proxy = need_proxy($host);
1406
-	if ($user) {
1407
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1408
-	}
1409
-
1410
-	$connect = '';
1411
-	if ($http_proxy) {
1412
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1413
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1414
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1415
-				. "Host: $path_host\r\n"
1416
-				. "Proxy-Connection: Keep-Alive\r\n";
1417
-		} else {
1418
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1419
-				. (!$user ? '' : "$user@")
1420
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1421
-		}
1422
-		$t2 = @parse_url($http_proxy);
1423
-		$first_host = $t2['host'];
1424
-		if (!($port = $t2['port'])) {
1425
-			$port = 80;
1426
-		}
1427
-		if ($t2['user']) {
1428
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1429
-		}
1430
-	} else {
1431
-		$first_host = $noproxy . $host;
1432
-	}
1433
-
1434
-	if ($connect) {
1435
-		$streamContext = stream_context_create(array(
1436
-			'ssl' => array(
1437
-				'verify_peer' => false,
1438
-				'allow_self_signed' => true,
1439
-				'SNI_enabled' => true,
1440
-				'peer_name' => $host,
1441
-			)
1442
-		));
1443
-		if (version_compare(phpversion(), '5.6', '<')) {
1444
-			stream_context_set_option($streamContext, 'ssl', 'SNI_server_name', $host);
1445
-		}
1446
-		$f = @stream_socket_client(
1447
-			"tcp://$first_host:$port",
1448
-			$errno,
1449
-			$errstr,
1450
-			_INC_DISTANT_CONNECT_TIMEOUT,
1451
-			STREAM_CLIENT_CONNECT,
1452
-			$streamContext
1453
-		);
1454
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1455
-		if (!$f) {
1456
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1457
-			return $errno;
1458
-		}
1459
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1460
-
1461
-		fputs($f, $connect);
1462
-		fputs($f, "\r\n");
1463
-		$res = fread($f, 1024);
1464
-		if (!$res
1465
-			or !count($res = explode(' ', $res))
1466
-			or $res[1] !== '200'
1467
-		) {
1468
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1469
-			fclose($f);
1470
-
1471
-			return false;
1472
-		}
1473
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1474
-		stream_set_blocking($f, true);
1475
-		// envoyer le handshake
1476
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1477
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1478
-	} else {
1479
-		$ntry = 3;
1480
-		do {
1481
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1482
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1483
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1484
-		if (!$f) {
1485
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1486
-
1487
-			return $errno;
1488
-		}
1489
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1490
-	}
1491
-
1492
-	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1493
-
1494
-	$host_port = $host;
1495
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1496
-		$host_port .= ":$port";
1497
-	}
1498
-	$req = "$method $path $vers\r\n"
1499
-		. "Host: $host_port\r\n"
1500
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1501
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1502
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1503
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1504
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1505
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1506
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1404
+    $proxy_user = '';
1405
+    $http_proxy = need_proxy($host);
1406
+    if ($user) {
1407
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1408
+    }
1409
+
1410
+    $connect = '';
1411
+    if ($http_proxy) {
1412
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1413
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1414
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1415
+                . "Host: $path_host\r\n"
1416
+                . "Proxy-Connection: Keep-Alive\r\n";
1417
+        } else {
1418
+            $path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1419
+                . (!$user ? '' : "$user@")
1420
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1421
+        }
1422
+        $t2 = @parse_url($http_proxy);
1423
+        $first_host = $t2['host'];
1424
+        if (!($port = $t2['port'])) {
1425
+            $port = 80;
1426
+        }
1427
+        if ($t2['user']) {
1428
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1429
+        }
1430
+    } else {
1431
+        $first_host = $noproxy . $host;
1432
+    }
1433
+
1434
+    if ($connect) {
1435
+        $streamContext = stream_context_create(array(
1436
+            'ssl' => array(
1437
+                'verify_peer' => false,
1438
+                'allow_self_signed' => true,
1439
+                'SNI_enabled' => true,
1440
+                'peer_name' => $host,
1441
+            )
1442
+        ));
1443
+        if (version_compare(phpversion(), '5.6', '<')) {
1444
+            stream_context_set_option($streamContext, 'ssl', 'SNI_server_name', $host);
1445
+        }
1446
+        $f = @stream_socket_client(
1447
+            "tcp://$first_host:$port",
1448
+            $errno,
1449
+            $errstr,
1450
+            _INC_DISTANT_CONNECT_TIMEOUT,
1451
+            STREAM_CLIENT_CONNECT,
1452
+            $streamContext
1453
+        );
1454
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1455
+        if (!$f) {
1456
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1457
+            return $errno;
1458
+        }
1459
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1460
+
1461
+        fputs($f, $connect);
1462
+        fputs($f, "\r\n");
1463
+        $res = fread($f, 1024);
1464
+        if (!$res
1465
+            or !count($res = explode(' ', $res))
1466
+            or $res[1] !== '200'
1467
+        ) {
1468
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1469
+            fclose($f);
1470
+
1471
+            return false;
1472
+        }
1473
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1474
+        stream_set_blocking($f, true);
1475
+        // envoyer le handshake
1476
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1477
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1478
+    } else {
1479
+        $ntry = 3;
1480
+        do {
1481
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1482
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1483
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1484
+        if (!$f) {
1485
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1486
+
1487
+            return $errno;
1488
+        }
1489
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1490
+    }
1491
+
1492
+    $site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1493
+
1494
+    $host_port = $host;
1495
+    if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1496
+        $host_port .= ":$port";
1497
+    }
1498
+    $req = "$method $path $vers\r\n"
1499
+        . "Host: $host_port\r\n"
1500
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1501
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1502
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1503
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1504
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1505
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1506
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1507 1507
 
1508 1508
 #	spip_log("Requete\n$req", 'distant');
1509
-	fputs($f, $req);
1510
-	fputs($f, $datas ? $datas : "\r\n");
1509
+    fputs($f, $req);
1510
+    fputs($f, $datas ? $datas : "\r\n");
1511 1511
 
1512
-	return $f;
1512
+    return $f;
1513 1513
 }
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32 32
 	define('_INC_DISTANT_MAX_SIZE', 2097152);
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38
-define('_REGEXP_COPIE_LOCALE', ',' 	.
38
+define('_REGEXP_COPIE_LOCALE', ','.
39 39
 	preg_replace(
40 40
 		'@^https?:@',
41 41
 		'https?:',
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 
71 71
 	// si c'est la protection de soi-meme, retourner le path
72 72
 	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
73
+		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)).urldecode($match[1]);
74 74
 
75 75
 		return @file_exists($source) ? $source : false;
76 76
 	}
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 		return false;
91 91
 	}
92 92
 
93
-	$localrac = _DIR_RACINE . $local;
93
+	$localrac = _DIR_RACINE.$local;
94 94
 	$t = ($mode == 'force') ? false : @file_exists($localrac);
95 95
 
96 96
 	// test d'existence du fichier
@@ -115,13 +115,13 @@  discard block
 block discarded – undo
115 115
 			array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116 116
 		);
117 117
 		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
118
+			spip_log("copie_locale : Echec recuperation $source sur $localrac status : ".$res['status'], 'distant'._LOG_INFO_IMPORTANTE);
119 119
 		}
120 120
 		if (!$res['length']) {
121 121
 			// si $t c'est sans doute juste un not-modified-since
122 122
 			return $t ? $local : false;
123 123
 		}
124
-		spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
124
+		spip_log("copie_locale : recuperation $source sur $localrac taille ".$res['length'].' OK', 'distant');
125 125
 
126 126
 		// pour une eventuelle indexation
127 127
 		pipeline(
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
  *   url ou false en cas d'echec
154 154
  */
155 155
 function valider_url_distante($url, $known_hosts = array()) {
156
-	if (!function_exists('protocole_verifier')){
156
+	if (!function_exists('protocole_verifier')) {
157 157
 		include_spip('inc/filtres_mini');
158 158
 	}
159 159
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 	}
163 163
 	
164 164
 	$parsed_url = parse_url($url);
165
-	if (!$parsed_url or empty($parsed_url['host']) ) {
165
+	if (!$parsed_url or empty($parsed_url['host'])) {
166 166
 		return false;
167 167
 	}
168 168
 
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
 			}
204 204
 		}
205 205
 		if ($ip) {
206
-			$parts = array_map('intval', explode( '.', $ip ));
206
+			$parts = array_map('intval', explode('.', $ip));
207 207
 			if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
-			  or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
-			  or ( 192 === $parts[0] && 168 === $parts[1] )
208
+			  or (172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1])
209
+			  or (192 === $parts[0] && 168 === $parts[1])
210 210
 			) {
211 211
 				return false;
212 212
 			}
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	}
219 219
 
220 220
 	$port = $parsed_url['port'];
221
-	if ($port === 80  or $port === 443  or $port === 8080) {
221
+	if ($port === 80 or $port === 443 or $port === 8080) {
222 222
 		return $url;
223 223
 	}
224 224
 
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 				}
286 286
 			}
287 287
 			if ($taille > 500) {
288
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
288
+				$boundary = substr(md5(rand().'spip'), 0, 8);
289 289
 			}
290 290
 		}
291 291
 
@@ -313,16 +313,16 @@  discard block
 block discarded – undo
313 313
 			}
314 314
 		} else {
315 315
 			// fabrique une chaine HTTP simple pour un POST
316
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
316
+			$entete = 'Content-Type: application/x-www-form-urlencoded'."\r\n";
317 317
 			$chaine = array();
318 318
 			if (is_array($donnees)) {
319 319
 				foreach ($donnees as $cle => $valeur) {
320 320
 					if (is_array($valeur)) {
321 321
 						foreach ($valeur as $val2) {
322
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
322
+							$chaine[] = rawurlencode($cle).'[]='.rawurlencode($val2);
323 323
 						}
324 324
 					} else {
325
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
325
+						$chaine[] = rawurlencode($cle).'='.rawurlencode($valeur);
326 326
 					}
327 327
 				}
328 328
 				$chaine = implode('&', $chaine);
@@ -423,9 +423,9 @@  discard block
 block discarded – undo
423 423
 	if (!empty($options['datas'])) {
424 424
 		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
425 425
 		if (stripos($head, 'Content-Length:') === false) {
426
-			$head .= 'Content-Length: ' . strlen($postdata);
426
+			$head .= 'Content-Length: '.strlen($postdata);
427 427
 		}
428
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
428
+		$options['datas'] = $head."\r\n\r\n".$postdata;
429 429
 		if (strlen($postdata)) {
430 430
 			$options['methode'] = 'POST';
431 431
 		}
@@ -434,9 +434,9 @@  discard block
 block discarded – undo
434 434
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
435 435
 	$url = preg_replace(',^feed://,i', 'http://', $url);
436 436
 	if (!tester_url_absolue($url)) {
437
-		$url = 'http://' . $url;
437
+		$url = 'http://'.$url;
438 438
 	} elseif (strncmp($url, '//', 2) == 0) {
439
-		$url = 'http:' . $url;
439
+		$url = 'http:'.$url;
440 440
 	}
441 441
 
442 442
 	$url = url_to_ascii($url);
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 		$options['if_modified_since']
466 466
 	);
467 467
 	if (!$handle) {
468
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
468
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
469 469
 
470 470
 		return false;
471 471
 	}
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 					'status' => 200,
495 495
 				);
496 496
 			} else {
497
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
497
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
498 498
 				return false;
499 499
 			}
500 500
 		} elseif ($res['location'] and $options['follow_location']) {
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 
507 507
 			return recuperer_url($url, $options);
508 508
 		} elseif ($res['status'] !== 200) {
509
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
509
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
510 510
 		}
511 511
 		$result['status'] = $res['status'];
512 512
 		if (isset($res['headers'])) {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 	$gz = false;
533 533
 	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
534
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
534
+		$gz = (_DIR_TMP.md5(uniqid(mt_rand())).'.tmp.gz');
535 535
 	}
536 536
 
537 537
 	// si on a pas deja recuperer le contenu par une methode detournee
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 	$sig['url'] = $url;
618 618
 
619 619
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
620
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
620
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
621 621
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
622 622
 	$cache = "$sub$cache";
623 623
 
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		return false;
727 727
 	}
728 728
 	if ($get_headers) {
729
-		return $res['headers'] . "\n" . $res['page'];
729
+		return $res['headers']."\n".$res['page'];
730 730
 	}
731 731
 
732 732
 	return $res['page'];
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 	$fp = false;
831 831
 	if ($fichier) {
832 832
 		include_spip('inc/acces');
833
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
833
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
834 834
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
835 835
 		if (!$fp and file_exists($fichier)) {
836 836
 			return filesize($fichier);
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 	}
890 890
 	$result['status'] = intval($r[1]);
891 891
 	while ($s = trim(fgets($handle, 16384))) {
892
-		$result['headers'][] = $s . "\n";
892
+		$result['headers'][] = $s."\n";
893 893
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
894 894
 		list(, $d, $v) = $r;
895 895
 		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
@@ -972,13 +972,13 @@  discard block
 block discarded – undo
972 972
 
973 973
 	// on se place tout le temps comme si on etait a la racine
974 974
 	if (_DIR_RACINE) {
975
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
975
+		$d = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $d);
976 976
 	}
977 977
 
978 978
 	$m = md5($source);
979 979
 
980 980
 	return $d
981
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
981
+	. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
982 982
 	. substr($m, 0, 4)
983 983
 	. ".$extension";
984 984
 }
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 	// Si c'est deja local pas de souci
1002 1002
 	if (!tester_url_absolue($source)) {
1003 1003
 		if (_DIR_RACINE) {
1004
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1004
+			$source = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $source);
1005 1005
 		}
1006 1006
 
1007 1007
 		return $source;
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 	if ($ext
1019 1019
 		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1020 1020
 		and $f = nom_fichier_copie_locale($source, $ext)
1021
-		and file_exists(_DIR_RACINE . $f)
1021
+		and file_exists(_DIR_RACINE.$f)
1022 1022
 	) {
1023 1023
 		return $f;
1024 1024
 	}
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
 
1027 1027
 	// Si c'est deja dans la table des documents,
1028 1028
 	// ramener le nom de sa copie potentielle
1029
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1029
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
1030 1030
 
1031 1031
 	if ($ext) {
1032 1032
 		return nom_fichier_copie_locale($source, $ext);
@@ -1037,9 +1037,9 @@  discard block
 block discarded – undo
1037 1037
 
1038 1038
 	$ext = $path_parts ? $path_parts['extension'] : '';
1039 1039
 
1040
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1040
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
1041 1041
 		$f = nom_fichier_copie_locale($source, $ext);
1042
-		if (file_exists(_DIR_RACINE . $f)) {
1042
+		if (file_exists(_DIR_RACINE.$f)) {
1043 1043
 			return $f;
1044 1044
 		}
1045 1045
 	}
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
 	// Ping  pour voir si son extension est connue et autorisee
1048 1048
 	// avec mise en cache du resultat du ping
1049 1049
 
1050
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1050
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
1051 1051
 	if (!@file_exists($cache)
1052 1052
 		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1053 1053
 		or _request('var_mode') == 'recalcul'
@@ -1056,10 +1056,10 @@  discard block
 block discarded – undo
1056 1056
 		ecrire_fichier($cache, serialize($path_parts));
1057 1057
 	}
1058 1058
 	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1059
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1059
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
1060 1060
 		return nom_fichier_copie_locale($source, $ext);
1061 1061
 	}
1062
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1062
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
1063 1063
 }
1064 1064
 
1065 1065
 
@@ -1124,19 +1124,19 @@  discard block
 block discarded – undo
1124 1124
 			if (!$t
1125 1125
 				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1126 1126
 			) {
1127
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1127
+				$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1128 1128
 			}
1129 1129
 			if (!$t
1130 1130
 				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1131 1131
 				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1132 1132
 			) {
1133
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1133
+				$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1134 1134
 			}
1135 1135
 		}
1136 1136
 
1137 1137
 		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1138 1138
 		if (!$t) {
1139
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1139
+			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1140 1140
 		}
1141 1141
 
1142 1142
 		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1146,11 +1146,11 @@  discard block
 block discarded – undo
1146 1146
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1147 1147
 		) {
1148 1148
 			# eviter xxx.3 => 3gp (> SPIP 3)
1149
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1149
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1150 1150
 		}
1151 1151
 
1152 1152
 		if ($t) {
1153
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1153
+			spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1154 1154
 			$a['extension'] = $t['extension'];
1155 1155
 		} else {
1156 1156
 			# par defaut on retombe sur '.bin' si c'est autorise
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
 		} else {
1193 1193
 			if ($a['body']) {
1194 1194
 				$a['extension'] = $extension;
1195
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1195
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1196 1196
 				ecrire_fichier($a['fichier'], $a['body']);
1197 1197
 				$size_image = @spip_getimagesize($a['fichier']);
1198 1198
 				$a['largeur'] = intval($size_image[0]);
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
 		}
1318 1318
 	} else {
1319 1319
 		$scheme = $t['scheme'];
1320
-		$noproxy = $scheme . '://';
1320
+		$noproxy = $scheme.'://';
1321 1321
 	}
1322 1322
 	if (isset($t['user'])) {
1323 1323
 		$user = array($t['user'], $t['pass']);
@@ -1331,7 +1331,7 @@  discard block
 block discarded – undo
1331 1331
 	}
1332 1332
 
1333 1333
 	if (!empty($t['query'])) {
1334
-		$path .= '?' . $t['query'];
1334
+		$path .= '?'.$t['query'];
1335 1335
 	}
1336 1336
 
1337 1337
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1404,20 +1404,20 @@  discard block
 block discarded – undo
1404 1404
 	$proxy_user = '';
1405 1405
 	$http_proxy = need_proxy($host);
1406 1406
 	if ($user) {
1407
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1407
+		$user = urlencode($user[0]).':'.urlencode($user[1]);
1408 1408
 	}
1409 1409
 
1410 1410
 	$connect = '';
1411 1411
 	if ($http_proxy) {
1412
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1413
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1414
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1412
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, array('tls', 'ssl'))) {
1413
+			$path_host = (!$user ? '' : "$user@").$host.(($port != 80) ? ":$port" : '');
1414
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1415 1415
 				. "Host: $path_host\r\n"
1416 1416
 				. "Proxy-Connection: Keep-Alive\r\n";
1417 1417
 		} else {
1418
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1418
+			$path = (in_array($scheme, array('tls', 'ssl')) ? 'https://' : "$scheme://")
1419 1419
 				. (!$user ? '' : "$user@")
1420
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1420
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1421 1421
 		}
1422 1422
 		$t2 = @parse_url($http_proxy);
1423 1423
 		$first_host = $t2['host'];
@@ -1425,10 +1425,10 @@  discard block
 block discarded – undo
1425 1425
 			$port = 80;
1426 1426
 		}
1427 1427
 		if ($t2['user']) {
1428
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1428
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1429 1429
 		}
1430 1430
 	} else {
1431
-		$first_host = $noproxy . $host;
1431
+		$first_host = $noproxy.$host;
1432 1432
 	}
1433 1433
 
1434 1434
 	if ($connect) {
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
 		);
1454 1454
 		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1455 1455
 		if (!$f) {
1456
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1456
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1457 1457
 			return $errno;
1458 1458
 		}
1459 1459
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
 			or !count($res = explode(' ', $res))
1466 1466
 			or $res[1] !== '200'
1467 1467
 		) {
1468
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1468
+			spip_log("Echec CONNECT sur $first_host:$port", 'connect'._LOG_INFO_IMPORTANTE);
1469 1469
 			fclose($f);
1470 1470
 
1471 1471
 			return false;
@@ -1482,7 +1482,7 @@  discard block
 block discarded – undo
1482 1482
 		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1483 1483
 		spip_log("Recuperer $path sur $first_host:$port par $f");
1484 1484
 		if (!$f) {
1485
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1485
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1486 1486
 
1487 1487
 			return $errno;
1488 1488
 		}
@@ -1492,16 +1492,16 @@  discard block
 block discarded – undo
1492 1492
 	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1493 1493
 
1494 1494
 	$host_port = $host;
1495
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1495
+	if ($port != (in_array($scheme, array('tls', 'ssl')) ? 443 : 80)) {
1496 1496
 		$host_port .= ":$port";
1497 1497
 	}
1498 1498
 	$req = "$method $path $vers\r\n"
1499 1499
 		. "Host: $host_port\r\n"
1500
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1501
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1500
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1501
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1502 1502
 		. (!$site ? '' : "Referer: $site/$referer\r\n")
1503
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1504
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1503
+		. (!$date ? '' : 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n"))
1504
+		. (!$user ? '' : ('Authorization: Basic '.base64_encode($user)."\r\n"))
1505 1505
 		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1506 1506
 		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1507 1507
 
Please login to merge, or discard this patch.
ecrire/inc/utils.php 2 patches
Indentation   +2224 added lines, -2225 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -48,63 +48,63 @@  discard block
 block discarded – undo
48 48
  *     Nom de la fonction, ou false.
49 49
  */
50 50
 function charger_fonction($nom, $dossier = 'exec', $continue = false) {
51
-	static $echecs = array();
52
-
53
-	if (strlen($dossier) and substr($dossier, -1) != '/') {
54
-		$dossier .= '/';
55
-	}
56
-	$f = str_replace('/', '_', $dossier) . $nom;
57
-
58
-	if (function_exists($f)) {
59
-		return $f;
60
-	}
61
-	if (function_exists($g = $f . '_dist')) {
62
-		return $g;
63
-	}
64
-
65
-	if (isset($echecs[$f])) {
66
-		return $echecs[$f];
67
-	}
68
-	// Sinon charger le fichier de declaration si plausible
69
-
70
-	if (!preg_match(',^\w+$,', $f)) {
71
-		if ($continue) {
72
-			return false;
73
-		} //appel interne, on passe
74
-		include_spip('inc/minipres');
75
-		echo minipres();
76
-		exit;
77
-	}
78
-
79
-	// passer en minuscules (cf les balises de formulaires)
80
-	// et inclure le fichier
81
-	if (!$inc = include_spip($dossier . ($d = strtolower($nom)))
82
-		// si le fichier truc/machin/nom.php n'existe pas,
83
-		// la fonction peut etre definie dans truc/machin.php qui regroupe plusieurs petites fonctions
84
-		and strlen(dirname($dossier)) and dirname($dossier) != '.'
85
-	) {
86
-		include_spip(substr($dossier, 0, -1));
87
-	}
88
-	if (function_exists($f)) {
89
-		return $f;
90
-	}
91
-	if (function_exists($g)) {
92
-		return $g;
93
-	}
94
-
95
-	if ($continue) {
96
-		return $echecs[$f] = false;
97
-	}
98
-
99
-	// Echec : message d'erreur
100
-	spip_log("fonction $nom ($f ou $g) indisponible" .
101
-		($inc ? "" : " (fichier $d absent de $dossier)"));
102
-
103
-	include_spip('inc/minipres');
104
-	echo minipres(_T('forum_titre_erreur'),
105
-		_T('fichier_introuvable', array('fichier' => '<b>' . spip_htmlentities($d) . '</b>')),
106
-		array('all_inline'=>true,'status'=>404));
107
-	exit;
51
+    static $echecs = array();
52
+
53
+    if (strlen($dossier) and substr($dossier, -1) != '/') {
54
+        $dossier .= '/';
55
+    }
56
+    $f = str_replace('/', '_', $dossier) . $nom;
57
+
58
+    if (function_exists($f)) {
59
+        return $f;
60
+    }
61
+    if (function_exists($g = $f . '_dist')) {
62
+        return $g;
63
+    }
64
+
65
+    if (isset($echecs[$f])) {
66
+        return $echecs[$f];
67
+    }
68
+    // Sinon charger le fichier de declaration si plausible
69
+
70
+    if (!preg_match(',^\w+$,', $f)) {
71
+        if ($continue) {
72
+            return false;
73
+        } //appel interne, on passe
74
+        include_spip('inc/minipres');
75
+        echo minipres();
76
+        exit;
77
+    }
78
+
79
+    // passer en minuscules (cf les balises de formulaires)
80
+    // et inclure le fichier
81
+    if (!$inc = include_spip($dossier . ($d = strtolower($nom)))
82
+        // si le fichier truc/machin/nom.php n'existe pas,
83
+        // la fonction peut etre definie dans truc/machin.php qui regroupe plusieurs petites fonctions
84
+        and strlen(dirname($dossier)) and dirname($dossier) != '.'
85
+    ) {
86
+        include_spip(substr($dossier, 0, -1));
87
+    }
88
+    if (function_exists($f)) {
89
+        return $f;
90
+    }
91
+    if (function_exists($g)) {
92
+        return $g;
93
+    }
94
+
95
+    if ($continue) {
96
+        return $echecs[$f] = false;
97
+    }
98
+
99
+    // Echec : message d'erreur
100
+    spip_log("fonction $nom ($f ou $g) indisponible" .
101
+        ($inc ? "" : " (fichier $d absent de $dossier)"));
102
+
103
+    include_spip('inc/minipres');
104
+    echo minipres(_T('forum_titre_erreur'),
105
+        _T('fichier_introuvable', array('fichier' => '<b>' . spip_htmlentities($d) . '</b>')),
106
+        array('all_inline'=>true,'status'=>404));
107
+    exit;
108 108
 }
109 109
 
110 110
 /**
@@ -114,17 +114,17 @@  discard block
 block discarded – undo
114 114
  * @return bool
115 115
  */
116 116
 function include_once_check($file) {
117
-	if (file_exists($file)) {
118
-		include_once $file;
117
+    if (file_exists($file)) {
118
+        include_once $file;
119 119
 
120
-		return true;
121
-	}
122
-	$crash = (isset($GLOBALS['meta']['message_crash_plugins']) ? unserialize($GLOBALS['meta']['message_crash_plugins']) : '');
123
-	$crash = ($crash ? $crash : array());
124
-	$crash[$file] = true;
125
-	ecrire_meta('message_crash_plugins', serialize($crash));
120
+        return true;
121
+    }
122
+    $crash = (isset($GLOBALS['meta']['message_crash_plugins']) ? unserialize($GLOBALS['meta']['message_crash_plugins']) : '');
123
+    $crash = ($crash ? $crash : array());
124
+    $crash[$file] = true;
125
+    ecrire_meta('message_crash_plugins', serialize($crash));
126 126
 
127
-	return false;
127
+    return false;
128 128
 }
129 129
 
130 130
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
  *     - string : chemin du fichier trouvé
149 149
  **/
150 150
 function include_spip($f, $include = true) {
151
-	return find_in_path($f . '.php', '', $include);
151
+    return find_in_path($f . '.php', '', $include);
152 152
 }
153 153
 
154 154
 /**
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
  *     - string : chemin du fichier trouvé
169 169
  **/
170 170
 function require_spip($f) {
171
-	return find_in_path($f . '.php', '', 'required');
171
+    return find_in_path($f . '.php', '', 'required');
172 172
 }
173 173
 
174 174
 /**
@@ -194,22 +194,22 @@  discard block
 block discarded – undo
194 194
  *     Les paramètres du pipeline modifiés
195 195
  **/
196 196
 function minipipe($fonc, &$val) {
197
-	// fonction
198
-	if (function_exists($fonc)) {
199
-		$val = call_user_func($fonc, $val);
200
-	} // Class::Methode
201
-	else {
202
-		if (preg_match("/^(\w*)::(\w*)$/S", $fonc, $regs)
203
-			and $methode = array($regs[1], $regs[2])
204
-			and is_callable($methode)
205
-		) {
206
-			$val = call_user_func($methode, $val);
207
-		} else {
208
-			spip_log("Erreur - '$fonc' non definie !");
209
-		}
210
-	}
197
+    // fonction
198
+    if (function_exists($fonc)) {
199
+        $val = call_user_func($fonc, $val);
200
+    } // Class::Methode
201
+    else {
202
+        if (preg_match("/^(\w*)::(\w*)$/S", $fonc, $regs)
203
+            and $methode = array($regs[1], $regs[2])
204
+            and is_callable($methode)
205
+        ) {
206
+            $val = call_user_func($methode, $val);
207
+        } else {
208
+            spip_log("Erreur - '$fonc' non definie !");
209
+        }
210
+    }
211 211
 
212
-	return $val;
212
+    return $val;
213 213
 }
214 214
 
215 215
 /**
@@ -240,45 +240,45 @@  discard block
 block discarded – undo
240 240
  *     Résultat
241 241
  */
242 242
 function pipeline($action, $val = null) {
243
-	static $charger;
244
-
245
-	// chargement initial des fonctions mises en cache, ou generation du cache
246
-	if (!$charger) {
247
-		if (!($ok = @is_readable($charger = _CACHE_PIPELINES))) {
248
-			include_spip('inc/plugin');
249
-			// generer les fichiers php precompiles
250
-			// de chargement des plugins et des pipelines
251
-			actualise_plugins_actifs();
252
-			if (!($ok = @is_readable($charger))) {
253
-				spip_log("fichier $charger pas cree");
254
-			}
255
-		}
256
-
257
-		if ($ok) {
258
-			include_once $charger;
259
-		}
260
-	}
261
-
262
-	// appliquer notre fonction si elle existe
263
-	$fonc = 'execute_pipeline_' . strtolower($action);
264
-	if (function_exists($fonc)) {
265
-		$val = $fonc($val);
266
-	} // plantage ?
267
-	else {
268
-		spip_log("fonction $fonc absente : pipeline desactive", _LOG_ERREUR);
269
-	}
270
-
271
-	// si le flux est une table avec 2 cle args&data
272
-	// on ne ressort du pipe que les donnees dans 'data'
273
-	// array_key_exists pour php 4.1.0
274
-	if (is_array($val)
275
-		and count($val) == 2
276
-		and (array_key_exists('data', $val))
277
-	) {
278
-		$val = $val['data'];
279
-	}
280
-
281
-	return $val;
243
+    static $charger;
244
+
245
+    // chargement initial des fonctions mises en cache, ou generation du cache
246
+    if (!$charger) {
247
+        if (!($ok = @is_readable($charger = _CACHE_PIPELINES))) {
248
+            include_spip('inc/plugin');
249
+            // generer les fichiers php precompiles
250
+            // de chargement des plugins et des pipelines
251
+            actualise_plugins_actifs();
252
+            if (!($ok = @is_readable($charger))) {
253
+                spip_log("fichier $charger pas cree");
254
+            }
255
+        }
256
+
257
+        if ($ok) {
258
+            include_once $charger;
259
+        }
260
+    }
261
+
262
+    // appliquer notre fonction si elle existe
263
+    $fonc = 'execute_pipeline_' . strtolower($action);
264
+    if (function_exists($fonc)) {
265
+        $val = $fonc($val);
266
+    } // plantage ?
267
+    else {
268
+        spip_log("fonction $fonc absente : pipeline desactive", _LOG_ERREUR);
269
+    }
270
+
271
+    // si le flux est une table avec 2 cle args&data
272
+    // on ne ressort du pipe que les donnees dans 'data'
273
+    // array_key_exists pour php 4.1.0
274
+    if (is_array($val)
275
+        and count($val) == 2
276
+        and (array_key_exists('data', $val))
277
+    ) {
278
+        $val = $val['data'];
279
+    }
280
+
281
+    return $val;
282 282
 }
283 283
 
284 284
 /**
@@ -322,35 +322,35 @@  discard block
 block discarded – undo
322 322
  *     paramètre est planté pour cause de compatibilité ascendante.
323 323
  */
324 324
 function spip_log($message = null, $name = null) {
325
-	static $pre = array();
326
-	static $log;
327
-	preg_match('/^([a-z_]*)\.?(\d)?$/iS', (string)$name, $regs);
328
-	if (!isset($regs[1]) or !$logname = $regs[1]) {
329
-		$logname = null;
330
-	}
331
-	if (!isset($regs[2]) or !$niveau = $regs[2]) {
332
-		$niveau = _LOG_INFO;
333
-	}
334
-
335
-	if ($niveau <= (defined('_LOG_FILTRE_GRAVITE') ? _LOG_FILTRE_GRAVITE : _LOG_INFO_IMPORTANTE)) {
336
-		if (!$pre) {
337
-			$pre = array(
338
-				_LOG_HS => 'HS:',
339
-				_LOG_ALERTE_ROUGE => 'ALERTE:',
340
-				_LOG_CRITIQUE => 'CRITIQUE:',
341
-				_LOG_ERREUR => 'ERREUR:',
342
-				_LOG_AVERTISSEMENT => 'WARNING:',
343
-				_LOG_INFO_IMPORTANTE => '!INFO:',
344
-				_LOG_INFO => 'info:',
345
-				_LOG_DEBUG => 'debug:'
346
-			);
347
-			$log = charger_fonction('log', 'inc');
348
-		}
349
-		if (!is_string($message)) {
350
-			$message = print_r($message, true);
351
-		}
352
-		$log($pre[$niveau] . ' ' . $message, $logname);
353
-	}
325
+    static $pre = array();
326
+    static $log;
327
+    preg_match('/^([a-z_]*)\.?(\d)?$/iS', (string)$name, $regs);
328
+    if (!isset($regs[1]) or !$logname = $regs[1]) {
329
+        $logname = null;
330
+    }
331
+    if (!isset($regs[2]) or !$niveau = $regs[2]) {
332
+        $niveau = _LOG_INFO;
333
+    }
334
+
335
+    if ($niveau <= (defined('_LOG_FILTRE_GRAVITE') ? _LOG_FILTRE_GRAVITE : _LOG_INFO_IMPORTANTE)) {
336
+        if (!$pre) {
337
+            $pre = array(
338
+                _LOG_HS => 'HS:',
339
+                _LOG_ALERTE_ROUGE => 'ALERTE:',
340
+                _LOG_CRITIQUE => 'CRITIQUE:',
341
+                _LOG_ERREUR => 'ERREUR:',
342
+                _LOG_AVERTISSEMENT => 'WARNING:',
343
+                _LOG_INFO_IMPORTANTE => '!INFO:',
344
+                _LOG_INFO => 'info:',
345
+                _LOG_DEBUG => 'debug:'
346
+            );
347
+            $log = charger_fonction('log', 'inc');
348
+        }
349
+        if (!is_string($message)) {
350
+            $message = print_r($message, true);
351
+        }
352
+        $log($pre[$niveau] . ' ' . $message, $logname);
353
+    }
354 354
 }
355 355
 
356 356
 /**
@@ -361,8 +361,8 @@  discard block
 block discarded – undo
361 361
  * @param array $opt Tableau d'options
362 362
  **/
363 363
 function journal($phrase, $opt = array()) {
364
-	$journal = charger_fonction('journal', 'inc');
365
-	$journal($phrase, $opt);
364
+    $journal = charger_fonction('journal', 'inc');
365
+    $journal($phrase, $opt);
366 366
 }
367 367
 
368 368
 
@@ -381,36 +381,36 @@  discard block
 block discarded – undo
381 381
  **/
382 382
 function _request($var, $c = false) {
383 383
 
384
-	if (is_array($c)) {
385
-		return isset($c[$var]) ? $c[$var] : null;
386
-	}
384
+    if (is_array($c)) {
385
+        return isset($c[$var]) ? $c[$var] : null;
386
+    }
387 387
 
388
-	if (isset($_GET[$var])) {
389
-		$a = $_GET[$var];
390
-	} elseif (isset($_POST[$var])) {
391
-		$a = $_POST[$var];
392
-	} else {
393
-		return null;
394
-	}
388
+    if (isset($_GET[$var])) {
389
+        $a = $_GET[$var];
390
+    } elseif (isset($_POST[$var])) {
391
+        $a = $_POST[$var];
392
+    } else {
393
+        return null;
394
+    }
395 395
 
396
-	// Si on est en ajax et en POST tout a ete encode
397
-	// via encodeURIComponent, il faut donc repasser
398
-	// dans le charset local...
399
-	if (defined('_AJAX')
400
-		and _AJAX
401
-		and isset($GLOBALS['meta']['charset'])
402
-		and $GLOBALS['meta']['charset'] != 'utf-8'
403
-		and is_string($a)
404
-		// check rapide mais pas fiable
405
-		and preg_match(',[\x80-\xFF],', $a)
406
-		// check fiable
407
-		and include_spip('inc/charsets')
408
-		and is_utf8($a)
409
-	) {
410
-		return importer_charset($a, 'utf-8');
411
-	}
396
+    // Si on est en ajax et en POST tout a ete encode
397
+    // via encodeURIComponent, il faut donc repasser
398
+    // dans le charset local...
399
+    if (defined('_AJAX')
400
+        and _AJAX
401
+        and isset($GLOBALS['meta']['charset'])
402
+        and $GLOBALS['meta']['charset'] != 'utf-8'
403
+        and is_string($a)
404
+        // check rapide mais pas fiable
405
+        and preg_match(',[\x80-\xFF],', $a)
406
+        // check fiable
407
+        and include_spip('inc/charsets')
408
+        and is_utf8($a)
409
+    ) {
410
+        return importer_charset($a, 'utf-8');
411
+    }
412 412
 
413
-	return $a;
413
+    return $a;
414 414
 }
415 415
 
416 416
 
@@ -428,22 +428,22 @@  discard block
 block discarded – undo
428 428
  *     - false sinon
429 429
  **/
430 430
 function set_request($var, $val = null, $c = false) {
431
-	if (is_array($c)) {
432
-		unset($c[$var]);
433
-		if ($val !== null) {
434
-			$c[$var] = $val;
435
-		}
431
+    if (is_array($c)) {
432
+        unset($c[$var]);
433
+        if ($val !== null) {
434
+            $c[$var] = $val;
435
+        }
436 436
 
437
-		return $c;
438
-	}
437
+        return $c;
438
+    }
439 439
 
440
-	unset($_GET[$var]);
441
-	unset($_POST[$var]);
442
-	if ($val !== null) {
443
-		$_GET[$var] = $val;
444
-	}
440
+    unset($_GET[$var]);
441
+    unset($_POST[$var]);
442
+    if ($val !== null) {
443
+        $_GET[$var] = $val;
444
+    }
445 445
 
446
-	return false; # n'affecte pas $c
446
+    return false; # n'affecte pas $c
447 447
 }
448 448
 
449 449
 /**
@@ -463,25 +463,25 @@  discard block
 block discarded – undo
463 463
  * @return array|mixed|string
464 464
  */
465 465
 function spip_sanitize_from_request($value, $key, $sanitize_function='entites_html') {
466
-	if (is_array($value)) {
467
-		if ($key=='*') {
468
-			$key = array_keys($value);
469
-		}
470
-		if (!is_array($key)) {
471
-			$key = [$key];
472
-		}
473
-		foreach ($key as $k) {
474
-			if (!empty($value[$k])) {
475
-				$value[$k] = spip_sanitize_from_request($value[$k], $k, $sanitize_function);
476
-			}
477
-		}
478
-		return $value;
479
-	}
480
-	// si la valeur vient des GET ou POST on la sanitize
481
-	if (!empty($value) and $value == _request($key)) {
482
-		$value = $sanitize_function($value);
483
-	}
484
-	return $value;
466
+    if (is_array($value)) {
467
+        if ($key=='*') {
468
+            $key = array_keys($value);
469
+        }
470
+        if (!is_array($key)) {
471
+            $key = [$key];
472
+        }
473
+        foreach ($key as $k) {
474
+            if (!empty($value[$k])) {
475
+                $value[$k] = spip_sanitize_from_request($value[$k], $k, $sanitize_function);
476
+            }
477
+        }
478
+        return $value;
479
+    }
480
+    // si la valeur vient des GET ou POST on la sanitize
481
+    if (!empty($value) and $value == _request($key)) {
482
+        $value = $sanitize_function($value);
483
+    }
484
+    return $value;
485 485
 }
486 486
 
487 487
 /**
@@ -489,23 +489,22 @@  discard block
 block discarded – undo
489 489
  * 
490 490
  * On est sur le web, on exclut certains protocoles, 
491 491
  * notamment 'file://', 'php://' et d'autres…
492
-
493 492
  * @param string $url
494 493
  * @return bool
495 494
  */
496 495
 function tester_url_absolue($url) {
497
-	$url = trim($url);
498
-	if (preg_match(";^([a-z]{3,7}:)?//;Uims", $url, $m)) {
499
-		if (
500
-			isset($m[1])
501
-			and $p = strtolower(rtrim($m[1], ':'))
502
-			and in_array($p, array('file', 'php', 'zlib', 'glob', 'phar', 'ssh2', 'rar', 'ogg', 'expect', 'zip'))
503
-		  ) {
504
-			return false;
505
-		}
506
-		return true;
507
-	}
508
-	return false;
496
+    $url = trim($url);
497
+    if (preg_match(";^([a-z]{3,7}:)?//;Uims", $url, $m)) {
498
+        if (
499
+            isset($m[1])
500
+            and $p = strtolower(rtrim($m[1], ':'))
501
+            and in_array($p, array('file', 'php', 'zlib', 'glob', 'phar', 'ssh2', 'rar', 'ogg', 'expect', 'zip'))
502
+            ) {
503
+            return false;
504
+        }
505
+        return true;
506
+    }
507
+    return false;
509 508
 }
510 509
 
511 510
 /**
@@ -527,94 +526,94 @@  discard block
 block discarded – undo
527 526
  * @return string URL
528 527
  */
529 528
 function parametre_url($url, $c, $v = null, $sep = '&amp;') {
530
-	// requete erronnee : plusieurs variable dans $c et aucun $v
531
-	if (strpos($c, "|") !== false and is_null($v)) {
532
-		return null;
533
-	}
534
-
535
-	// lever l'#ancre
536
-	if (preg_match(',^([^#]*)(#.*)$,', $url, $r)) {
537
-		$url = $r[1];
538
-		$ancre = $r[2];
539
-	} else {
540
-		$ancre = '';
541
-	}
542
-
543
-	// eclater
544
-	$url = preg_split(',[?]|&amp;|&,', $url);
545
-
546
-	// recuperer la base
547
-	$a = array_shift($url);
548
-	if (!$a) {
549
-		$a = './';
550
-	}
551
-
552
-	$regexp = ',^(' . str_replace('[]', '\[\]', $c) . '[[]?[]]?)(=.*)?$,';
553
-	$ajouts = array_flip(explode('|', $c));
554
-	$u = is_array($v) ? $v : rawurlencode($v);
555
-	$testv = (is_array($v) ? count($v) : strlen($v));
556
-	$v_read = null;
557
-	// lire les variables et agir
558
-	foreach ($url as $n => $val) {
559
-		if (preg_match($regexp, urldecode($val), $r)) {
560
-			$r = array_pad($r, 3, null);
561
-			if ($v === null) {
562
-				// c'est un tableau, on memorise les valeurs
563
-				if (substr($r[1], -2) == "[]") {
564
-					if (!$v_read) {
565
-						$v_read = array();
566
-					}
567
-					$v_read[] = $r[2] ? substr($r[2], 1) : '';
568
-				} // c'est un scalaire, on retourne direct
569
-				else {
570
-					return $r[2] ? substr($r[2], 1) : '';
571
-				}
572
-			} // suppression
573
-			elseif (!$testv) {
574
-				unset($url[$n]);
575
-			}
576
-			// Ajout. Pour une variable, remplacer au meme endroit,
577
-			// pour un tableau ce sera fait dans la prochaine boucle
578
-			elseif (substr($r[1], -2) != '[]') {
579
-				$url[$n] = $r[1] . '=' . $u;
580
-				unset($ajouts[$r[1]]);
581
-			}
582
-			// Pour les tableaux on laisse tomber les valeurs de
583
-			// départ, on remplira à l'étape suivante
584
-			else {
585
-				unset($url[$n]);
586
-			}
587
-		}
588
-	}
589
-
590
-	// traiter les parametres pas encore trouves
591
-	if ($v === null
592
-		and $args = func_get_args()
593
-		and count($args) == 2
594
-	) {
595
-		return $v_read; // rien trouve ou un tableau
596
-	} elseif ($testv) {
597
-		foreach ($ajouts as $k => $n) {
598
-			if (!is_array($v)) {
599
-				$url[] = $k . '=' . $u;
600
-			} else {
601
-				$id = (substr($k, -2) == '[]') ? $k : ($k . "[]");
602
-				foreach ($v as $w) {
603
-					$url[] = $id . '=' . (is_array($w) ? 'Array' : $w);
604
-				}
605
-			}
606
-		}
607
-	}
608
-
609
-	// eliminer les vides
610
-	$url = array_filter($url);
611
-
612
-	// recomposer l'adresse
613
-	if ($url) {
614
-		$a .= '?' . join($sep, $url);
615
-	}
616
-
617
-	return $a . $ancre;
529
+    // requete erronnee : plusieurs variable dans $c et aucun $v
530
+    if (strpos($c, "|") !== false and is_null($v)) {
531
+        return null;
532
+    }
533
+
534
+    // lever l'#ancre
535
+    if (preg_match(',^([^#]*)(#.*)$,', $url, $r)) {
536
+        $url = $r[1];
537
+        $ancre = $r[2];
538
+    } else {
539
+        $ancre = '';
540
+    }
541
+
542
+    // eclater
543
+    $url = preg_split(',[?]|&amp;|&,', $url);
544
+
545
+    // recuperer la base
546
+    $a = array_shift($url);
547
+    if (!$a) {
548
+        $a = './';
549
+    }
550
+
551
+    $regexp = ',^(' . str_replace('[]', '\[\]', $c) . '[[]?[]]?)(=.*)?$,';
552
+    $ajouts = array_flip(explode('|', $c));
553
+    $u = is_array($v) ? $v : rawurlencode($v);
554
+    $testv = (is_array($v) ? count($v) : strlen($v));
555
+    $v_read = null;
556
+    // lire les variables et agir
557
+    foreach ($url as $n => $val) {
558
+        if (preg_match($regexp, urldecode($val), $r)) {
559
+            $r = array_pad($r, 3, null);
560
+            if ($v === null) {
561
+                // c'est un tableau, on memorise les valeurs
562
+                if (substr($r[1], -2) == "[]") {
563
+                    if (!$v_read) {
564
+                        $v_read = array();
565
+                    }
566
+                    $v_read[] = $r[2] ? substr($r[2], 1) : '';
567
+                } // c'est un scalaire, on retourne direct
568
+                else {
569
+                    return $r[2] ? substr($r[2], 1) : '';
570
+                }
571
+            } // suppression
572
+            elseif (!$testv) {
573
+                unset($url[$n]);
574
+            }
575
+            // Ajout. Pour une variable, remplacer au meme endroit,
576
+            // pour un tableau ce sera fait dans la prochaine boucle
577
+            elseif (substr($r[1], -2) != '[]') {
578
+                $url[$n] = $r[1] . '=' . $u;
579
+                unset($ajouts[$r[1]]);
580
+            }
581
+            // Pour les tableaux on laisse tomber les valeurs de
582
+            // départ, on remplira à l'étape suivante
583
+            else {
584
+                unset($url[$n]);
585
+            }
586
+        }
587
+    }
588
+
589
+    // traiter les parametres pas encore trouves
590
+    if ($v === null
591
+        and $args = func_get_args()
592
+        and count($args) == 2
593
+    ) {
594
+        return $v_read; // rien trouve ou un tableau
595
+    } elseif ($testv) {
596
+        foreach ($ajouts as $k => $n) {
597
+            if (!is_array($v)) {
598
+                $url[] = $k . '=' . $u;
599
+            } else {
600
+                $id = (substr($k, -2) == '[]') ? $k : ($k . "[]");
601
+                foreach ($v as $w) {
602
+                    $url[] = $id . '=' . (is_array($w) ? 'Array' : $w);
603
+                }
604
+            }
605
+        }
606
+    }
607
+
608
+    // eliminer les vides
609
+    $url = array_filter($url);
610
+
611
+    // recomposer l'adresse
612
+    if ($url) {
613
+        $a .= '?' . join($sep, $url);
614
+    }
615
+
616
+    return $a . $ancre;
618 617
 }
619 618
 
620 619
 /**
@@ -632,21 +631,21 @@  discard block
 block discarded – undo
632 631
  * @return string
633 632
  */
634 633
 function ancre_url($url, $ancre) {
635
-	// lever l'#ancre
636
-	if (preg_match(',^([^#]*)(#.*)$,', $url, $r)) {
637
-		$url = $r[1];
638
-	}
639
-	if (preg_match('/[^-_a-zA-Z0-9]+/S', $ancre)) {
640
-		if (!function_exists('translitteration')) {
641
-			include_spip('inc/charsets');
642
-		}
643
-		$ancre = preg_replace(
644
-			array('/^[^-_a-zA-Z0-9]+/', '/[^-_a-zA-Z0-9]/'),
645
-			array('', '-'),
646
-			translitteration($ancre)
647
-		);
648
-	}
649
-	return $url . (strlen($ancre) ? '#' . $ancre : '');
634
+    // lever l'#ancre
635
+    if (preg_match(',^([^#]*)(#.*)$,', $url, $r)) {
636
+        $url = $r[1];
637
+    }
638
+    if (preg_match('/[^-_a-zA-Z0-9]+/S', $ancre)) {
639
+        if (!function_exists('translitteration')) {
640
+            include_spip('inc/charsets');
641
+        }
642
+        $ancre = preg_replace(
643
+            array('/^[^-_a-zA-Z0-9]+/', '/[^-_a-zA-Z0-9]/'),
644
+            array('', '-'),
645
+            translitteration($ancre)
646
+        );
647
+    }
648
+    return $url . (strlen($ancre) ? '#' . $ancre : '');
650 649
 }
651 650
 
652 651
 /**
@@ -656,16 +655,16 @@  discard block
 block discarded – undo
656 655
  * @return string
657 656
  */
658 657
 function nettoyer_uri($reset = null) {
659
-	static $done = false;
660
-	static $propre = '';
661
-	if (!is_null($reset)) {
662
-		return $propre = $reset;
663
-	}
664
-	if ($done) {
665
-		return $propre;
666
-	}
667
-	$done = true;
668
-	return $propre = nettoyer_uri_var($GLOBALS['REQUEST_URI']);
658
+    static $done = false;
659
+    static $propre = '';
660
+    if (!is_null($reset)) {
661
+        return $propre = $reset;
662
+    }
663
+    if ($done) {
664
+        return $propre;
665
+    }
666
+    $done = true;
667
+    return $propre = nettoyer_uri_var($GLOBALS['REQUEST_URI']);
669 668
 }
670 669
 
671 670
 /**
@@ -677,13 +676,13 @@  discard block
 block discarded – undo
677 676
  * @return string
678 677
  */
679 678
 function nettoyer_uri_var($request_uri) {
680
-	$uri1 = $request_uri;
681
-	do {
682
-		$uri = $uri1;
683
-		$uri1 = preg_replace(',([?&])(var_[^=&]*|PHPSESSID|fbclid|utm_[^=&]*)=[^&]*(&|$),i',
684
-			'\1', $uri);
685
-	} while ($uri <> $uri1);
686
-	return preg_replace(',[?&]$,', '', $uri1);
679
+    $uri1 = $request_uri;
680
+    do {
681
+        $uri = $uri1;
682
+        $uri1 = preg_replace(',([?&])(var_[^=&]*|PHPSESSID|fbclid|utm_[^=&]*)=[^&]*(&|$),i',
683
+            '\1', $uri);
684
+    } while ($uri <> $uri1);
685
+    return preg_replace(',[?&]$,', '', $uri1);
687 686
 }
688 687
 
689 688
 
@@ -697,47 +696,47 @@  discard block
 block discarded – undo
697 696
  *    URL vers soi-même
698 697
  **/
699 698
 function self($amp = '&amp;', $root = false) {
700
-	$url = nettoyer_uri();
701
-	if (!$root
702
-		and (
703
-			// si pas de profondeur on peut tronquer
704
-			$GLOBALS['profondeur_url'] < (_DIR_RESTREINT ? 1 : 2)
705
-			// sinon c'est OK si _SET_HTML_BASE a ete force a false
706
-			or (defined('_SET_HTML_BASE') and !_SET_HTML_BASE))
707
-	) {
708
-		$url = preg_replace(',^[^?]*/,', '', $url);
709
-	}
710
-	// ajouter le cas echeant les variables _POST['id_...']
711
-	foreach ($_POST as $v => $c) {
712
-		if (substr($v, 0, 3) == 'id_') {
713
-			$url = parametre_url($url, $v, $c, '&');
714
-		}
715
-	}
716
-
717
-	// supprimer les variables sans interet
718
-	if (test_espace_prive()) {
719
-		$url = preg_replace(',([?&])('
720
-			. 'lang|show_docs|'
721
-			. 'changer_lang|var_lang|action)=[^&]*,i', '\1', $url);
722
-		$url = preg_replace(',([?&])[&]+,', '\1', $url);
723
-		$url = preg_replace(',[&]$,', '\1', $url);
724
-	}
725
-
726
-	// eviter les hacks
727
-	include_spip('inc/filtres_mini');
728
-	$url = spip_htmlspecialchars($url);
699
+    $url = nettoyer_uri();
700
+    if (!$root
701
+        and (
702
+            // si pas de profondeur on peut tronquer
703
+            $GLOBALS['profondeur_url'] < (_DIR_RESTREINT ? 1 : 2)
704
+            // sinon c'est OK si _SET_HTML_BASE a ete force a false
705
+            or (defined('_SET_HTML_BASE') and !_SET_HTML_BASE))
706
+    ) {
707
+        $url = preg_replace(',^[^?]*/,', '', $url);
708
+    }
709
+    // ajouter le cas echeant les variables _POST['id_...']
710
+    foreach ($_POST as $v => $c) {
711
+        if (substr($v, 0, 3) == 'id_') {
712
+            $url = parametre_url($url, $v, $c, '&');
713
+        }
714
+    }
715
+
716
+    // supprimer les variables sans interet
717
+    if (test_espace_prive()) {
718
+        $url = preg_replace(',([?&])('
719
+            . 'lang|show_docs|'
720
+            . 'changer_lang|var_lang|action)=[^&]*,i', '\1', $url);
721
+        $url = preg_replace(',([?&])[&]+,', '\1', $url);
722
+        $url = preg_replace(',[&]$,', '\1', $url);
723
+    }
724
+
725
+    // eviter les hacks
726
+    include_spip('inc/filtres_mini');
727
+    $url = spip_htmlspecialchars($url);
729 728
 	
730
-	$url = str_replace(array("'", '"', '<', '[', ']', ':'), array('%27', '%22', '%3C', '%5B', '%5D', '%3A'), $url);
729
+    $url = str_replace(array("'", '"', '<', '[', ']', ':'), array('%27', '%22', '%3C', '%5B', '%5D', '%3A'), $url);
731 730
 
732
-	// &amp; ?
733
-	if ($amp != '&amp;') {
734
-		$url = str_replace('&amp;', $amp, $url);
735
-	}
731
+    // &amp; ?
732
+    if ($amp != '&amp;') {
733
+        $url = str_replace('&amp;', $amp, $url);
734
+    }
736 735
 
737
-	// Si ca demarre par ? ou vide, donner './'
738
-	$url = preg_replace(',^([?].*)?$,', './\1', $url);
736
+    // Si ca demarre par ? ou vide, donner './'
737
+    $url = preg_replace(',^([?].*)?$,', './\1', $url);
739 738
 
740
-	return $url;
739
+    return $url;
741 740
 }
742 741
 
743 742
 
@@ -748,7 +747,7 @@  discard block
 block discarded – undo
748 747
  *     true si c'est le cas, false sinon.
749 748
  */
750 749
 function test_espace_prive() {
751
-	return defined('_ESPACE_PRIVE') ? _ESPACE_PRIVE : false;
750
+    return defined('_ESPACE_PRIVE') ? _ESPACE_PRIVE : false;
752 751
 }
753 752
 
754 753
 /**
@@ -758,7 +757,7 @@  discard block
 block discarded – undo
758 757
  * @return bool
759 758
  */
760 759
 function test_plugin_actif($plugin) {
761
-	return ($plugin and defined('_DIR_PLUGIN_' . strtoupper($plugin))) ? true : false;
760
+    return ($plugin and defined('_DIR_PLUGIN_' . strtoupper($plugin))) ? true : false;
762 761
 }
763 762
 
764 763
 /**
@@ -789,51 +788,51 @@  discard block
 block discarded – undo
789 788
  *     Texte
790 789
  */
791 790
 function _T($texte, $args = array(), $options = array()) {
792
-	static $traduire = false;
793
-	$o = array('class' => '', 'force' => true, 'sanitize' => true);
794
-	if ($options) {
795
-		// support de l'ancien argument $class
796
-		if (is_string($options)) {
797
-			$options = array('class' => $options);
798
-		}
799
-		$o = array_merge($o, $options);
800
-	}
791
+    static $traduire = false;
792
+    $o = array('class' => '', 'force' => true, 'sanitize' => true);
793
+    if ($options) {
794
+        // support de l'ancien argument $class
795
+        if (is_string($options)) {
796
+            $options = array('class' => $options);
797
+        }
798
+        $o = array_merge($o, $options);
799
+    }
801 800
 
802
-	if (!$traduire) {
803
-		$traduire = charger_fonction('traduire', 'inc');
804
-		include_spip('inc/lang');
805
-	}
801
+    if (!$traduire) {
802
+        $traduire = charger_fonction('traduire', 'inc');
803
+        include_spip('inc/lang');
804
+    }
806 805
 
807
-	// On peut passer explicitement la langue dans le tableau
808
-	// On utilise le même nom de variable que la globale
809
-	if (isset($args['spip_lang'])) {
810
-		$lang = $args['spip_lang'];
811
-		// On l'enleve pour ne pas le passer au remplacement
812
-		unset($args['spip_lang']);
813
-	} // Sinon on prend la langue du contexte
814
-	else {
815
-		$lang = $GLOBALS['spip_lang'];
816
-	}
817
-	$text = $traduire($texte, $lang);
806
+    // On peut passer explicitement la langue dans le tableau
807
+    // On utilise le même nom de variable que la globale
808
+    if (isset($args['spip_lang'])) {
809
+        $lang = $args['spip_lang'];
810
+        // On l'enleve pour ne pas le passer au remplacement
811
+        unset($args['spip_lang']);
812
+    } // Sinon on prend la langue du contexte
813
+    else {
814
+        $lang = $GLOBALS['spip_lang'];
815
+    }
816
+    $text = $traduire($texte, $lang);
818 817
 
819
-	if (!strlen($text)) {
820
-		if (!$o['force']) {
821
-			return '';
822
-		}
818
+    if (!strlen($text)) {
819
+        if (!$o['force']) {
820
+            return '';
821
+        }
823 822
 
824
-		$text = $texte;
823
+        $text = $texte;
825 824
 
826
-		// pour les chaines non traduites, assurer un service minimum
827
-		if (!$GLOBALS['test_i18n'] and (_request('var_mode') != 'traduction')) {
828
-			$text = str_replace('_', ' ',
829
-				(($n = strpos($text, ':')) === false ? $texte :
830
-					substr($texte, $n + 1)));
831
-		}
832
-		$o['class'] = null;
825
+        // pour les chaines non traduites, assurer un service minimum
826
+        if (!$GLOBALS['test_i18n'] and (_request('var_mode') != 'traduction')) {
827
+            $text = str_replace('_', ' ',
828
+                (($n = strpos($text, ':')) === false ? $texte :
829
+                    substr($texte, $n + 1)));
830
+        }
831
+        $o['class'] = null;
833 832
 
834
-	}
833
+    }
835 834
 
836
-	return _L($text, $args, $o);
835
+    return _L($text, $args, $o);
837 836
 
838 837
 }
839 838
 
@@ -861,53 +860,53 @@  discard block
 block discarded – undo
861 860
  *     Texte
862 861
  */
863 862
 function _L($text, $args = array(), $options = array()) {
864
-	$f = $text;
865
-	$defaut_options = array(
866
-		'class' => null,
867
-		'sanitize' => true,
868
-	);
869
-	// support de l'ancien argument $class
870
-	if ($options and is_string($options)) {
871
-		$options = array('class' => $options);
872
-	}
873
-	if (is_array($options)) {
874
-		$options += $defaut_options;
875
-	} else {
876
-		$options = $defaut_options;
877
-	}
878
-
879
-	if (is_array($args) and count($args)) {
880
-		if (!function_exists('interdire_scripts')) {
881
-			include_spip('inc/texte');
882
-		}
883
-		if (!function_exists('echapper_html_suspect')) {
884
-			include_spip('inc/texte_mini');
885
-		}
886
-		foreach ($args as $name => $value) {
887
-			if (strpos($text, "@$name@") !== false) {
888
-				if ($options['sanitize']) {
889
-					$value = echapper_html_suspect($value);
890
-					$value = interdire_scripts($value, -1);
891
-				}
892
-				if (!empty($options['class'])) {
893
-					$value = "<span class='".$options['class']."'>$value</span>";
894
-				}
895
-				$text = str_replace("@$name@", $value, $text);
896
-				unset($args[$name]);
897
-			}
898
-		}
899
-		// Si des variables n'ont pas ete inserees, le signaler
900
-		// (chaines de langues pas a jour)
901
-		if ($args) {
902
-			spip_log("$f:  variables inutilisees " . join(', ', array_keys($args)), _LOG_DEBUG);
903
-		}
904
-	}
905
-
906
-	if (($GLOBALS['test_i18n'] or (_request('var_mode') == 'traduction')) and is_null($options['class'])) {
907
-		return "<span class=debug-traduction-erreur>$text</span>";
908
-	} else {
909
-		return $text;
910
-	}
863
+    $f = $text;
864
+    $defaut_options = array(
865
+        'class' => null,
866
+        'sanitize' => true,
867
+    );
868
+    // support de l'ancien argument $class
869
+    if ($options and is_string($options)) {
870
+        $options = array('class' => $options);
871
+    }
872
+    if (is_array($options)) {
873
+        $options += $defaut_options;
874
+    } else {
875
+        $options = $defaut_options;
876
+    }
877
+
878
+    if (is_array($args) and count($args)) {
879
+        if (!function_exists('interdire_scripts')) {
880
+            include_spip('inc/texte');
881
+        }
882
+        if (!function_exists('echapper_html_suspect')) {
883
+            include_spip('inc/texte_mini');
884
+        }
885
+        foreach ($args as $name => $value) {
886
+            if (strpos($text, "@$name@") !== false) {
887
+                if ($options['sanitize']) {
888
+                    $value = echapper_html_suspect($value);
889
+                    $value = interdire_scripts($value, -1);
890
+                }
891
+                if (!empty($options['class'])) {
892
+                    $value = "<span class='".$options['class']."'>$value</span>";
893
+                }
894
+                $text = str_replace("@$name@", $value, $text);
895
+                unset($args[$name]);
896
+            }
897
+        }
898
+        // Si des variables n'ont pas ete inserees, le signaler
899
+        // (chaines de langues pas a jour)
900
+        if ($args) {
901
+            spip_log("$f:  variables inutilisees " . join(', ', array_keys($args)), _LOG_DEBUG);
902
+        }
903
+    }
904
+
905
+    if (($GLOBALS['test_i18n'] or (_request('var_mode') == 'traduction')) and is_null($options['class'])) {
906
+        return "<span class=debug-traduction-erreur>$text</span>";
907
+    } else {
908
+        return $text;
909
+    }
911 910
 }
912 911
 
913 912
 
@@ -921,13 +920,13 @@  discard block
 block discarded – undo
921 920
  * @return string
922 921
  */
923 922
 function joli_repertoire($rep) {
924
-	$a = substr($rep, 0, 1);
925
-	if ($a <> '.' and $a <> '/') {
926
-		$rep = (_DIR_RESTREINT ? '' : _DIR_RESTREINT_ABS) . $rep;
927
-	}
928
-	$rep = preg_replace(',(^\.\.\/),', '', $rep);
923
+    $a = substr($rep, 0, 1);
924
+    if ($a <> '.' and $a <> '/') {
925
+        $rep = (_DIR_RESTREINT ? '' : _DIR_RESTREINT_ABS) . $rep;
926
+    }
927
+    $rep = preg_replace(',(^\.\.\/),', '', $rep);
929 928
 
930
-	return $rep;
929
+    return $rep;
931 930
 }
932 931
 
933 932
 
@@ -952,33 +951,33 @@  discard block
 block discarded – undo
952 951
  * @return float|int|string|void
953 952
  */
954 953
 function spip_timer($t = 'rien', $raw = false) {
955
-	static $time;
956
-	$a = time();
957
-	$b = microtime();
958
-	// microtime peut contenir les microsecondes et le temps
959
-	$b = explode(' ', $b);
960
-	if (count($b) == 2) {
961
-		$a = end($b);
962
-	} // plus precis !
963
-	$b = reset($b);
964
-	if (!isset($time[$t])) {
965
-		$time[$t] = $a + $b;
966
-	} else {
967
-		$p = ($a + $b - $time[$t]) * 1000;
968
-		unset($time[$t]);
954
+    static $time;
955
+    $a = time();
956
+    $b = microtime();
957
+    // microtime peut contenir les microsecondes et le temps
958
+    $b = explode(' ', $b);
959
+    if (count($b) == 2) {
960
+        $a = end($b);
961
+    } // plus precis !
962
+    $b = reset($b);
963
+    if (!isset($time[$t])) {
964
+        $time[$t] = $a + $b;
965
+    } else {
966
+        $p = ($a + $b - $time[$t]) * 1000;
967
+        unset($time[$t]);
969 968
 #			echo "'$p'";exit;
970
-		if ($raw) {
971
-			return $p;
972
-		}
973
-		if ($p < 1000) {
974
-			$s = '';
975
-		} else {
976
-			$s = sprintf("%d ", $x = floor($p / 1000));
977
-			$p -= ($x * 1000);
978
-		}
969
+        if ($raw) {
970
+            return $p;
971
+        }
972
+        if ($p < 1000) {
973
+            $s = '';
974
+        } else {
975
+            $s = sprintf("%d ", $x = floor($p / 1000));
976
+            $p -= ($x * 1000);
977
+        }
979 978
 
980
-		return $s . sprintf($s ? "%07.3f ms" : "%.3f ms", $p);
981
-	}
979
+        return $s . sprintf($s ? "%07.3f ms" : "%.3f ms", $p);
980
+    }
982 981
 }
983 982
 
984 983
 
@@ -986,21 +985,21 @@  discard block
 block discarded – undo
986 985
 // sinon renvoie True et le date sauf si ca n'est pas souhaite
987 986
 // https://code.spip.net/@spip_touch
988 987
 function spip_touch($fichier, $duree = 0, $touch = true) {
989
-	if ($duree) {
990
-		clearstatcache();
991
-		if ((@$f = filemtime($fichier)) and ($f >= time() - $duree)) {
992
-			return false;
993
-		}
994
-	}
995
-	if ($touch !== false) {
996
-		if (!@touch($fichier)) {
997
-			spip_unlink($fichier);
998
-			@touch($fichier);
999
-		};
1000
-		@chmod($fichier, _SPIP_CHMOD & ~0111);
1001
-	}
988
+    if ($duree) {
989
+        clearstatcache();
990
+        if ((@$f = filemtime($fichier)) and ($f >= time() - $duree)) {
991
+            return false;
992
+        }
993
+    }
994
+    if ($touch !== false) {
995
+        if (!@touch($fichier)) {
996
+            spip_unlink($fichier);
997
+            @touch($fichier);
998
+        };
999
+        @chmod($fichier, _SPIP_CHMOD & ~0111);
1000
+    }
1002 1001
 
1003
-	return true;
1002
+    return true;
1004 1003
 }
1005 1004
 
1006 1005
 
@@ -1012,11 +1011,11 @@  discard block
 block discarded – undo
1012 1011
  * @uses cron()
1013 1012
  **/
1014 1013
 function action_cron() {
1015
-	include_spip('inc/headers');
1016
-	http_status(204); // No Content
1017
-	header("Connection: close");
1018
-	define('_DIRECT_CRON_FORCE', true);
1019
-	cron();
1014
+    include_spip('inc/headers');
1015
+    http_status(204); // No Content
1016
+    header("Connection: close");
1017
+    define('_DIRECT_CRON_FORCE', true);
1018
+    cron();
1020 1019
 }
1021 1020
 
1022 1021
 /**
@@ -1032,26 +1031,26 @@  discard block
 block discarded – undo
1032 1031
  *     True si la tache a pu être effectuée
1033 1032
  */
1034 1033
 function cron($taches = array(), $taches_old = array()) {
1035
-	// si pas en mode cron force, laisser tomber.
1036
-	if (!defined('_DIRECT_CRON_FORCE')) {
1037
-		return false;
1038
-	}
1039
-	if (!is_array($taches)) {
1040
-		$taches = $taches_old;
1041
-	} // compat anciens appels
1042
-	// si taches a inserer en base et base inaccessible, laisser tomber
1043
-	// sinon on ne verifie pas la connexion tout de suite, car si ca se trouve
1044
-	// queue_sleep_time_to_next_job() dira qu'il n'y a rien a faire
1045
-	// et on evite d'ouvrir une connexion pour rien (utilisation de _DIRECT_CRON_FORCE dans mes_options.php)
1046
-	if ($taches and count($taches) and !spip_connect()) {
1047
-		return false;
1048
-	}
1049
-	spip_log("cron !", 'jq' . _LOG_DEBUG);
1050
-	if ($genie = charger_fonction('genie', 'inc', true)) {
1051
-		return $genie($taches);
1052
-	}
1053
-
1054
-	return false;
1034
+    // si pas en mode cron force, laisser tomber.
1035
+    if (!defined('_DIRECT_CRON_FORCE')) {
1036
+        return false;
1037
+    }
1038
+    if (!is_array($taches)) {
1039
+        $taches = $taches_old;
1040
+    } // compat anciens appels
1041
+    // si taches a inserer en base et base inaccessible, laisser tomber
1042
+    // sinon on ne verifie pas la connexion tout de suite, car si ca se trouve
1043
+    // queue_sleep_time_to_next_job() dira qu'il n'y a rien a faire
1044
+    // et on evite d'ouvrir une connexion pour rien (utilisation de _DIRECT_CRON_FORCE dans mes_options.php)
1045
+    if ($taches and count($taches) and !spip_connect()) {
1046
+        return false;
1047
+    }
1048
+    spip_log("cron !", 'jq' . _LOG_DEBUG);
1049
+    if ($genie = charger_fonction('genie', 'inc', true)) {
1050
+        return $genie($taches);
1051
+    }
1052
+
1053
+    return false;
1055 1054
 }
1056 1055
 
1057 1056
 /**
@@ -1083,17 +1082,17 @@  discard block
 block discarded – undo
1083 1082
  *     Le numéro de travail ajouté ou `0` si aucun travail n’a été ajouté.
1084 1083
  */
1085 1084
 function job_queue_add(
1086
-	$function,
1087
-	$description,
1088
-	$arguments = array(),
1089
-	$file = '',
1090
-	$no_duplicate = false,
1091
-	$time = 0,
1092
-	$priority = 0
1085
+    $function,
1086
+    $description,
1087
+    $arguments = array(),
1088
+    $file = '',
1089
+    $no_duplicate = false,
1090
+    $time = 0,
1091
+    $priority = 0
1093 1092
 ) {
1094
-	include_spip('inc/queue');
1093
+    include_spip('inc/queue');
1095 1094
 
1096
-	return queue_add_job($function, $description, $arguments, $file, $no_duplicate, $time, $priority);
1095
+    return queue_add_job($function, $description, $arguments, $file, $no_duplicate, $time, $priority);
1097 1096
 }
1098 1097
 
1099 1098
 /**
@@ -1104,9 +1103,9 @@  discard block
 block discarded – undo
1104 1103
  * @return bool
1105 1104
  */
1106 1105
 function job_queue_remove($id_job) {
1107
-	include_spip('inc/queue');
1106
+    include_spip('inc/queue');
1108 1107
 
1109
-	return queue_remove_job($id_job);
1108
+    return queue_remove_job($id_job);
1110 1109
 }
1111 1110
 
1112 1111
 /**
@@ -1119,9 +1118,9 @@  discard block
 block discarded – undo
1119 1118
  *     or an array of simple array to link multiples objet in one time
1120 1119
  */
1121 1120
 function job_queue_link($id_job, $objets) {
1122
-	include_spip('inc/queue');
1121
+    include_spip('inc/queue');
1123 1122
 
1124
-	return queue_link_job($id_job, $objets);
1123
+    return queue_link_job($id_job, $objets);
1125 1124
 }
1126 1125
 
1127 1126
 
@@ -1141,36 +1140,36 @@  discard block
 block discarded – undo
1141 1140
  *  - `null` si la queue n'est pas encore initialisée
1142 1141
  */
1143 1142
 function queue_sleep_time_to_next_job($force = null) {
1144
-	static $queue_next_job_time = -1;
1145
-	if ($force === true) {
1146
-		$queue_next_job_time = -1;
1147
-	} elseif ($force) {
1148
-		$queue_next_job_time = $force;
1149
-	}
1150
-
1151
-	if ($queue_next_job_time == -1) {
1152
-		if (!defined('_JQ_NEXT_JOB_TIME_FILENAME')) {
1153
-			define('_JQ_NEXT_JOB_TIME_FILENAME', _DIR_TMP . "job_queue_next.txt");
1154
-		}
1155
-		// utiliser un cache memoire si dispo
1156
-		if (function_exists("cache_get") and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
1157
-			$queue_next_job_time = cache_get(_JQ_NEXT_JOB_TIME_FILENAME);
1158
-		} else {
1159
-			$queue_next_job_time = null;
1160
-			if (lire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, $contenu)) {
1161
-				$queue_next_job_time = intval($contenu);
1162
-			}
1163
-		}
1164
-	}
1165
-
1166
-	if (is_null($queue_next_job_time)) {
1167
-		return null;
1168
-	}
1169
-	if (!$_SERVER['REQUEST_TIME']) {
1170
-		$_SERVER['REQUEST_TIME'] = time();
1171
-	}
1172
-
1173
-	return $queue_next_job_time - $_SERVER['REQUEST_TIME'];
1143
+    static $queue_next_job_time = -1;
1144
+    if ($force === true) {
1145
+        $queue_next_job_time = -1;
1146
+    } elseif ($force) {
1147
+        $queue_next_job_time = $force;
1148
+    }
1149
+
1150
+    if ($queue_next_job_time == -1) {
1151
+        if (!defined('_JQ_NEXT_JOB_TIME_FILENAME')) {
1152
+            define('_JQ_NEXT_JOB_TIME_FILENAME', _DIR_TMP . "job_queue_next.txt");
1153
+        }
1154
+        // utiliser un cache memoire si dispo
1155
+        if (function_exists("cache_get") and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
1156
+            $queue_next_job_time = cache_get(_JQ_NEXT_JOB_TIME_FILENAME);
1157
+        } else {
1158
+            $queue_next_job_time = null;
1159
+            if (lire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, $contenu)) {
1160
+                $queue_next_job_time = intval($contenu);
1161
+            }
1162
+        }
1163
+    }
1164
+
1165
+    if (is_null($queue_next_job_time)) {
1166
+        return null;
1167
+    }
1168
+    if (!$_SERVER['REQUEST_TIME']) {
1169
+        $_SERVER['REQUEST_TIME'] = time();
1170
+    }
1171
+
1172
+    return $queue_next_job_time - $_SERVER['REQUEST_TIME'];
1174 1173
 }
1175 1174
 
1176 1175
 
@@ -1182,9 +1181,9 @@  discard block
 block discarded – undo
1182 1181
  * @return string
1183 1182
  */
1184 1183
 function quote_amp($u) {
1185
-	return preg_replace(
1186
-		"/&(?![a-z]{0,4}\w{2,3};|#x?[0-9a-f]{2,6};)/i",
1187
-		"&amp;", $u);
1184
+    return preg_replace(
1185
+        "/&(?![a-z]{0,4}\w{2,3};|#x?[0-9a-f]{2,6};)/i",
1186
+        "&amp;", $u);
1188 1187
 }
1189 1188
 
1190 1189
 
@@ -1207,27 +1206,27 @@  discard block
 block discarded – undo
1207 1206
  *     Balise HTML `<script>` et son contenu
1208 1207
  **/
1209 1208
 function http_script($script, $src = '', $noscript = '') {
1210
-	static $done = array();
1209
+    static $done = array();
1211 1210
 
1212
-	if ($src && !isset($done[$src])) {
1213
-		$done[$src] = true;
1214
-		$src = find_in_path($src, _JAVASCRIPT);
1215
-		$src = " src='$src'";
1216
-	} else {
1217
-		$src = '';
1218
-	}
1219
-	if ($script) {
1220
-		$script = ("/*<![CDATA[*/\n" .
1221
-			preg_replace(',</([^>]*)>,', '<\/\1>', $script) .
1222
-			"/*]]>*/");
1223
-	}
1224
-	if ($noscript) {
1225
-		$noscript = "<noscript>\n\t$noscript\n</noscript>\n";
1226
-	}
1211
+    if ($src && !isset($done[$src])) {
1212
+        $done[$src] = true;
1213
+        $src = find_in_path($src, _JAVASCRIPT);
1214
+        $src = " src='$src'";
1215
+    } else {
1216
+        $src = '';
1217
+    }
1218
+    if ($script) {
1219
+        $script = ("/*<![CDATA[*/\n" .
1220
+            preg_replace(',</([^>]*)>,', '<\/\1>', $script) .
1221
+            "/*]]>*/");
1222
+    }
1223
+    if ($noscript) {
1224
+        $noscript = "<noscript>\n\t$noscript\n</noscript>\n";
1225
+    }
1227 1226
 
1228
-	return ($src or $script or $noscript)
1229
-		? "<script type='text/javascript'$src>$script</script>$noscript"
1230
-		: '';
1227
+    return ($src or $script or $noscript)
1228
+        ? "<script type='text/javascript'$src>$script</script>$noscript"
1229
+        : '';
1231 1230
 }
1232 1231
 
1233 1232
 
@@ -1262,7 +1261,7 @@  discard block
 block discarded – undo
1262 1261
  *     Texte échappé
1263 1262
  **/
1264 1263
 function texte_script($texte) {
1265
-	return str_replace('\'', '\\\'', str_replace('\\', '\\\\', $texte));
1264
+    return str_replace('\'', '\\\'', str_replace('\\', '\\\\', $texte));
1266 1265
 }
1267 1266
 
1268 1267
 
@@ -1299,69 +1298,69 @@  discard block
 block discarded – undo
1299 1298
  *     Liste des chemins, par ordre de priorité.
1300 1299
  **/
1301 1300
 function _chemin($dir_path = null) {
1302
-	static $path_base = null;
1303
-	static $path_full = null;
1304
-	if ($path_base == null) {
1305
-		// Chemin standard depuis l'espace public
1306
-		$path = defined('_SPIP_PATH') ? _SPIP_PATH :
1307
-			_DIR_RACINE . ':' .
1308
-			_DIR_RACINE . 'squelettes-dist/:' .
1309
-			_DIR_RACINE . 'prive/:' .
1310
-			_DIR_RESTREINT;
1311
-		// Ajouter squelettes/
1312
-		if (@is_dir(_DIR_RACINE . 'squelettes')) {
1313
-			$path = _DIR_RACINE . 'squelettes/:' . $path;
1314
-		}
1315
-		foreach (explode(':', $path) as $dir) {
1316
-			if (strlen($dir) and substr($dir, -1) != '/') {
1317
-				$dir .= "/";
1318
-			}
1319
-			$path_base[] = $dir;
1320
-		}
1321
-		$path_full = $path_base;
1322
-		// Et le(s) dossier(s) des squelettes nommes
1323
-		if (strlen($GLOBALS['dossier_squelettes'])) {
1324
-			foreach (array_reverse(explode(':', $GLOBALS['dossier_squelettes'])) as $d) {
1325
-				array_unshift($path_full, ($d[0] == '/' ? '' : _DIR_RACINE) . $d . '/');
1326
-			}
1327
-		}
1328
-		$GLOBALS['path_sig'] = md5(serialize($path_full));
1329
-	}
1330
-	if ($dir_path === null) {
1331
-		return $path_full;
1332
-	}
1333
-
1334
-	if (strlen($dir_path)) {
1335
-		$tete = "";
1336
-		if (reset($path_base) == _DIR_RACINE . 'squelettes/') {
1337
-			$tete = array_shift($path_base);
1338
-		}
1339
-		$dirs = array_reverse(explode(':', $dir_path));
1340
-		foreach ($dirs as $dir_path) {
1341
-			#if ($dir_path{0}!='/')
1342
-			#	$dir_path = $dir_path;
1343
-			if (substr($dir_path, -1) != '/') {
1344
-				$dir_path .= "/";
1345
-			}
1346
-			if (!in_array($dir_path, $path_base)) {
1347
-				array_unshift($path_base, $dir_path);
1348
-			}
1349
-		}
1350
-		if (strlen($tete)) {
1351
-			array_unshift($path_base, $tete);
1352
-		}
1353
-	}
1354
-	$path_full = $path_base;
1355
-	// Et le(s) dossier(s) des squelettes nommes
1356
-	if (strlen($GLOBALS['dossier_squelettes'])) {
1357
-		foreach (array_reverse(explode(':', $GLOBALS['dossier_squelettes'])) as $d) {
1358
-			array_unshift($path_full, ((isset($d[0]) and $d[0] == '/') ? '' : _DIR_RACINE) . $d . '/');
1359
-		}
1360
-	}
1361
-
1362
-	$GLOBALS['path_sig'] = md5(serialize($path_full));
1363
-
1364
-	return $path_full;
1301
+    static $path_base = null;
1302
+    static $path_full = null;
1303
+    if ($path_base == null) {
1304
+        // Chemin standard depuis l'espace public
1305
+        $path = defined('_SPIP_PATH') ? _SPIP_PATH :
1306
+            _DIR_RACINE . ':' .
1307
+            _DIR_RACINE . 'squelettes-dist/:' .
1308
+            _DIR_RACINE . 'prive/:' .
1309
+            _DIR_RESTREINT;
1310
+        // Ajouter squelettes/
1311
+        if (@is_dir(_DIR_RACINE . 'squelettes')) {
1312
+            $path = _DIR_RACINE . 'squelettes/:' . $path;
1313
+        }
1314
+        foreach (explode(':', $path) as $dir) {
1315
+            if (strlen($dir) and substr($dir, -1) != '/') {
1316
+                $dir .= "/";
1317
+            }
1318
+            $path_base[] = $dir;
1319
+        }
1320
+        $path_full = $path_base;
1321
+        // Et le(s) dossier(s) des squelettes nommes
1322
+        if (strlen($GLOBALS['dossier_squelettes'])) {
1323
+            foreach (array_reverse(explode(':', $GLOBALS['dossier_squelettes'])) as $d) {
1324
+                array_unshift($path_full, ($d[0] == '/' ? '' : _DIR_RACINE) . $d . '/');
1325
+            }
1326
+        }
1327
+        $GLOBALS['path_sig'] = md5(serialize($path_full));
1328
+    }
1329
+    if ($dir_path === null) {
1330
+        return $path_full;
1331
+    }
1332
+
1333
+    if (strlen($dir_path)) {
1334
+        $tete = "";
1335
+        if (reset($path_base) == _DIR_RACINE . 'squelettes/') {
1336
+            $tete = array_shift($path_base);
1337
+        }
1338
+        $dirs = array_reverse(explode(':', $dir_path));
1339
+        foreach ($dirs as $dir_path) {
1340
+            #if ($dir_path{0}!='/')
1341
+            #	$dir_path = $dir_path;
1342
+            if (substr($dir_path, -1) != '/') {
1343
+                $dir_path .= "/";
1344
+            }
1345
+            if (!in_array($dir_path, $path_base)) {
1346
+                array_unshift($path_base, $dir_path);
1347
+            }
1348
+        }
1349
+        if (strlen($tete)) {
1350
+            array_unshift($path_base, $tete);
1351
+        }
1352
+    }
1353
+    $path_full = $path_base;
1354
+    // Et le(s) dossier(s) des squelettes nommes
1355
+    if (strlen($GLOBALS['dossier_squelettes'])) {
1356
+        foreach (array_reverse(explode(':', $GLOBALS['dossier_squelettes'])) as $d) {
1357
+            array_unshift($path_full, ((isset($d[0]) and $d[0] == '/') ? '' : _DIR_RACINE) . $d . '/');
1358
+        }
1359
+    }
1360
+
1361
+    $GLOBALS['path_sig'] = md5(serialize($path_full));
1362
+
1363
+    return $path_full;
1365 1364
 }
1366 1365
 
1367 1366
 /**
@@ -1374,76 +1373,76 @@  discard block
 block discarded – undo
1374 1373
  * @return array Liste de chemins
1375 1374
  **/
1376 1375
 function creer_chemin() {
1377
-	$path_a = _chemin();
1378
-	static $c = '';
1376
+    $path_a = _chemin();
1377
+    static $c = '';
1379 1378
 
1380
-	// on calcule le chemin si le dossier skel a change
1381
-	if ($c != $GLOBALS['dossier_squelettes']) {
1382
-		// assurer le non plantage lors de la montee de version :
1383
-		$c = $GLOBALS['dossier_squelettes'];
1384
-		$path_a = _chemin(''); // forcer un recalcul du chemin
1385
-	}
1379
+    // on calcule le chemin si le dossier skel a change
1380
+    if ($c != $GLOBALS['dossier_squelettes']) {
1381
+        // assurer le non plantage lors de la montee de version :
1382
+        $c = $GLOBALS['dossier_squelettes'];
1383
+        $path_a = _chemin(''); // forcer un recalcul du chemin
1384
+    }
1386 1385
 
1387
-	return $path_a;
1386
+    return $path_a;
1388 1387
 }
1389 1388
 
1390 1389
 
1391 1390
 function lister_themes_prives() {
1392
-	static $themes = null;
1393
-	if (is_null($themes)) {
1394
-		// si pas encore definie
1395
-		if (!defined('_SPIP_THEME_PRIVE')) {
1396
-			define('_SPIP_THEME_PRIVE', 'spip');
1397
-		}
1398
-		$themes = array(_SPIP_THEME_PRIVE);
1399
-		// lors d'une installation neuve, prefs n'est pas definie.
1400
-		if (isset($GLOBALS['visiteur_session']['prefs'])) {
1401
-			$prefs = $GLOBALS['visiteur_session']['prefs'];
1402
-		} else {
1403
-			$prefs = array();
1404
-		}
1405
-		if (is_string($prefs)) {
1406
-			$prefs = unserialize($GLOBALS['visiteur_session']['prefs']);
1407
-		}
1408
-		if (
1409
-			((isset($prefs['theme']) and $theme = $prefs['theme'])
1410
-				or (isset($GLOBALS['theme_prive_defaut']) and $theme = $GLOBALS['theme_prive_defaut']))
1411
-			and $theme != _SPIP_THEME_PRIVE
1412
-		) {
1413
-			array_unshift($themes, $theme);
1414
-		} // placer le theme choisi en tete
1415
-	}
1416
-
1417
-	return $themes;
1391
+    static $themes = null;
1392
+    if (is_null($themes)) {
1393
+        // si pas encore definie
1394
+        if (!defined('_SPIP_THEME_PRIVE')) {
1395
+            define('_SPIP_THEME_PRIVE', 'spip');
1396
+        }
1397
+        $themes = array(_SPIP_THEME_PRIVE);
1398
+        // lors d'une installation neuve, prefs n'est pas definie.
1399
+        if (isset($GLOBALS['visiteur_session']['prefs'])) {
1400
+            $prefs = $GLOBALS['visiteur_session']['prefs'];
1401
+        } else {
1402
+            $prefs = array();
1403
+        }
1404
+        if (is_string($prefs)) {
1405
+            $prefs = unserialize($GLOBALS['visiteur_session']['prefs']);
1406
+        }
1407
+        if (
1408
+            ((isset($prefs['theme']) and $theme = $prefs['theme'])
1409
+                or (isset($GLOBALS['theme_prive_defaut']) and $theme = $GLOBALS['theme_prive_defaut']))
1410
+            and $theme != _SPIP_THEME_PRIVE
1411
+        ) {
1412
+            array_unshift($themes, $theme);
1413
+        } // placer le theme choisi en tete
1414
+    }
1415
+
1416
+    return $themes;
1418 1417
 }
1419 1418
 
1420 1419
 function find_in_theme($file, $subdir = '', $include = false) {
1421
-	static $themefiles = array();
1422
-	if (isset($themefiles["$subdir$file"])) {
1423
-		return $themefiles["$subdir$file"];
1424
-	}
1425
-	// on peut fournir une icone generique -xx.svg qui fera le job dans toutes les tailles, et qui est prioritaire sur le png
1426
-	// si il y a un .svg a la bonne taille (-16.svg) a cote, on l'utilise en remplacement du -16.png
1427
-	if (preg_match(',-(\d+)[.](png|gif|svg)$,', $file, $m)
1428
-	  and $file_svg_generique = substr($file,0, -strlen($m[0])) . "-xx.svg"
1429
-		and $f = find_in_theme("$file_svg_generique")) {
1430
-		if ($fsize = substr($f,0,-6) . $m[1] . ".svg" and file_exists($fsize)) {
1431
-			return $themefiles["$subdir$file"] = $fsize;
1432
-		}
1433
-		else {
1434
-			return $themefiles["$subdir$file"] = "$f?".$m[1]."px";
1435
-		}
1436
-	}
1437
-
1438
-	$themes = lister_themes_prives();
1439
-	foreach ($themes as $theme) {
1440
-		if ($f = find_in_path($file, "prive/themes/$theme/$subdir", $include)) {
1441
-			return $themefiles["$subdir$file"] = $f;
1442
-		}
1443
-	}
1444
-	spip_log("$file introuvable dans le theme prive " . reset($themes), 'theme');
1445
-
1446
-	return $themefiles["$subdir$file"] = "";
1420
+    static $themefiles = array();
1421
+    if (isset($themefiles["$subdir$file"])) {
1422
+        return $themefiles["$subdir$file"];
1423
+    }
1424
+    // on peut fournir une icone generique -xx.svg qui fera le job dans toutes les tailles, et qui est prioritaire sur le png
1425
+    // si il y a un .svg a la bonne taille (-16.svg) a cote, on l'utilise en remplacement du -16.png
1426
+    if (preg_match(',-(\d+)[.](png|gif|svg)$,', $file, $m)
1427
+      and $file_svg_generique = substr($file,0, -strlen($m[0])) . "-xx.svg"
1428
+        and $f = find_in_theme("$file_svg_generique")) {
1429
+        if ($fsize = substr($f,0,-6) . $m[1] . ".svg" and file_exists($fsize)) {
1430
+            return $themefiles["$subdir$file"] = $fsize;
1431
+        }
1432
+        else {
1433
+            return $themefiles["$subdir$file"] = "$f?".$m[1]."px";
1434
+        }
1435
+    }
1436
+
1437
+    $themes = lister_themes_prives();
1438
+    foreach ($themes as $theme) {
1439
+        if ($f = find_in_path($file, "prive/themes/$theme/$subdir", $include)) {
1440
+            return $themefiles["$subdir$file"] = $f;
1441
+        }
1442
+    }
1443
+    spip_log("$file introuvable dans le theme prive " . reset($themes), 'theme');
1444
+
1445
+    return $themefiles["$subdir$file"] = "";
1447 1446
 }
1448 1447
 
1449 1448
 
@@ -1467,31 +1466,31 @@  discard block
 block discarded – undo
1467 1466
  *     sinon chaîne vide.
1468 1467
  **/
1469 1468
 function chemin_image($icone) {
1470
-	static $icone_renommer;
1471
-	if ($p = strpos($icone, '?')) {
1472
-		$icone = substr($icone,0, $p);
1473
-	}
1474
-	// gerer le cas d'un double appel en evitant de refaire le travail inutilement
1475
-	if (strpos($icone, "/") !== false and file_exists($icone)) {
1476
-		return $icone;
1477
-	}
1478
-
1479
-	// si c'est un nom d'image complet (article-24.png) essayer de le renvoyer direct
1480
-	if (preg_match(',[.](png|gif|jpg|webp|svg)$,', $icone) and $f = find_in_theme("images/$icone")) {
1481
-		return $f;
1482
-	}
1483
-	// sinon passer par le module de renommage
1484
-	if (is_null($icone_renommer)) {
1485
-		$icone_renommer = charger_fonction('icone_renommer', 'inc', true);
1486
-	}
1487
-	if ($icone_renommer) {
1488
-		list($icone, $fonction) = $icone_renommer($icone, "");
1489
-		if (file_exists($icone)) {
1490
-			return $icone;
1491
-		}
1492
-	}
1493
-
1494
-	return find_in_path($icone, _NOM_IMG_PACK);
1469
+    static $icone_renommer;
1470
+    if ($p = strpos($icone, '?')) {
1471
+        $icone = substr($icone,0, $p);
1472
+    }
1473
+    // gerer le cas d'un double appel en evitant de refaire le travail inutilement
1474
+    if (strpos($icone, "/") !== false and file_exists($icone)) {
1475
+        return $icone;
1476
+    }
1477
+
1478
+    // si c'est un nom d'image complet (article-24.png) essayer de le renvoyer direct
1479
+    if (preg_match(',[.](png|gif|jpg|webp|svg)$,', $icone) and $f = find_in_theme("images/$icone")) {
1480
+        return $f;
1481
+    }
1482
+    // sinon passer par le module de renommage
1483
+    if (is_null($icone_renommer)) {
1484
+        $icone_renommer = charger_fonction('icone_renommer', 'inc', true);
1485
+    }
1486
+    if ($icone_renommer) {
1487
+        list($icone, $fonction) = $icone_renommer($icone, "");
1488
+        if (file_exists($icone)) {
1489
+            return $icone;
1490
+        }
1491
+    }
1492
+
1493
+    return find_in_path($icone, _NOM_IMG_PACK);
1495 1494
 }
1496 1495
 
1497 1496
 //
@@ -1529,127 +1528,127 @@  discard block
 block discarded – undo
1529 1528
  *     - false : fichier introuvable
1530 1529
  **/
1531 1530
 function find_in_path($file, $dirname = '', $include = false) {
1532
-	static $dirs = array();
1533
-	static $inc = array(); # cf https://git.spip.net/spip/spip/commit/42e4e028e38c839121efaee84308d08aee307eec
1534
-	static $c = '';
1535
-
1536
-	if (!$file and !strlen($file)) {
1537
-		return false;
1538
-	}
1539
-
1540
-	// on calcule le chemin si le dossier skel a change
1541
-	if ($c != $GLOBALS['dossier_squelettes']) {
1542
-		// assurer le non plantage lors de la montee de version :
1543
-		$c = $GLOBALS['dossier_squelettes'];
1544
-		creer_chemin(); // forcer un recalcul du chemin et la mise a jour de path_sig
1545
-	}
1546
-
1547
-	if (isset($GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file])) {
1548
-		if (!$GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file]) {
1549
-			return false;
1550
-		}
1551
-		if ($include and !isset($inc[$dirname][$file])) {
1552
-			include_once _ROOT_CWD . $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file];
1553
-			$inc[$dirname][$file] = $inc[''][$dirname . $file] = true;
1554
-		}
1555
-
1556
-		return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file];
1557
-	}
1558
-
1559
-	$a = strrpos($file, '/');
1560
-	if ($a !== false) {
1561
-		$dirname .= substr($file, 0, ++$a);
1562
-		$file = substr($file, $a);
1563
-	}
1564
-
1565
-	foreach (creer_chemin() as $dir) {
1566
-		if (!isset($dirs[$a = $dir . $dirname])) {
1567
-			$dirs[$a] = (is_dir(_ROOT_CWD . $a) || !$a);
1568
-		}
1569
-		if ($dirs[$a]) {
1570
-			if (file_exists(_ROOT_CWD . ($a .= $file))) {
1571
-				if ($include and !isset($inc[$dirname][$file])) {
1572
-					include_once _ROOT_CWD . $a;
1573
-					$inc[$dirname][$file] = $inc[''][$dirname . $file] = true;
1574
-				}
1575
-				if (!defined('_SAUVER_CHEMIN')) {
1576
-					// si le chemin n'a pas encore ete charge, ne pas lever le flag, ne pas cacher
1577
-					if (is_null($GLOBALS['path_files'])) {
1578
-						return $a;
1579
-					}
1580
-					define('_SAUVER_CHEMIN', true);
1581
-				}
1582
-
1583
-				return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file] = $GLOBALS['path_files'][$GLOBALS['path_sig']][''][$dirname . $file] = $a;
1584
-			}
1585
-		}
1586
-	}
1587
-
1588
-	if ($include) {
1589
-		spip_log("include_spip $dirname$file non trouve");
1590
-		if ($include === 'required') {
1591
-			echo '<pre>',
1592
-			"<strong>Erreur Fatale</strong><br />";
1593
-			if (function_exists('debug_print_backtrace')) {
1594
-				echo debug_print_backtrace();
1595
-			}
1596
-			echo '</pre>';
1597
-			die("Erreur interne: ne peut inclure $dirname$file");
1598
-		}
1599
-	}
1600
-
1601
-	if (!defined('_SAUVER_CHEMIN')) {
1602
-		// si le chemin n'a pas encore ete charge, ne pas lever le flag, ne pas cacher
1603
-		if (is_null($GLOBALS['path_files'])) {
1604
-			return false;
1605
-		}
1606
-		define('_SAUVER_CHEMIN', true);
1607
-	}
1608
-
1609
-	return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file] = $GLOBALS['path_files'][$GLOBALS['path_sig']][''][$dirname . $file] = false;
1531
+    static $dirs = array();
1532
+    static $inc = array(); # cf https://git.spip.net/spip/spip/commit/42e4e028e38c839121efaee84308d08aee307eec
1533
+    static $c = '';
1534
+
1535
+    if (!$file and !strlen($file)) {
1536
+        return false;
1537
+    }
1538
+
1539
+    // on calcule le chemin si le dossier skel a change
1540
+    if ($c != $GLOBALS['dossier_squelettes']) {
1541
+        // assurer le non plantage lors de la montee de version :
1542
+        $c = $GLOBALS['dossier_squelettes'];
1543
+        creer_chemin(); // forcer un recalcul du chemin et la mise a jour de path_sig
1544
+    }
1545
+
1546
+    if (isset($GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file])) {
1547
+        if (!$GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file]) {
1548
+            return false;
1549
+        }
1550
+        if ($include and !isset($inc[$dirname][$file])) {
1551
+            include_once _ROOT_CWD . $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file];
1552
+            $inc[$dirname][$file] = $inc[''][$dirname . $file] = true;
1553
+        }
1554
+
1555
+        return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file];
1556
+    }
1557
+
1558
+    $a = strrpos($file, '/');
1559
+    if ($a !== false) {
1560
+        $dirname .= substr($file, 0, ++$a);
1561
+        $file = substr($file, $a);
1562
+    }
1563
+
1564
+    foreach (creer_chemin() as $dir) {
1565
+        if (!isset($dirs[$a = $dir . $dirname])) {
1566
+            $dirs[$a] = (is_dir(_ROOT_CWD . $a) || !$a);
1567
+        }
1568
+        if ($dirs[$a]) {
1569
+            if (file_exists(_ROOT_CWD . ($a .= $file))) {
1570
+                if ($include and !isset($inc[$dirname][$file])) {
1571
+                    include_once _ROOT_CWD . $a;
1572
+                    $inc[$dirname][$file] = $inc[''][$dirname . $file] = true;
1573
+                }
1574
+                if (!defined('_SAUVER_CHEMIN')) {
1575
+                    // si le chemin n'a pas encore ete charge, ne pas lever le flag, ne pas cacher
1576
+                    if (is_null($GLOBALS['path_files'])) {
1577
+                        return $a;
1578
+                    }
1579
+                    define('_SAUVER_CHEMIN', true);
1580
+                }
1581
+
1582
+                return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file] = $GLOBALS['path_files'][$GLOBALS['path_sig']][''][$dirname . $file] = $a;
1583
+            }
1584
+        }
1585
+    }
1586
+
1587
+    if ($include) {
1588
+        spip_log("include_spip $dirname$file non trouve");
1589
+        if ($include === 'required') {
1590
+            echo '<pre>',
1591
+            "<strong>Erreur Fatale</strong><br />";
1592
+            if (function_exists('debug_print_backtrace')) {
1593
+                echo debug_print_backtrace();
1594
+            }
1595
+            echo '</pre>';
1596
+            die("Erreur interne: ne peut inclure $dirname$file");
1597
+        }
1598
+    }
1599
+
1600
+    if (!defined('_SAUVER_CHEMIN')) {
1601
+        // si le chemin n'a pas encore ete charge, ne pas lever le flag, ne pas cacher
1602
+        if (is_null($GLOBALS['path_files'])) {
1603
+            return false;
1604
+        }
1605
+        define('_SAUVER_CHEMIN', true);
1606
+    }
1607
+
1608
+    return $GLOBALS['path_files'][$GLOBALS['path_sig']][$dirname][$file] = $GLOBALS['path_files'][$GLOBALS['path_sig']][''][$dirname . $file] = false;
1610 1609
 }
1611 1610
 
1612 1611
 function clear_path_cache() {
1613
-	$GLOBALS['path_files'] = array();
1614
-	spip_unlink(_CACHE_CHEMIN);
1612
+    $GLOBALS['path_files'] = array();
1613
+    spip_unlink(_CACHE_CHEMIN);
1615 1614
 }
1616 1615
 
1617 1616
 function load_path_cache() {
1618
-	// charger le path des plugins
1619
-	if (@is_readable(_CACHE_PLUGINS_PATH)) {
1620
-		include_once(_CACHE_PLUGINS_PATH);
1621
-	}
1622
-	$GLOBALS['path_files'] = array();
1623
-	// si le visiteur est admin,
1624
-	// on ne recharge pas le cache pour forcer sa mise a jour
1625
-	if (
1626
-		// la session n'est pas encore chargee a ce moment, on ne peut donc pas s'y fier
1627
-		//AND (!isset($GLOBALS['visiteur_session']['statut']) OR $GLOBALS['visiteur_session']['statut']!='0minirezo')
1628
-		// utiliser le cookie est un pis aller qui marche 'en general'
1629
-		// on blinde par un second test au moment de la lecture de la session
1630
-		// !isset($_COOKIE[$GLOBALS['cookie_prefix'].'_admin'])
1631
-		// et en ignorant ce cache en cas de recalcul explicite
1632
-	!_request('var_mode')
1633
-	) {
1634
-		// on essaye de lire directement sans verrou pour aller plus vite
1635
-		if ($contenu = spip_file_get_contents(_CACHE_CHEMIN)) {
1636
-			// mais si semble corrompu on relit avec un verrou
1637
-			if (!$GLOBALS['path_files'] = unserialize($contenu)) {
1638
-				lire_fichier(_CACHE_CHEMIN, $contenu);
1639
-				if (!$GLOBALS['path_files'] = unserialize($contenu)) {
1640
-					$GLOBALS['path_files'] = array();
1641
-				}
1642
-			}
1643
-		}
1644
-	}
1617
+    // charger le path des plugins
1618
+    if (@is_readable(_CACHE_PLUGINS_PATH)) {
1619
+        include_once(_CACHE_PLUGINS_PATH);
1620
+    }
1621
+    $GLOBALS['path_files'] = array();
1622
+    // si le visiteur est admin,
1623
+    // on ne recharge pas le cache pour forcer sa mise a jour
1624
+    if (
1625
+        // la session n'est pas encore chargee a ce moment, on ne peut donc pas s'y fier
1626
+        //AND (!isset($GLOBALS['visiteur_session']['statut']) OR $GLOBALS['visiteur_session']['statut']!='0minirezo')
1627
+        // utiliser le cookie est un pis aller qui marche 'en general'
1628
+        // on blinde par un second test au moment de la lecture de la session
1629
+        // !isset($_COOKIE[$GLOBALS['cookie_prefix'].'_admin'])
1630
+        // et en ignorant ce cache en cas de recalcul explicite
1631
+    !_request('var_mode')
1632
+    ) {
1633
+        // on essaye de lire directement sans verrou pour aller plus vite
1634
+        if ($contenu = spip_file_get_contents(_CACHE_CHEMIN)) {
1635
+            // mais si semble corrompu on relit avec un verrou
1636
+            if (!$GLOBALS['path_files'] = unserialize($contenu)) {
1637
+                lire_fichier(_CACHE_CHEMIN, $contenu);
1638
+                if (!$GLOBALS['path_files'] = unserialize($contenu)) {
1639
+                    $GLOBALS['path_files'] = array();
1640
+                }
1641
+            }
1642
+        }
1643
+    }
1645 1644
 }
1646 1645
 
1647 1646
 function save_path_cache() {
1648
-	if (defined('_SAUVER_CHEMIN')
1649
-		and _SAUVER_CHEMIN
1650
-	) {
1651
-		ecrire_fichier(_CACHE_CHEMIN, serialize($GLOBALS['path_files']));
1652
-	}
1647
+    if (defined('_SAUVER_CHEMIN')
1648
+        and _SAUVER_CHEMIN
1649
+    ) {
1650
+        ecrire_fichier(_CACHE_CHEMIN, serialize($GLOBALS['path_files']));
1651
+    }
1653 1652
 }
1654 1653
 
1655 1654
 
@@ -1669,33 +1668,33 @@  discard block
 block discarded – undo
1669 1668
  * @return array
1670 1669
  */
1671 1670
 function find_all_in_path($dir, $pattern, $recurs = false) {
1672
-	$liste_fichiers = array();
1673
-	$maxfiles = 10000;
1674
-
1675
-	// cas borderline si dans mes_options on appelle redirige_par_entete qui utilise _T et charge un fichier de langue
1676
-	// on a pas encore inclus flock.php
1677
-	if (!function_exists('preg_files')) {
1678
-		include_once _ROOT_RESTREINT . 'inc/flock.php';
1679
-	}
1680
-
1681
-	// Parcourir le chemin
1682
-	foreach (creer_chemin() as $d) {
1683
-		$f = $d . $dir;
1684
-		if (@is_dir($f)) {
1685
-			$liste = preg_files($f, $pattern, $maxfiles - count($liste_fichiers), $recurs === true ? array() : $recurs);
1686
-			foreach ($liste as $chemin) {
1687
-				$nom = basename($chemin);
1688
-				// ne prendre que les fichiers pas deja trouves
1689
-				// car find_in_path prend le premier qu'il trouve,
1690
-				// les autres sont donc masques
1691
-				if (!isset($liste_fichiers[$nom])) {
1692
-					$liste_fichiers[$nom] = $chemin;
1693
-				}
1694
-			}
1695
-		}
1696
-	}
1697
-
1698
-	return $liste_fichiers;
1671
+    $liste_fichiers = array();
1672
+    $maxfiles = 10000;
1673
+
1674
+    // cas borderline si dans mes_options on appelle redirige_par_entete qui utilise _T et charge un fichier de langue
1675
+    // on a pas encore inclus flock.php
1676
+    if (!function_exists('preg_files')) {
1677
+        include_once _ROOT_RESTREINT . 'inc/flock.php';
1678
+    }
1679
+
1680
+    // Parcourir le chemin
1681
+    foreach (creer_chemin() as $d) {
1682
+        $f = $d . $dir;
1683
+        if (@is_dir($f)) {
1684
+            $liste = preg_files($f, $pattern, $maxfiles - count($liste_fichiers), $recurs === true ? array() : $recurs);
1685
+            foreach ($liste as $chemin) {
1686
+                $nom = basename($chemin);
1687
+                // ne prendre que les fichiers pas deja trouves
1688
+                // car find_in_path prend le premier qu'il trouve,
1689
+                // les autres sont donc masques
1690
+                if (!isset($liste_fichiers[$nom])) {
1691
+                    $liste_fichiers[$nom] = $chemin;
1692
+                }
1693
+            }
1694
+        }
1695
+    }
1696
+
1697
+    return $liste_fichiers;
1699 1698
 }
1700 1699
 
1701 1700
 /**
@@ -1707,17 +1706,17 @@  discard block
 block discarded – undo
1707 1706
  * @return bool
1708 1707
  */
1709 1708
 function autoriser_sans_cookie($nom, $strict = false) {
1710
-	static $autsanscookie = array('install', 'base_repair');
1709
+    static $autsanscookie = array('install', 'base_repair');
1711 1710
 
1712
-	if (in_array($nom, $autsanscookie)) {
1713
-		if (test_espace_prive()){
1714
-			include_spip('base/connect_sql');
1715
-			if (!$strict or !spip_connect()){
1716
-				return true;
1717
-			}
1718
-		}
1719
-	}
1720
-	return false;
1711
+    if (in_array($nom, $autsanscookie)) {
1712
+        if (test_espace_prive()){
1713
+            include_spip('base/connect_sql');
1714
+            if (!$strict or !spip_connect()){
1715
+                return true;
1716
+            }
1717
+        }
1718
+    }
1719
+    return false;
1721 1720
 }
1722 1721
 
1723 1722
 /**
@@ -1743,99 +1742,99 @@  discard block
 block discarded – undo
1743 1742
  *           (cas des raccourcis personalises [->spip20] : il faut implementer une fonction generer_url_spip et une fonction generer_url_ecrire_spip)
1744 1743
  */
1745 1744
 function generer_url_entite($id = '', $entite = '', $args = '', $ancre = '', $public = null, $type = null) {
1746
-	if ($public === null) {
1747
-		$public = !test_espace_prive();
1748
-	}
1749
-	$entite = objet_type($entite); // cas particulier d'appels sur objet/id_objet...
1750
-
1751
-	if (!$public) {
1752
-		if (!$entite) {
1753
-			return '';
1754
-		}
1755
-		if (!function_exists('generer_url_ecrire_objet')) {
1756
-			include_spip('inc/urls');
1757
-		}
1758
-		$res = generer_url_ecrire_objet($entite, $id, $args, $ancre, false);
1759
-	} else {
1760
-		if ($type === null) {
1761
-			$type = (isset($GLOBALS['type_urls']))
1762
-				? $GLOBALS['type_urls'] // pour surcharge via fichier d'options
1763
-				: ((isset($GLOBALS['meta']['type_urls'])) // sinon la config url_etendues
1764
-					? ($GLOBALS['meta']['type_urls']) : "page"); // sinon type "page" par défaut
1765
-		}
1766
-
1767
-		$f = charger_fonction($type, 'urls', true);
1768
-		// se rabattre sur les urls page si les urls perso non dispo
1769
-		if (!$f) {
1770
-			$f = charger_fonction('page', 'urls', true);
1771
-		}
1772
-
1773
-		// si $entite='', on veut la fonction de passage URL ==> id
1774
-		// sinon on veut effectuer le passage id ==> URL
1775
-		if (!$entite) {
1776
-			return $f;
1777
-		}
1778
-
1779
-		// mais d'abord il faut tester le cas des urls sur une
1780
-		// base distante
1781
-		if (is_string($public)
1782
-			and $g = charger_fonction('connect', 'urls', true)
1783
-		) {
1784
-			$f = $g;
1785
-		}
1786
-
1787
-		$res = $f(intval($id), $entite, $args, $ancre, $public);
1788
-
1789
-	}
1790
-	if ($res) {
1791
-		return $res;
1792
-	}
1793
-	// Sinon c'est un raccourci ou compat SPIP < 2
1794
-	if (!function_exists($f = 'generer_url_' . $entite)) {
1795
-		if (!function_exists($f .= '_dist')) {
1796
-			$f = '';
1797
-		}
1798
-	}
1799
-	if ($f) {
1800
-		$url = $f($id, $args, $ancre);
1801
-		if (strlen($args)) {
1802
-			$url .= strstr($url, '?')
1803
-				? '&amp;' . $args
1804
-				: '?' . $args;
1805
-		}
1806
-
1807
-		return $url;
1808
-	}
1809
-	// On a ete gentil mais la ....
1810
-	spip_log("generer_url_entite: entite $entite ($f) inconnue $type $public");
1811
-
1812
-	return '';
1745
+    if ($public === null) {
1746
+        $public = !test_espace_prive();
1747
+    }
1748
+    $entite = objet_type($entite); // cas particulier d'appels sur objet/id_objet...
1749
+
1750
+    if (!$public) {
1751
+        if (!$entite) {
1752
+            return '';
1753
+        }
1754
+        if (!function_exists('generer_url_ecrire_objet')) {
1755
+            include_spip('inc/urls');
1756
+        }
1757
+        $res = generer_url_ecrire_objet($entite, $id, $args, $ancre, false);
1758
+    } else {
1759
+        if ($type === null) {
1760
+            $type = (isset($GLOBALS['type_urls']))
1761
+                ? $GLOBALS['type_urls'] // pour surcharge via fichier d'options
1762
+                : ((isset($GLOBALS['meta']['type_urls'])) // sinon la config url_etendues
1763
+                    ? ($GLOBALS['meta']['type_urls']) : "page"); // sinon type "page" par défaut
1764
+        }
1765
+
1766
+        $f = charger_fonction($type, 'urls', true);
1767
+        // se rabattre sur les urls page si les urls perso non dispo
1768
+        if (!$f) {
1769
+            $f = charger_fonction('page', 'urls', true);
1770
+        }
1771
+
1772
+        // si $entite='', on veut la fonction de passage URL ==> id
1773
+        // sinon on veut effectuer le passage id ==> URL
1774
+        if (!$entite) {
1775
+            return $f;
1776
+        }
1777
+
1778
+        // mais d'abord il faut tester le cas des urls sur une
1779
+        // base distante
1780
+        if (is_string($public)
1781
+            and $g = charger_fonction('connect', 'urls', true)
1782
+        ) {
1783
+            $f = $g;
1784
+        }
1785
+
1786
+        $res = $f(intval($id), $entite, $args, $ancre, $public);
1787
+
1788
+    }
1789
+    if ($res) {
1790
+        return $res;
1791
+    }
1792
+    // Sinon c'est un raccourci ou compat SPIP < 2
1793
+    if (!function_exists($f = 'generer_url_' . $entite)) {
1794
+        if (!function_exists($f .= '_dist')) {
1795
+            $f = '';
1796
+        }
1797
+    }
1798
+    if ($f) {
1799
+        $url = $f($id, $args, $ancre);
1800
+        if (strlen($args)) {
1801
+            $url .= strstr($url, '?')
1802
+                ? '&amp;' . $args
1803
+                : '?' . $args;
1804
+        }
1805
+
1806
+        return $url;
1807
+    }
1808
+    // On a ete gentil mais la ....
1809
+    spip_log("generer_url_entite: entite $entite ($f) inconnue $type $public");
1810
+
1811
+    return '';
1813 1812
 }
1814 1813
 
1815 1814
 function generer_url_ecrire_entite_edit($id, $entite, $args = '', $ancre = '') {
1816
-	$exec = objet_info($entite, 'url_edit');
1817
-	$url = generer_url_ecrire($exec, $args);
1818
-	if (intval($id)) {
1819
-		$url = parametre_url($url, id_table_objet($entite), $id);
1820
-	} else {
1821
-		$url = parametre_url($url, 'new', 'oui');
1822
-	}
1823
-	if ($ancre) {
1824
-		$url = ancre_url($url, $ancre);
1825
-	}
1815
+    $exec = objet_info($entite, 'url_edit');
1816
+    $url = generer_url_ecrire($exec, $args);
1817
+    if (intval($id)) {
1818
+        $url = parametre_url($url, id_table_objet($entite), $id);
1819
+    } else {
1820
+        $url = parametre_url($url, 'new', 'oui');
1821
+    }
1822
+    if ($ancre) {
1823
+        $url = ancre_url($url, $ancre);
1824
+    }
1826 1825
 
1827
-	return $url;
1826
+    return $url;
1828 1827
 }
1829 1828
 
1830 1829
 // https://code.spip.net/@urls_connect_dist
1831 1830
 function urls_connect_dist($i, &$entite, $args = '', $ancre = '', $public = null) {
1832
-	include_spip('base/connect_sql');
1833
-	$id_type = id_table_objet($entite, $public);
1831
+    include_spip('base/connect_sql');
1832
+    $id_type = id_table_objet($entite, $public);
1834 1833
 
1835
-	return _DIR_RACINE . get_spip_script('./')
1836
-	. "?" . _SPIP_PAGE . "=$entite&$id_type=$i&connect=$public"
1837
-	. (!$args ? '' : "&$args")
1838
-	. (!$ancre ? '' : "#$ancre");
1834
+    return _DIR_RACINE . get_spip_script('./')
1835
+    . "?" . _SPIP_PAGE . "=$entite&$id_type=$i&connect=$public"
1836
+    . (!$args ? '' : "&$args")
1837
+    . (!$ancre ? '' : "#$ancre");
1839 1838
 }
1840 1839
 
1841 1840
 
@@ -1846,32 +1845,32 @@  discard block
 block discarded – undo
1846 1845
  * @return string
1847 1846
  */
1848 1847
 function urlencode_1738($url) {
1849
-	if (preg_match(',[^\x00-\x7E],sS', $url)) {
1850
-		$uri = '';
1851
-		for ($i = 0; $i < strlen($url); $i++) {
1852
-			if (ord($a = $url[$i]) > 127) {
1853
-				$a = rawurlencode($a);
1854
-			}
1855
-			$uri .= $a;
1856
-		}
1857
-		$url = $uri;
1858
-	}
1848
+    if (preg_match(',[^\x00-\x7E],sS', $url)) {
1849
+        $uri = '';
1850
+        for ($i = 0; $i < strlen($url); $i++) {
1851
+            if (ord($a = $url[$i]) > 127) {
1852
+                $a = rawurlencode($a);
1853
+            }
1854
+            $uri .= $a;
1855
+        }
1856
+        $url = $uri;
1857
+    }
1859 1858
 
1860
-	return quote_amp($url);
1859
+    return quote_amp($url);
1861 1860
 }
1862 1861
 
1863 1862
 // https://code.spip.net/@generer_url_entite_absolue
1864 1863
 function generer_url_entite_absolue($id = '', $entite = '', $args = '', $ancre = '', $connect = null) {
1865
-	if (!$connect) {
1866
-		$connect = true;
1867
-	}
1868
-	$h = generer_url_entite($id, $entite, $args, $ancre, $connect);
1869
-	if (!preg_match(',^\w+:,', $h)) {
1870
-		include_spip('inc/filtres_mini');
1871
-		$h = url_absolue($h);
1872
-	}
1864
+    if (!$connect) {
1865
+        $connect = true;
1866
+    }
1867
+    $h = generer_url_entite($id, $entite, $args, $ancre, $connect);
1868
+    if (!preg_match(',^\w+:,', $h)) {
1869
+        include_spip('inc/filtres_mini');
1870
+        $h = url_absolue($h);
1871
+    }
1873 1872
 
1874
-	return $h;
1873
+    return $h;
1875 1874
 }
1876 1875
 
1877 1876
 
@@ -1887,11 +1886,11 @@  discard block
 block discarded – undo
1887 1886
  *     true si la valeur est considérée active ; false sinon.
1888 1887
  **/
1889 1888
 function test_valeur_serveur($truc) {
1890
-	if (!$truc) {
1891
-		return false;
1892
-	}
1889
+    if (!$truc) {
1890
+        return false;
1891
+    }
1893 1892
 
1894
-	return (strtolower($truc) !== 'off');
1893
+    return (strtolower($truc) !== 'off');
1895 1894
 }
1896 1895
 
1897 1896
 //
@@ -1919,80 +1918,80 @@  discard block
 block discarded – undo
1919 1918
  */
1920 1919
 function url_de_base($profondeur = null) {
1921 1920
 
1922
-	static $url = array();
1923
-	if (is_array($profondeur)) {
1924
-		return $url = $profondeur;
1925
-	}
1926
-	if ($profondeur === false) {
1927
-		return $url;
1928
-	}
1929
-
1930
-	if (is_null($profondeur)) {
1931
-		$profondeur = $GLOBALS['profondeur_url'];
1932
-	}
1933
-
1934
-	if (isset($url[$profondeur])) {
1935
-		return $url[$profondeur];
1936
-	}
1937
-
1938
-	$http = 'http';
1939
-
1940
-	if (
1941
-		isset($_SERVER["SCRIPT_URI"])
1942
-		and substr($_SERVER["SCRIPT_URI"], 0, 5) == 'https'
1943
-	) {
1944
-		$http = 'https';
1945
-	} elseif (
1946
-		isset($_SERVER['HTTPS'])
1947
-		and test_valeur_serveur($_SERVER['HTTPS'])
1948
-	) {
1949
-		$http = 'https';
1950
-	}
1951
-
1952
-	// note : HTTP_HOST contient le :port si necessaire
1953
-	$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
1954
-	// si on n'a pas trouvé d'hôte du tout, en dernier recours on utilise adresse_site comme fallback
1955
-	if (is_null($host) and isset($GLOBALS['meta']['adresse_site'])) {
1956
-		$host = $GLOBALS['meta']['adresse_site'];
1957
-		if ($scheme = parse_url($host, PHP_URL_SCHEME)) {
1958
-			$http = $scheme;
1959
-			$host = str_replace("{$scheme}://", '', $host);
1960
-		}
1961
-	}
1962
-	if (isset($_SERVER['SERVER_PORT'])
1963
-		and $port = $_SERVER['SERVER_PORT']
1964
-		and strpos($host, ":") == false
1965
-	) {
1966
-		if (!defined('_PORT_HTTP_STANDARD')) {
1967
-			define('_PORT_HTTP_STANDARD', '80');
1968
-		}
1969
-		if (!defined('_PORT_HTTPS_STANDARD')) {
1970
-			define('_PORT_HTTPS_STANDARD', '443');
1971
-		}
1972
-		if ($http == "http" and !in_array($port, explode(',', _PORT_HTTP_STANDARD))) {
1973
-			$host .= ":$port";
1974
-		}
1975
-		if ($http == "https" and !in_array($port, explode(',', _PORT_HTTPS_STANDARD))) {
1976
-			$host .= ":$port";
1977
-		}
1978
-	}
1979
-
1980
-	if (!$GLOBALS['REQUEST_URI']) {
1981
-		if (isset($_SERVER['REQUEST_URI'])) {
1982
-			$GLOBALS['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
1983
-		} else {
1984
-			$GLOBALS['REQUEST_URI'] = (php_sapi_name() !== 'cli') ? $_SERVER['PHP_SELF'] : '';
1985
-			if (!empty($_SERVER['QUERY_STRING'])
1986
-				and !strpos($_SERVER['REQUEST_URI'], '?')
1987
-			) {
1988
-				$GLOBALS['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
1989
-			}
1990
-		}
1991
-	}
1992
-
1993
-	$url[$profondeur] = url_de_($http, $host, $GLOBALS['REQUEST_URI'], $profondeur);
1994
-
1995
-	return $url[$profondeur];
1921
+    static $url = array();
1922
+    if (is_array($profondeur)) {
1923
+        return $url = $profondeur;
1924
+    }
1925
+    if ($profondeur === false) {
1926
+        return $url;
1927
+    }
1928
+
1929
+    if (is_null($profondeur)) {
1930
+        $profondeur = $GLOBALS['profondeur_url'];
1931
+    }
1932
+
1933
+    if (isset($url[$profondeur])) {
1934
+        return $url[$profondeur];
1935
+    }
1936
+
1937
+    $http = 'http';
1938
+
1939
+    if (
1940
+        isset($_SERVER["SCRIPT_URI"])
1941
+        and substr($_SERVER["SCRIPT_URI"], 0, 5) == 'https'
1942
+    ) {
1943
+        $http = 'https';
1944
+    } elseif (
1945
+        isset($_SERVER['HTTPS'])
1946
+        and test_valeur_serveur($_SERVER['HTTPS'])
1947
+    ) {
1948
+        $http = 'https';
1949
+    }
1950
+
1951
+    // note : HTTP_HOST contient le :port si necessaire
1952
+    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
1953
+    // si on n'a pas trouvé d'hôte du tout, en dernier recours on utilise adresse_site comme fallback
1954
+    if (is_null($host) and isset($GLOBALS['meta']['adresse_site'])) {
1955
+        $host = $GLOBALS['meta']['adresse_site'];
1956
+        if ($scheme = parse_url($host, PHP_URL_SCHEME)) {
1957
+            $http = $scheme;
1958
+            $host = str_replace("{$scheme}://", '', $host);
1959
+        }
1960
+    }
1961
+    if (isset($_SERVER['SERVER_PORT'])
1962
+        and $port = $_SERVER['SERVER_PORT']
1963
+        and strpos($host, ":") == false
1964
+    ) {
1965
+        if (!defined('_PORT_HTTP_STANDARD')) {
1966
+            define('_PORT_HTTP_STANDARD', '80');
1967
+        }
1968
+        if (!defined('_PORT_HTTPS_STANDARD')) {
1969
+            define('_PORT_HTTPS_STANDARD', '443');
1970
+        }
1971
+        if ($http == "http" and !in_array($port, explode(',', _PORT_HTTP_STANDARD))) {
1972
+            $host .= ":$port";
1973
+        }
1974
+        if ($http == "https" and !in_array($port, explode(',', _PORT_HTTPS_STANDARD))) {
1975
+            $host .= ":$port";
1976
+        }
1977
+    }
1978
+
1979
+    if (!$GLOBALS['REQUEST_URI']) {
1980
+        if (isset($_SERVER['REQUEST_URI'])) {
1981
+            $GLOBALS['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
1982
+        } else {
1983
+            $GLOBALS['REQUEST_URI'] = (php_sapi_name() !== 'cli') ? $_SERVER['PHP_SELF'] : '';
1984
+            if (!empty($_SERVER['QUERY_STRING'])
1985
+                and !strpos($_SERVER['REQUEST_URI'], '?')
1986
+            ) {
1987
+                $GLOBALS['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
1988
+            }
1989
+        }
1990
+    }
1991
+
1992
+    $url[$profondeur] = url_de_($http, $host, $GLOBALS['REQUEST_URI'], $profondeur);
1993
+
1994
+    return $url[$profondeur];
1996 1995
 }
1997 1996
 
1998 1997
 /**
@@ -2005,26 +2004,26 @@  discard block
 block discarded – undo
2005 2004
  * @return string
2006 2005
  */
2007 2006
 function url_de_($http, $host, $request, $prof = 0) {
2008
-	$prof = max($prof, 0);
2007
+    $prof = max($prof, 0);
2009 2008
 
2010
-	$myself = ltrim($request, '/');
2011
-	# supprimer la chaine de GET
2012
-	list($myself) = explode('?', $myself);
2013
-	// vieux mode HTTP qui envoie après le nom de la methode l'URL compléte
2014
-	// protocole, "://", nom du serveur avant le path dans _SERVER["REQUEST_URI"]
2015
-	if (strpos($myself,'://') !== false) {
2016
-		$myself = explode('://',$myself);
2017
-		array_shift($myself);
2018
-		$myself = implode('://',$myself);
2019
-		$myself = explode('/',$myself);
2020
-		array_shift($myself);
2021
-		$myself = implode('/',$myself);
2022
-	}
2023
-	$url = join('/', array_slice(explode('/', $myself), 0, -1 - $prof)) . '/';
2009
+    $myself = ltrim($request, '/');
2010
+    # supprimer la chaine de GET
2011
+    list($myself) = explode('?', $myself);
2012
+    // vieux mode HTTP qui envoie après le nom de la methode l'URL compléte
2013
+    // protocole, "://", nom du serveur avant le path dans _SERVER["REQUEST_URI"]
2014
+    if (strpos($myself,'://') !== false) {
2015
+        $myself = explode('://',$myself);
2016
+        array_shift($myself);
2017
+        $myself = implode('://',$myself);
2018
+        $myself = explode('/',$myself);
2019
+        array_shift($myself);
2020
+        $myself = implode('/',$myself);
2021
+    }
2022
+    $url = join('/', array_slice(explode('/', $myself), 0, -1 - $prof)) . '/';
2024 2023
 
2025
-	$url = $http . '://' . rtrim($host, '/') . '/' . ltrim($url, '/');
2024
+    $url = $http . '://' . rtrim($host, '/') . '/' . ltrim($url, '/');
2026 2025
 
2027
-	return $url;
2026
+    return $url;
2028 2027
 }
2029 2028
 
2030 2029
 
@@ -2059,26 +2058,26 @@  discard block
 block discarded – undo
2059 2058
  * @return string URL
2060 2059
  **/
2061 2060
 function generer_url_ecrire($script = '', $args = "", $no_entities = false, $rel = false) {
2062
-	if (!$rel) {
2063
-		$rel = url_de_base() . _DIR_RESTREINT_ABS . _SPIP_ECRIRE_SCRIPT;
2064
-	} else {
2065
-		if (!is_string($rel)) {
2066
-			$rel = _DIR_RESTREINT ? _DIR_RESTREINT :
2067
-				('./' . _SPIP_ECRIRE_SCRIPT);
2068
-		}
2069
-	}
2070
-
2071
-	list($script, $ancre) = array_pad(explode('#', $script), 2, null);
2072
-	if ($script and ($script <> 'accueil' or $rel)) {
2073
-		$args = "?exec=$script" . (!$args ? '' : "&$args");
2074
-	} elseif ($args) {
2075
-		$args = "?$args";
2076
-	}
2077
-	if ($ancre) {
2078
-		$args .= "#$ancre";
2079
-	}
2080
-
2081
-	return $rel . ($no_entities ? $args : str_replace('&', '&amp;', $args));
2061
+    if (!$rel) {
2062
+        $rel = url_de_base() . _DIR_RESTREINT_ABS . _SPIP_ECRIRE_SCRIPT;
2063
+    } else {
2064
+        if (!is_string($rel)) {
2065
+            $rel = _DIR_RESTREINT ? _DIR_RESTREINT :
2066
+                ('./' . _SPIP_ECRIRE_SCRIPT);
2067
+        }
2068
+    }
2069
+
2070
+    list($script, $ancre) = array_pad(explode('#', $script), 2, null);
2071
+    if ($script and ($script <> 'accueil' or $rel)) {
2072
+        $args = "?exec=$script" . (!$args ? '' : "&$args");
2073
+    } elseif ($args) {
2074
+        $args = "?$args";
2075
+    }
2076
+    if ($ancre) {
2077
+        $args .= "#$ancre";
2078
+    }
2079
+
2080
+    return $rel . ($no_entities ? $args : str_replace('&', '&amp;', $args));
2082 2081
 }
2083 2082
 
2084 2083
 //
@@ -2100,12 +2099,12 @@  discard block
 block discarded – undo
2100 2099
  *     Nom du fichier (constante _SPIP_SCRIPT), sinon nom par défaut
2101 2100
  **/
2102 2101
 function get_spip_script($default = '') {
2103
-	# cas define('_SPIP_SCRIPT', '');
2104
-	if (_SPIP_SCRIPT) {
2105
-		return _SPIP_SCRIPT;
2106
-	} else {
2107
-		return $default;
2108
-	}
2102
+    # cas define('_SPIP_SCRIPT', '');
2103
+    if (_SPIP_SCRIPT) {
2104
+        return _SPIP_SCRIPT;
2105
+    } else {
2106
+        return $default;
2107
+    }
2109 2108
 }
2110 2109
 
2111 2110
 /**
@@ -2134,39 +2133,39 @@  discard block
 block discarded – undo
2134 2133
  * @return string URL
2135 2134
  **/
2136 2135
 function generer_url_public($script = '', $args = "", $no_entities = false, $rel = true, $action = '') {
2137
-	// si le script est une action (spip_pass, spip_inscription),
2138
-	// standardiser vers la nouvelle API
2139
-
2140
-	if (!$action) {
2141
-		$action = get_spip_script();
2142
-	}
2143
-	if ($script) {
2144
-		$action = parametre_url($action, _SPIP_PAGE, $script, '&');
2145
-	}
2146
-
2147
-	if ($args) {
2148
-		if (is_array($args)) {
2149
-			$r = '';
2150
-			foreach ($args as $k => $v) {
2151
-				$r .= '&' . $k . '=' . $v;
2152
-			}
2153
-			$args = substr($r, 1);
2154
-		}
2155
-		$action .=
2156
-			(strpos($action, '?') !== false ? '&' : '?') . $args;
2157
-	}
2158
-	if (!$no_entities) {
2159
-		$action = quote_amp($action);
2160
-	}
2161
-
2162
-	// ne pas generer une url avec /./?page= en cas d'url absolue et de _SPIP_SCRIPT vide
2163
-	return ($rel ? _DIR_RACINE . $action : rtrim(url_de_base(), '/') . preg_replace(",^/[.]/,", "/", "/$action"));
2136
+    // si le script est une action (spip_pass, spip_inscription),
2137
+    // standardiser vers la nouvelle API
2138
+
2139
+    if (!$action) {
2140
+        $action = get_spip_script();
2141
+    }
2142
+    if ($script) {
2143
+        $action = parametre_url($action, _SPIP_PAGE, $script, '&');
2144
+    }
2145
+
2146
+    if ($args) {
2147
+        if (is_array($args)) {
2148
+            $r = '';
2149
+            foreach ($args as $k => $v) {
2150
+                $r .= '&' . $k . '=' . $v;
2151
+            }
2152
+            $args = substr($r, 1);
2153
+        }
2154
+        $action .=
2155
+            (strpos($action, '?') !== false ? '&' : '?') . $args;
2156
+    }
2157
+    if (!$no_entities) {
2158
+        $action = quote_amp($action);
2159
+    }
2160
+
2161
+    // ne pas generer une url avec /./?page= en cas d'url absolue et de _SPIP_SCRIPT vide
2162
+    return ($rel ? _DIR_RACINE . $action : rtrim(url_de_base(), '/') . preg_replace(",^/[.]/,", "/", "/$action"));
2164 2163
 }
2165 2164
 
2166 2165
 // https://code.spip.net/@generer_url_prive
2167 2166
 function generer_url_prive($script, $args = "", $no_entities = false) {
2168 2167
 
2169
-	return generer_url_public($script, $args, $no_entities, false, _DIR_RESTREINT_ABS . 'prive.php');
2168
+    return generer_url_public($script, $args, $no_entities, false, _DIR_RESTREINT_ABS . 'prive.php');
2170 2169
 }
2171 2170
 
2172 2171
 // Pour les formulaires en methode POST,
@@ -2191,19 +2190,19 @@  discard block
 block discarded – undo
2191 2190
  **/
2192 2191
 function generer_form_ecrire($script, $corps, $atts = '', $submit = '') {
2193 2192
 
2194
-	$script1 = explode('&', $script);
2195
-	$script1 = reset($script1);
2193
+    $script1 = explode('&', $script);
2194
+    $script1 = reset($script1);
2196 2195
 
2197
-	return "<form action='"
2198
-	. ($script ? generer_url_ecrire($script) : '')
2199
-	. "' "
2200
-	. ($atts ? $atts : " method='post'")
2201
-	. "><div>\n"
2202
-	. "<input type='hidden' name='exec' value='$script1' />"
2203
-	. $corps
2204
-	. (!$submit ? '' :
2205
-		("<div style='text-align: " . $GLOBALS['spip_lang_right'] . "'><input class='fondo' type='submit' value=\"" . entites_html($submit) . "\" /></div>"))
2206
-	. "</div></form>\n";
2196
+    return "<form action='"
2197
+    . ($script ? generer_url_ecrire($script) : '')
2198
+    . "' "
2199
+    . ($atts ? $atts : " method='post'")
2200
+    . "><div>\n"
2201
+    . "<input type='hidden' name='exec' value='$script1' />"
2202
+    . $corps
2203
+    . (!$submit ? '' :
2204
+        ("<div style='text-align: " . $GLOBALS['spip_lang_right'] . "'><input class='fondo' type='submit' value=\"" . entites_html($submit) . "\" /></div>"))
2205
+    . "</div></form>\n";
2207 2206
 }
2208 2207
 
2209 2208
 /**
@@ -2220,22 +2219,22 @@  discard block
 block discarded – undo
2220 2219
  * @return string
2221 2220
  */
2222 2221
 function generer_form_action($script, $corps, $atts = '', $public = false) {
2223
-	// si l'on est dans l'espace prive, on garde dans l'url
2224
-	// l'exec a l'origine de l'action, qui permet de savoir si il est necessaire
2225
-	// ou non de proceder a l'authentification (cas typique de l'install par exemple)
2226
-	$h = (_DIR_RACINE and !$public)
2227
-		? generer_url_ecrire(_request('exec'))
2228
-		: generer_url_public();
2222
+    // si l'on est dans l'espace prive, on garde dans l'url
2223
+    // l'exec a l'origine de l'action, qui permet de savoir si il est necessaire
2224
+    // ou non de proceder a l'authentification (cas typique de l'install par exemple)
2225
+    $h = (_DIR_RACINE and !$public)
2226
+        ? generer_url_ecrire(_request('exec'))
2227
+        : generer_url_public();
2229 2228
 
2230
-	return "\n<form action='" .
2231
-	$h .
2232
-	"'" .
2233
-	$atts .
2234
-	">\n" .
2235
-	"<div>" .
2236
-	"\n<input type='hidden' name='action' value='$script' />" .
2237
-	$corps .
2238
-	"</div></form>";
2229
+    return "\n<form action='" .
2230
+    $h .
2231
+    "'" .
2232
+    $atts .
2233
+    ">\n" .
2234
+    "<div>" .
2235
+    "\n<input type='hidden' name='action' value='$script' />" .
2236
+    $corps .
2237
+    "</div></form>";
2239 2238
 }
2240 2239
 
2241 2240
 /**
@@ -2254,22 +2253,22 @@  discard block
 block discarded – undo
2254 2253
  *     URL
2255 2254
  */
2256 2255
 function generer_url_action($script, $args = "", $no_entities = false, $public = false) {
2257
-	// si l'on est dans l'espace prive, on garde dans l'url
2258
-	// l'exec a l'origine de l'action, qui permet de savoir si il est necessaire
2259
-	// ou non de proceder a l'authentification (cas typique de l'install par exemple)
2260
-	$url = (_DIR_RACINE and !$public)
2261
-		? generer_url_ecrire(_request('exec'))
2262
-		: generer_url_public('', '', false, false);
2263
-	$url = parametre_url($url, 'action', $script);
2264
-	if ($args) {
2265
-		$url .= quote_amp('&' . $args);
2266
-	}
2256
+    // si l'on est dans l'espace prive, on garde dans l'url
2257
+    // l'exec a l'origine de l'action, qui permet de savoir si il est necessaire
2258
+    // ou non de proceder a l'authentification (cas typique de l'install par exemple)
2259
+    $url = (_DIR_RACINE and !$public)
2260
+        ? generer_url_ecrire(_request('exec'))
2261
+        : generer_url_public('', '', false, false);
2262
+    $url = parametre_url($url, 'action', $script);
2263
+    if ($args) {
2264
+        $url .= quote_amp('&' . $args);
2265
+    }
2267 2266
 
2268
-	if ($no_entities) {
2269
-		$url = str_replace('&amp;', '&', $url);
2270
-	}
2267
+    if ($no_entities) {
2268
+        $url = str_replace('&amp;', '&', $url);
2269
+    }
2271 2270
 
2272
-	return $url;
2271
+    return $url;
2273 2272
 }
2274 2273
 
2275 2274
 
@@ -2282,8 +2281,8 @@  discard block
 block discarded – undo
2282 2281
  * @param string $ta Répertoire temporaire accessible
2283 2282
  */
2284 2283
 function spip_initialisation($pi = null, $pa = null, $ti = null, $ta = null) {
2285
-	spip_initialisation_core($pi, $pa, $ti, $ta);
2286
-	spip_initialisation_suite();
2284
+    spip_initialisation_core($pi, $pa, $ti, $ta);
2285
+    spip_initialisation_suite();
2287 2286
 }
2288 2287
 
2289 2288
 /**
@@ -2303,315 +2302,315 @@  discard block
 block discarded – undo
2303 2302
  * @param string $ta Répertoire temporaire accessible
2304 2303
  */
2305 2304
 function spip_initialisation_core($pi = null, $pa = null, $ti = null, $ta = null) {
2306
-	static $too_late = 0;
2307
-	if ($too_late++) {
2308
-		return;
2309
-	}
2310
-
2311
-	// Declaration des repertoires
2312
-
2313
-	// le nom du repertoire plugins/ activables/desactivables
2314
-	if (!defined('_DIR_PLUGINS')) {
2315
-		define('_DIR_PLUGINS', _DIR_RACINE . "plugins/");
2316
-	}
2317
-
2318
-	// le nom du repertoire des extensions/ permanentes du core, toujours actives
2319
-	if (!defined('_DIR_PLUGINS_DIST')) {
2320
-		define('_DIR_PLUGINS_DIST', _DIR_RACINE . "plugins-dist/");
2321
-	}
2322
-
2323
-	// le nom du repertoire des librairies
2324
-	if (!defined('_DIR_LIB')) {
2325
-		define('_DIR_LIB', _DIR_RACINE . "lib/");
2326
-	}
2327
-
2328
-	if (!defined('_DIR_IMG')) {
2329
-		define('_DIR_IMG', $pa);
2330
-	}
2331
-	if (!defined('_DIR_LOGOS')) {
2332
-		define('_DIR_LOGOS', $pa);
2333
-	}
2334
-	if (!defined('_DIR_IMG_ICONES')) {
2335
-		define('_DIR_IMG_ICONES', _DIR_LOGOS . "icones/");
2336
-	}
2337
-
2338
-	if (!defined('_DIR_DUMP')) {
2339
-		define('_DIR_DUMP', $ti . "dump/");
2340
-	}
2341
-	if (!defined('_DIR_SESSIONS')) {
2342
-		define('_DIR_SESSIONS', $ti . "sessions/");
2343
-	}
2344
-	if (!defined('_DIR_TRANSFERT')) {
2345
-		define('_DIR_TRANSFERT', $ti . "upload/");
2346
-	}
2347
-	if (!defined('_DIR_CACHE')) {
2348
-		define('_DIR_CACHE', $ti . "cache/");
2349
-	}
2350
-	if (!defined('_DIR_CACHE_XML')) {
2351
-		define('_DIR_CACHE_XML', _DIR_CACHE . "xml/");
2352
-	}
2353
-	if (!defined('_DIR_SKELS')) {
2354
-		define('_DIR_SKELS', _DIR_CACHE . "skel/");
2355
-	}
2356
-	if (!defined('_DIR_AIDE')) {
2357
-		define('_DIR_AIDE', _DIR_CACHE . "aide/");
2358
-	}
2359
-	if (!defined('_DIR_TMP')) {
2360
-		define('_DIR_TMP', $ti);
2361
-	}
2362
-
2363
-	if (!defined('_DIR_VAR')) {
2364
-		define('_DIR_VAR', $ta);
2365
-	}
2366
-
2367
-	if (!defined('_DIR_ETC')) {
2368
-		define('_DIR_ETC', $pi);
2369
-	}
2370
-	if (!defined('_DIR_CONNECT')) {
2371
-		define('_DIR_CONNECT', $pi);
2372
-	}
2373
-	if (!defined('_DIR_CHMOD')) {
2374
-		define('_DIR_CHMOD', $pi);
2375
-	}
2376
-
2377
-	if (!isset($GLOBALS['test_dirs']))
2378
-		// Pas $pi car il est bon de le mettre hors ecriture apres intstall
2379
-		// il sera rajoute automatiquement si besoin a l'etape 2 de l'install
2380
-	{
2381
-		$GLOBALS['test_dirs'] = array($pa, $ti, $ta);
2382
-	}
2383
-
2384
-	// Declaration des fichiers
2385
-
2386
-	if (!defined('_CACHE_PLUGINS_PATH')) {
2387
-		define('_CACHE_PLUGINS_PATH', _DIR_CACHE . "charger_plugins_chemins.php");
2388
-	}
2389
-	if (!defined('_CACHE_PLUGINS_OPT')) {
2390
-		define('_CACHE_PLUGINS_OPT', _DIR_CACHE . "charger_plugins_options.php");
2391
-	}
2392
-	if (!defined('_CACHE_PLUGINS_FCT')) {
2393
-		define('_CACHE_PLUGINS_FCT', _DIR_CACHE . "charger_plugins_fonctions.php");
2394
-	}
2395
-	if (!defined('_CACHE_PIPELINES')) {
2396
-		define('_CACHE_PIPELINES', _DIR_CACHE . "charger_pipelines.php");
2397
-	}
2398
-	if (!defined('_CACHE_CHEMIN')) {
2399
-		define('_CACHE_CHEMIN', _DIR_CACHE . "chemin.txt");
2400
-	}
2401
-
2402
-	# attention .php obligatoire pour ecrire_fichier_securise
2403
-	if (!defined('_FILE_META')) {
2404
-		define('_FILE_META', $ti . 'meta_cache.php');
2405
-	}
2406
-	if (!defined('_DIR_LOG')) {
2407
-		define('_DIR_LOG', _DIR_TMP . 'log/');
2408
-	}
2409
-	if (!defined('_FILE_LOG')) {
2410
-		define('_FILE_LOG', 'spip');
2411
-	}
2412
-	if (!defined('_FILE_LOG_SUFFIX')) {
2413
-		define('_FILE_LOG_SUFFIX', '.log');
2414
-	}
2415
-
2416
-	// Le fichier de connexion a la base de donnees
2417
-	// tient compte des anciennes versions (inc_connect...)
2418
-	if (!defined('_FILE_CONNECT_INS')) {
2419
-		define('_FILE_CONNECT_INS', 'connect');
2420
-	}
2421
-	if (!defined('_FILE_CONNECT')) {
2422
-		define('_FILE_CONNECT',
2423
-		(@is_readable($f = _DIR_CONNECT . _FILE_CONNECT_INS . '.php') ? $f
2424
-			: (@is_readable($f = _DIR_RESTREINT . 'inc_connect.php') ? $f
2425
-				: false)));
2426
-	}
2427
-
2428
-	// Le fichier de reglages des droits
2429
-	if (!defined('_FILE_CHMOD_INS')) {
2430
-		define('_FILE_CHMOD_INS', 'chmod');
2431
-	}
2432
-	if (!defined('_FILE_CHMOD')) {
2433
-		define('_FILE_CHMOD',
2434
-		(@is_readable($f = _DIR_CHMOD . _FILE_CHMOD_INS . '.php') ? $f
2435
-			: false));
2436
-	}
2437
-
2438
-	if (!defined('_FILE_LDAP')) {
2439
-		define('_FILE_LDAP', 'ldap.php');
2440
-	}
2441
-
2442
-	if (!defined('_FILE_TMP_SUFFIX')) {
2443
-		define('_FILE_TMP_SUFFIX', '.tmp.php');
2444
-	}
2445
-	if (!defined('_FILE_CONNECT_TMP')) {
2446
-		define('_FILE_CONNECT_TMP', _DIR_CONNECT . _FILE_CONNECT_INS . _FILE_TMP_SUFFIX);
2447
-	}
2448
-	if (!defined('_FILE_CHMOD_TMP')) {
2449
-		define('_FILE_CHMOD_TMP', _DIR_CHMOD . _FILE_CHMOD_INS . _FILE_TMP_SUFFIX);
2450
-	}
2451
-
2452
-	// Definition des droits d'acces en ecriture
2453
-	if (!defined('_SPIP_CHMOD') and _FILE_CHMOD) {
2454
-		include_once _FILE_CHMOD;
2455
-	}
2456
-
2457
-	// Se mefier des fichiers mal remplis!
2458
-	if (!defined('_SPIP_CHMOD')) {
2459
-		define('_SPIP_CHMOD', 0777);
2460
-	}
2461
-
2462
-	if (!defined('_DEFAULT_CHARSET')) {
2463
-		/** Le charset par défaut lors de l'installation */
2464
-		define('_DEFAULT_CHARSET', 'utf-8');
2465
-	}
2466
-	if (!defined('_ROOT_PLUGINS')) {
2467
-		define('_ROOT_PLUGINS', _ROOT_RACINE . "plugins/");
2468
-	}
2469
-	if (!defined('_ROOT_PLUGINS_DIST')) {
2470
-		define('_ROOT_PLUGINS_DIST', _ROOT_RACINE . "plugins-dist/");
2471
-	}
2472
-	if (!defined('_ROOT_PLUGINS_SUPPL') && defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
2473
-		define('_ROOT_PLUGINS_SUPPL', _ROOT_RACINE . str_replace(_DIR_RACINE, '', _DIR_PLUGINS_SUPPL));
2474
-	}
2475
-
2476
-	// La taille des Log
2477
-	if (!defined('_MAX_LOG')) {
2478
-		define('_MAX_LOG', 100);
2479
-	}
2480
-
2481
-	// Sommes-nous dans l'empire du Mal ?
2482
-	// (ou sous le signe du Pingouin, ascendant GNU ?)
2483
-	if (isset($_SERVER['SERVER_SOFTWARE']) and strpos($_SERVER['SERVER_SOFTWARE'], '(Win') !== false) {
2484
-		if (!defined('_OS_SERVEUR')) {
2485
-			define('_OS_SERVEUR', 'windows');
2486
-		}
2487
-		if (!defined('_SPIP_LOCK_MODE')) {
2488
-			define('_SPIP_LOCK_MODE', 1);
2489
-		} // utiliser le flock php
2490
-	} else {
2491
-		if (!defined('_OS_SERVEUR')) {
2492
-			define('_OS_SERVEUR', '');
2493
-		}
2494
-		if (!defined('_SPIP_LOCK_MODE')) {
2495
-			define('_SPIP_LOCK_MODE', 1);
2496
-		} // utiliser le flock php
2497
-		#if (!defined('_SPIP_LOCK_MODE')) define('_SPIP_LOCK_MODE',2); // utiliser le nfslock de spip mais link() est tres souvent interdite
2498
-	}
2499
-
2500
-	// Langue par defaut
2501
-	if (!defined('_LANGUE_PAR_DEFAUT')) {
2502
-		define('_LANGUE_PAR_DEFAUT', 'fr');
2503
-	}
2504
-
2505
-	//
2506
-	// Module de lecture/ecriture/suppression de fichiers utilisant flock()
2507
-	// (non surchargeable en l'etat ; attention si on utilise include_spip()
2508
-	// pour le rendre surchargeable, on va provoquer un reecriture
2509
-	// systematique du noyau ou une baisse de perfs => a etudier)
2510
-	include_once _ROOT_RESTREINT . 'inc/flock.php';
2511
-
2512
-	// charger tout de suite le path et son cache
2513
-	load_path_cache();
2514
-
2515
-	// *********** traiter les variables ************
2516
-
2517
-	//
2518
-	// Securite
2519
-	//
2520
-
2521
-	// Ne pas se faire manger par un bug php qui accepte ?GLOBALS[truc]=toto
2522
-	if (isset($_REQUEST['GLOBALS'])) {
2523
-		die();
2524
-	}
2525
-	// nettoyer les magic quotes \' et les caracteres nuls %00
2526
-	spip_desinfecte($_GET);
2527
-	spip_desinfecte($_POST);
2528
-	spip_desinfecte($_COOKIE);
2529
-	spip_desinfecte($_REQUEST);
2530
-
2531
-	// appliquer le cookie_prefix
2532
-	if ($GLOBALS['cookie_prefix'] != 'spip') {
2533
-		include_spip('inc/cookie');
2534
-		recuperer_cookies_spip($GLOBALS['cookie_prefix']);
2535
-	}
2536
-
2537
-	//
2538
-	// Capacites php (en fonction de la version)
2539
-	//
2540
-	$GLOBALS['flag_ob'] = (function_exists("ob_start")
2541
-		&& function_exists("ini_get")
2542
-		&& !strstr(@ini_get('disable_functions'), 'ob_'));
2543
-	$GLOBALS['flag_sapi_name'] = function_exists("php_sapi_name");
2544
-	$GLOBALS['flag_get_cfg_var'] = (@get_cfg_var('error_reporting') != "");
2545
-	$GLOBALS['flag_upload'] = (!$GLOBALS['flag_get_cfg_var'] ||
2546
-		(get_cfg_var('upload_max_filesize') > 0));
2547
-
2548
-
2549
-	// Compatibilite avec serveurs ne fournissant pas $REQUEST_URI
2550
-	if (isset($_SERVER['REQUEST_URI'])) {
2551
-		$GLOBALS['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
2552
-	} else {
2553
-		$GLOBALS['REQUEST_URI'] = (php_sapi_name() !== 'cli') ? $_SERVER['PHP_SELF'] : '';
2554
-		if (!empty($_SERVER['QUERY_STRING'])
2555
-			and !strpos($_SERVER['REQUEST_URI'], '?')
2556
-		) {
2557
-			$GLOBALS['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
2558
-		}
2559
-	}
2560
-
2561
-	// Duree de validite de l'alea pour les cookies et ce qui s'ensuit.
2562
-	if (!defined('_RENOUVELLE_ALEA')) {
2563
-		define('_RENOUVELLE_ALEA', 12 * 3600);
2564
-	}
2565
-	if (!defined('_DUREE_COOKIE_ADMIN')) {
2566
-		define('_DUREE_COOKIE_ADMIN', 14 * 24 * 3600);
2567
-	}
2568
-
2569
-	// charger les meta si possible et renouveller l'alea au besoin
2570
-	// charge aussi effacer_meta et ecrire_meta
2571
-	$inc_meta = charger_fonction('meta', 'inc');
2572
-	$inc_meta();
2573
-
2574
-	// nombre de repertoires depuis la racine
2575
-	// on compare a l'adresse de spip.php : $_SERVER["SCRIPT_NAME"]
2576
-	// ou a defaut celle donnee en meta ; (mais si celle-ci est fausse
2577
-	// le calcul est faux)
2578
-	if (!_DIR_RESTREINT) {
2579
-		$GLOBALS['profondeur_url'] = 1;
2580
-	} else {
2581
-		$uri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI']) : '';
2582
-		$uri_ref = $_SERVER["SCRIPT_NAME"];
2583
-		if (!$uri_ref
2584
-			// si on est appele avec un autre ti, on est sans doute en mutu
2585
-			// si jamais c'est de la mutu avec sous rep, on est perdu si on se fie
2586
-			// a spip.php qui est a la racine du spip, et vue qu'on sait pas se reperer
2587
-			// s'en remettre a l'adresse du site. alea jacta est.
2588
-			or $ti !== _NOM_TEMPORAIRES_INACCESSIBLES
2589
-		) {
2590
-
2591
-			if (isset($GLOBALS['meta']['adresse_site'])) {
2592
-				$uri_ref = parse_url($GLOBALS['meta']['adresse_site']);
2593
-				$uri_ref = (isset($uri_ref['path']) ? $uri_ref['path'] : '') . '/';
2594
-			} else {
2595
-				$uri_ref = "";
2596
-			}
2597
-		}
2598
-		if (!$uri or !$uri_ref) {
2599
-			$GLOBALS['profondeur_url'] = 0;
2600
-		} else {
2601
-			$GLOBALS['profondeur_url'] = max(0,
2602
-				substr_count($uri[0], '/')
2603
-				- substr_count($uri_ref, '/'));
2604
-		}
2605
-	}
2606
-	// s'il y a un cookie ou PHP_AUTH, initialiser visiteur_session
2607
-	if (_FILE_CONNECT) {
2608
-		if (verifier_visiteur() == '0minirezo'
2609
-			// si c'est un admin sans cookie admin, il faut ignorer le cache chemin !
2610
-			and !isset($_COOKIE['spip_admin'])
2611
-		) {
2612
-			clear_path_cache();
2613
-		}
2614
-	}
2305
+    static $too_late = 0;
2306
+    if ($too_late++) {
2307
+        return;
2308
+    }
2309
+
2310
+    // Declaration des repertoires
2311
+
2312
+    // le nom du repertoire plugins/ activables/desactivables
2313
+    if (!defined('_DIR_PLUGINS')) {
2314
+        define('_DIR_PLUGINS', _DIR_RACINE . "plugins/");
2315
+    }
2316
+
2317
+    // le nom du repertoire des extensions/ permanentes du core, toujours actives
2318
+    if (!defined('_DIR_PLUGINS_DIST')) {
2319
+        define('_DIR_PLUGINS_DIST', _DIR_RACINE . "plugins-dist/");
2320
+    }
2321
+
2322
+    // le nom du repertoire des librairies
2323
+    if (!defined('_DIR_LIB')) {
2324
+        define('_DIR_LIB', _DIR_RACINE . "lib/");
2325
+    }
2326
+
2327
+    if (!defined('_DIR_IMG')) {
2328
+        define('_DIR_IMG', $pa);
2329
+    }
2330
+    if (!defined('_DIR_LOGOS')) {
2331
+        define('_DIR_LOGOS', $pa);
2332
+    }
2333
+    if (!defined('_DIR_IMG_ICONES')) {
2334
+        define('_DIR_IMG_ICONES', _DIR_LOGOS . "icones/");
2335
+    }
2336
+
2337
+    if (!defined('_DIR_DUMP')) {
2338
+        define('_DIR_DUMP', $ti . "dump/");
2339
+    }
2340
+    if (!defined('_DIR_SESSIONS')) {
2341
+        define('_DIR_SESSIONS', $ti . "sessions/");
2342
+    }
2343
+    if (!defined('_DIR_TRANSFERT')) {
2344
+        define('_DIR_TRANSFERT', $ti . "upload/");
2345
+    }
2346
+    if (!defined('_DIR_CACHE')) {
2347
+        define('_DIR_CACHE', $ti . "cache/");
2348
+    }
2349
+    if (!defined('_DIR_CACHE_XML')) {
2350
+        define('_DIR_CACHE_XML', _DIR_CACHE . "xml/");
2351
+    }
2352
+    if (!defined('_DIR_SKELS')) {
2353
+        define('_DIR_SKELS', _DIR_CACHE . "skel/");
2354
+    }
2355
+    if (!defined('_DIR_AIDE')) {
2356
+        define('_DIR_AIDE', _DIR_CACHE . "aide/");
2357
+    }
2358
+    if (!defined('_DIR_TMP')) {
2359
+        define('_DIR_TMP', $ti);
2360
+    }
2361
+
2362
+    if (!defined('_DIR_VAR')) {
2363
+        define('_DIR_VAR', $ta);
2364
+    }
2365
+
2366
+    if (!defined('_DIR_ETC')) {
2367
+        define('_DIR_ETC', $pi);
2368
+    }
2369
+    if (!defined('_DIR_CONNECT')) {
2370
+        define('_DIR_CONNECT', $pi);
2371
+    }
2372
+    if (!defined('_DIR_CHMOD')) {
2373
+        define('_DIR_CHMOD', $pi);
2374
+    }
2375
+
2376
+    if (!isset($GLOBALS['test_dirs']))
2377
+        // Pas $pi car il est bon de le mettre hors ecriture apres intstall
2378
+        // il sera rajoute automatiquement si besoin a l'etape 2 de l'install
2379
+    {
2380
+        $GLOBALS['test_dirs'] = array($pa, $ti, $ta);
2381
+    }
2382
+
2383
+    // Declaration des fichiers
2384
+
2385
+    if (!defined('_CACHE_PLUGINS_PATH')) {
2386
+        define('_CACHE_PLUGINS_PATH', _DIR_CACHE . "charger_plugins_chemins.php");
2387
+    }
2388
+    if (!defined('_CACHE_PLUGINS_OPT')) {
2389
+        define('_CACHE_PLUGINS_OPT', _DIR_CACHE . "charger_plugins_options.php");
2390
+    }
2391
+    if (!defined('_CACHE_PLUGINS_FCT')) {
2392
+        define('_CACHE_PLUGINS_FCT', _DIR_CACHE . "charger_plugins_fonctions.php");
2393
+    }
2394
+    if (!defined('_CACHE_PIPELINES')) {
2395
+        define('_CACHE_PIPELINES', _DIR_CACHE . "charger_pipelines.php");
2396
+    }
2397
+    if (!defined('_CACHE_CHEMIN')) {
2398
+        define('_CACHE_CHEMIN', _DIR_CACHE . "chemin.txt");
2399
+    }
2400
+
2401
+    # attention .php obligatoire pour ecrire_fichier_securise
2402
+    if (!defined('_FILE_META')) {
2403
+        define('_FILE_META', $ti . 'meta_cache.php');
2404
+    }
2405
+    if (!defined('_DIR_LOG')) {
2406
+        define('_DIR_LOG', _DIR_TMP . 'log/');
2407
+    }
2408
+    if (!defined('_FILE_LOG')) {
2409
+        define('_FILE_LOG', 'spip');
2410
+    }
2411
+    if (!defined('_FILE_LOG_SUFFIX')) {
2412
+        define('_FILE_LOG_SUFFIX', '.log');
2413
+    }
2414
+
2415
+    // Le fichier de connexion a la base de donnees
2416
+    // tient compte des anciennes versions (inc_connect...)
2417
+    if (!defined('_FILE_CONNECT_INS')) {
2418
+        define('_FILE_CONNECT_INS', 'connect');
2419
+    }
2420
+    if (!defined('_FILE_CONNECT')) {
2421
+        define('_FILE_CONNECT',
2422
+        (@is_readable($f = _DIR_CONNECT . _FILE_CONNECT_INS . '.php') ? $f
2423
+            : (@is_readable($f = _DIR_RESTREINT . 'inc_connect.php') ? $f
2424
+                : false)));
2425
+    }
2426
+
2427
+    // Le fichier de reglages des droits
2428
+    if (!defined('_FILE_CHMOD_INS')) {
2429
+        define('_FILE_CHMOD_INS', 'chmod');
2430
+    }
2431
+    if (!defined('_FILE_CHMOD')) {
2432
+        define('_FILE_CHMOD',
2433
+        (@is_readable($f = _DIR_CHMOD . _FILE_CHMOD_INS . '.php') ? $f
2434
+            : false));
2435
+    }
2436
+
2437
+    if (!defined('_FILE_LDAP')) {
2438
+        define('_FILE_LDAP', 'ldap.php');
2439
+    }
2440
+
2441
+    if (!defined('_FILE_TMP_SUFFIX')) {
2442
+        define('_FILE_TMP_SUFFIX', '.tmp.php');
2443
+    }
2444
+    if (!defined('_FILE_CONNECT_TMP')) {
2445
+        define('_FILE_CONNECT_TMP', _DIR_CONNECT . _FILE_CONNECT_INS . _FILE_TMP_SUFFIX);
2446
+    }
2447
+    if (!defined('_FILE_CHMOD_TMP')) {
2448
+        define('_FILE_CHMOD_TMP', _DIR_CHMOD . _FILE_CHMOD_INS . _FILE_TMP_SUFFIX);
2449
+    }
2450
+
2451
+    // Definition des droits d'acces en ecriture
2452
+    if (!defined('_SPIP_CHMOD') and _FILE_CHMOD) {
2453
+        include_once _FILE_CHMOD;
2454
+    }
2455
+
2456
+    // Se mefier des fichiers mal remplis!
2457
+    if (!defined('_SPIP_CHMOD')) {
2458
+        define('_SPIP_CHMOD', 0777);
2459
+    }
2460
+
2461
+    if (!defined('_DEFAULT_CHARSET')) {
2462
+        /** Le charset par défaut lors de l'installation */
2463
+        define('_DEFAULT_CHARSET', 'utf-8');
2464
+    }
2465
+    if (!defined('_ROOT_PLUGINS')) {
2466
+        define('_ROOT_PLUGINS', _ROOT_RACINE . "plugins/");
2467
+    }
2468
+    if (!defined('_ROOT_PLUGINS_DIST')) {
2469
+        define('_ROOT_PLUGINS_DIST', _ROOT_RACINE . "plugins-dist/");
2470
+    }
2471
+    if (!defined('_ROOT_PLUGINS_SUPPL') && defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
2472
+        define('_ROOT_PLUGINS_SUPPL', _ROOT_RACINE . str_replace(_DIR_RACINE, '', _DIR_PLUGINS_SUPPL));
2473
+    }
2474
+
2475
+    // La taille des Log
2476
+    if (!defined('_MAX_LOG')) {
2477
+        define('_MAX_LOG', 100);
2478
+    }
2479
+
2480
+    // Sommes-nous dans l'empire du Mal ?
2481
+    // (ou sous le signe du Pingouin, ascendant GNU ?)
2482
+    if (isset($_SERVER['SERVER_SOFTWARE']) and strpos($_SERVER['SERVER_SOFTWARE'], '(Win') !== false) {
2483
+        if (!defined('_OS_SERVEUR')) {
2484
+            define('_OS_SERVEUR', 'windows');
2485
+        }
2486
+        if (!defined('_SPIP_LOCK_MODE')) {
2487
+            define('_SPIP_LOCK_MODE', 1);
2488
+        } // utiliser le flock php
2489
+    } else {
2490
+        if (!defined('_OS_SERVEUR')) {
2491
+            define('_OS_SERVEUR', '');
2492
+        }
2493
+        if (!defined('_SPIP_LOCK_MODE')) {
2494
+            define('_SPIP_LOCK_MODE', 1);
2495
+        } // utiliser le flock php
2496
+        #if (!defined('_SPIP_LOCK_MODE')) define('_SPIP_LOCK_MODE',2); // utiliser le nfslock de spip mais link() est tres souvent interdite
2497
+    }
2498
+
2499
+    // Langue par defaut
2500
+    if (!defined('_LANGUE_PAR_DEFAUT')) {
2501
+        define('_LANGUE_PAR_DEFAUT', 'fr');
2502
+    }
2503
+
2504
+    //
2505
+    // Module de lecture/ecriture/suppression de fichiers utilisant flock()
2506
+    // (non surchargeable en l'etat ; attention si on utilise include_spip()
2507
+    // pour le rendre surchargeable, on va provoquer un reecriture
2508
+    // systematique du noyau ou une baisse de perfs => a etudier)
2509
+    include_once _ROOT_RESTREINT . 'inc/flock.php';
2510
+
2511
+    // charger tout de suite le path et son cache
2512
+    load_path_cache();
2513
+
2514
+    // *********** traiter les variables ************
2515
+
2516
+    //
2517
+    // Securite
2518
+    //
2519
+
2520
+    // Ne pas se faire manger par un bug php qui accepte ?GLOBALS[truc]=toto
2521
+    if (isset($_REQUEST['GLOBALS'])) {
2522
+        die();
2523
+    }
2524
+    // nettoyer les magic quotes \' et les caracteres nuls %00
2525
+    spip_desinfecte($_GET);
2526
+    spip_desinfecte($_POST);
2527
+    spip_desinfecte($_COOKIE);
2528
+    spip_desinfecte($_REQUEST);
2529
+
2530
+    // appliquer le cookie_prefix
2531
+    if ($GLOBALS['cookie_prefix'] != 'spip') {
2532
+        include_spip('inc/cookie');
2533
+        recuperer_cookies_spip($GLOBALS['cookie_prefix']);
2534
+    }
2535
+
2536
+    //
2537
+    // Capacites php (en fonction de la version)
2538
+    //
2539
+    $GLOBALS['flag_ob'] = (function_exists("ob_start")
2540
+        && function_exists("ini_get")
2541
+        && !strstr(@ini_get('disable_functions'), 'ob_'));
2542
+    $GLOBALS['flag_sapi_name'] = function_exists("php_sapi_name");
2543
+    $GLOBALS['flag_get_cfg_var'] = (@get_cfg_var('error_reporting') != "");
2544
+    $GLOBALS['flag_upload'] = (!$GLOBALS['flag_get_cfg_var'] ||
2545
+        (get_cfg_var('upload_max_filesize') > 0));
2546
+
2547
+
2548
+    // Compatibilite avec serveurs ne fournissant pas $REQUEST_URI
2549
+    if (isset($_SERVER['REQUEST_URI'])) {
2550
+        $GLOBALS['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
2551
+    } else {
2552
+        $GLOBALS['REQUEST_URI'] = (php_sapi_name() !== 'cli') ? $_SERVER['PHP_SELF'] : '';
2553
+        if (!empty($_SERVER['QUERY_STRING'])
2554
+            and !strpos($_SERVER['REQUEST_URI'], '?')
2555
+        ) {
2556
+            $GLOBALS['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
2557
+        }
2558
+    }
2559
+
2560
+    // Duree de validite de l'alea pour les cookies et ce qui s'ensuit.
2561
+    if (!defined('_RENOUVELLE_ALEA')) {
2562
+        define('_RENOUVELLE_ALEA', 12 * 3600);
2563
+    }
2564
+    if (!defined('_DUREE_COOKIE_ADMIN')) {
2565
+        define('_DUREE_COOKIE_ADMIN', 14 * 24 * 3600);
2566
+    }
2567
+
2568
+    // charger les meta si possible et renouveller l'alea au besoin
2569
+    // charge aussi effacer_meta et ecrire_meta
2570
+    $inc_meta = charger_fonction('meta', 'inc');
2571
+    $inc_meta();
2572
+
2573
+    // nombre de repertoires depuis la racine
2574
+    // on compare a l'adresse de spip.php : $_SERVER["SCRIPT_NAME"]
2575
+    // ou a defaut celle donnee en meta ; (mais si celle-ci est fausse
2576
+    // le calcul est faux)
2577
+    if (!_DIR_RESTREINT) {
2578
+        $GLOBALS['profondeur_url'] = 1;
2579
+    } else {
2580
+        $uri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI']) : '';
2581
+        $uri_ref = $_SERVER["SCRIPT_NAME"];
2582
+        if (!$uri_ref
2583
+            // si on est appele avec un autre ti, on est sans doute en mutu
2584
+            // si jamais c'est de la mutu avec sous rep, on est perdu si on se fie
2585
+            // a spip.php qui est a la racine du spip, et vue qu'on sait pas se reperer
2586
+            // s'en remettre a l'adresse du site. alea jacta est.
2587
+            or $ti !== _NOM_TEMPORAIRES_INACCESSIBLES
2588
+        ) {
2589
+
2590
+            if (isset($GLOBALS['meta']['adresse_site'])) {
2591
+                $uri_ref = parse_url($GLOBALS['meta']['adresse_site']);
2592
+                $uri_ref = (isset($uri_ref['path']) ? $uri_ref['path'] : '') . '/';
2593
+            } else {
2594
+                $uri_ref = "";
2595
+            }
2596
+        }
2597
+        if (!$uri or !$uri_ref) {
2598
+            $GLOBALS['profondeur_url'] = 0;
2599
+        } else {
2600
+            $GLOBALS['profondeur_url'] = max(0,
2601
+                substr_count($uri[0], '/')
2602
+                - substr_count($uri_ref, '/'));
2603
+        }
2604
+    }
2605
+    // s'il y a un cookie ou PHP_AUTH, initialiser visiteur_session
2606
+    if (_FILE_CONNECT) {
2607
+        if (verifier_visiteur() == '0minirezo'
2608
+            // si c'est un admin sans cookie admin, il faut ignorer le cache chemin !
2609
+            and !isset($_COOKIE['spip_admin'])
2610
+        ) {
2611
+            clear_path_cache();
2612
+        }
2613
+    }
2615 2614
 
2616 2615
 }
2617 2616
 
@@ -2621,174 +2620,174 @@  discard block
 block discarded – undo
2621 2620
  *
2622 2621
  */
2623 2622
 function spip_initialisation_suite() {
2624
-	static $too_late = 0;
2625
-	if ($too_late++) {
2626
-		return;
2627
-	}
2628
-
2629
-	// taille mini des login
2630
-	if (!defined('_LOGIN_TROP_COURT')) {
2631
-		define('_LOGIN_TROP_COURT', 4);
2632
-	}
2633
-
2634
-	// la taille maxi des logos (0 : pas de limite) (pas de define par defaut, ce n'est pas utile)
2635
-	#if (!defined('_LOGO_MAX_SIZE')) define('_LOGO_MAX_SIZE', 0); # poids en ko
2636
-	#if (!defined('_LOGO_MAX_WIDTH')) define('_LOGO_MAX_WIDTH', 0); # largeur en pixels
2637
-	#if (!defined('_LOGO_MAX_HEIGHT')) define('_LOGO_MAX_HEIGHT', 0); # hauteur en pixels
2638
-
2639
-	// la taille maxi des images (0 : pas de limite) (pas de define par defaut, ce n'est pas utile)
2640
-	#if (!defined('_DOC_MAX_SIZE')) define('_DOC_MAX_SIZE', 0); # poids en ko
2641
-	#if (!defined('_IMG_MAX_SIZE')) define('_IMG_MAX_SIZE', 0); # poids en ko
2642
-	#if (!defined('_IMG_MAX_WIDTH')) define('_IMG_MAX_WIDTH', 0); # largeur en pixels
2643
-	#if (!defined('_IMG_MAX_HEIGHT')) define('_IMG_MAX_HEIGHT', 0); # hauteur en pixels
2644
-
2645
-	if (!defined('_PASS_LONGUEUR_MINI')) {
2646
-		define('_PASS_LONGUEUR_MINI', 6);
2647
-	}
2648
-
2649
-
2650
-	// Qualite des images calculees automatiquement. C'est un nombre entre 0 et 100, meme pour imagick (on ramene a 0..1 par la suite)
2651
-	if (!defined('_IMG_QUALITE')) {
2652
-		define('_IMG_QUALITE', 85);
2653
-	} # valeur par defaut
2654
-	if (!defined('_IMG_GD_QUALITE')) {
2655
-		define('_IMG_GD_QUALITE', _IMG_QUALITE);
2656
-	} # surcharge pour la lib GD
2657
-	if (!defined('_IMG_CONVERT_QUALITE')) {
2658
-		define('_IMG_CONVERT_QUALITE', _IMG_QUALITE);
2659
-	} # surcharge pour imagick en ligne de commande
2660
-	// Historiquement la valeur pour imagick semble differente. Si ca n'est pas necessaire, il serait preferable de garder _IMG_QUALITE
2661
-	if (!defined('_IMG_IMAGICK_QUALITE')) {
2662
-		define('_IMG_IMAGICK_QUALITE', 75);
2663
-	} # surcharge pour imagick en PHP
2664
-
2665
-	if (!defined('_COPIE_LOCALE_MAX_SIZE')) {
2666
-		define('_COPIE_LOCALE_MAX_SIZE', 33554432);
2667
-	} // poids en octet
2668
-
2669
-	// qq chaines standard
2670
-	if (!defined('_ACCESS_FILE_NAME')) {
2671
-		define('_ACCESS_FILE_NAME', '.htaccess');
2672
-	}
2673
-	if (!defined('_AUTH_USER_FILE')) {
2674
-		define('_AUTH_USER_FILE', '.htpasswd');
2675
-	}
2676
-	if (!defined('_SPIP_DUMP')) {
2677
-		define('_SPIP_DUMP', 'dump@nom_site@@[email protected]');
2678
-	}
2679
-	if (!defined('_CACHE_RUBRIQUES')) {
2680
-		/** Fichier cache pour le navigateur de rubrique du bandeau */
2681
-		define('_CACHE_RUBRIQUES', _DIR_TMP . 'menu-rubriques-cache.txt');
2682
-	}
2683
-	if (!defined('_CACHE_RUBRIQUES_MAX')) {
2684
-		/** Nombre maxi de rubriques enfants affichées pour chaque rubrique du navigateur de rubrique du bandeau */
2685
-		define('_CACHE_RUBRIQUES_MAX', 500);
2686
-	}
2687
-
2688
-	if (!defined('_EXTENSION_SQUELETTES')) {
2689
-		define('_EXTENSION_SQUELETTES', 'html');
2690
-	}
2691
-
2692
-	if (!defined('_DOCTYPE_ECRIRE')) {
2693
-		/** Définit le doctype de l’espace privé */
2694
-		define('_DOCTYPE_ECRIRE', "<!DOCTYPE html>\n");
2695
-	}
2696
-	if (!defined('_DOCTYPE_AIDE')) {
2697
-		/** Définit le doctype de l’aide en ligne */
2698
-		define('_DOCTYPE_AIDE',
2699
-		"<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Frameset//EN' 'http://www.w3.org/TR/1999/REC-html401-19991224/frameset.dtd'>");
2700
-	}
2701
-
2702
-	if (!defined('_SPIP_SCRIPT')) {
2703
-		/** L'adresse de base du site ; on peut mettre '' si la racine est gerée par
2704
-		 * le script de l'espace public, alias index.php */
2705
-		define('_SPIP_SCRIPT', 'spip.php');
2706
-	}
2707
-	if (!defined('_SPIP_PAGE')) {
2708
-		/** Argument page, personalisable en cas de conflit avec un autre script */
2709
-		define('_SPIP_PAGE', 'page');
2710
-	}
2711
-
2712
-	// le script de l'espace prive
2713
-	// Mettre a "index.php" si DirectoryIndex ne le fait pas ou pb connexes:
2714
-	// les anciens IIS n'acceptent pas les POST sur ecrire/ (#419)
2715
-	// meme pb sur thttpd cf. https://forum.spip.net/fr_184153.html
2716
-	if (!defined('_SPIP_ECRIRE_SCRIPT')) {
2717
-		if (!empty($_SERVER['SERVER_SOFTWARE']) and preg_match(',IIS|thttpd,', $_SERVER['SERVER_SOFTWARE'])) {
2718
-			define('_SPIP_ECRIRE_SCRIPT', 'index.php');
2719
-		} else {
2720
-			define('_SPIP_ECRIRE_SCRIPT', '');
2721
-		}
2722
-	}
2723
-
2724
-
2725
-	if (!defined('_SPIP_AJAX')) {
2726
-		define('_SPIP_AJAX', ((!isset($_COOKIE['spip_accepte_ajax']))
2727
-			? 1
2728
-			: (($_COOKIE['spip_accepte_ajax'] != -1) ? 1 : 0)));
2729
-	}
2730
-
2731
-	// La requete est-elle en ajax ?
2732
-	if (!defined('_AJAX')) {
2733
-		define('_AJAX',
2734
-			(isset($_SERVER['HTTP_X_REQUESTED_WITH']) # ajax jQuery
2735
-				or !empty($_REQUEST['var_ajax_redir']) # redirection 302 apres ajax jQuery
2736
-				or !empty($_REQUEST['var_ajaxcharset']) # compat ascendante pour plugins
2737
-				or !empty($_REQUEST['var_ajax']) # forms ajax & inclure ajax de spip
2738
-			)
2739
-			and empty($_REQUEST['var_noajax']) # horrible exception, car c'est pas parce que la requete est ajax jquery qu'il faut tuer tous les formulaires ajax qu'elle contient
2740
-		);
2741
-	}
2742
-
2743
-	# nombre de pixels maxi pour calcul de la vignette avec gd
2744
-	# au dela de 5500000 on considere que php n'est pas limite en memoire pour cette operation
2745
-	# les configurations limitees en memoire ont un seuil plutot vers 1MPixel
2746
-	if (!defined('_IMG_GD_MAX_PIXELS')) {
2747
-		define('_IMG_GD_MAX_PIXELS',
2748
-		(isset($GLOBALS['meta']['max_taille_vignettes']) and $GLOBALS['meta']['max_taille_vignettes'])
2749
-			? $GLOBALS['meta']['max_taille_vignettes']
2750
-			: 0);
2751
-	}
2752
-
2753
-	if (!defined('_MEMORY_LIMIT_MIN')) {
2754
-		define('_MEMORY_LIMIT_MIN', 16);
2755
-	} // en Mo
2756
-	// si on est dans l'espace prive et si le besoin est superieur a 8Mo (qui est vraiment le standard)
2757
-	// on verifie que la memoire est suffisante pour le compactage css+js pour eviter la page blanche
2758
-	// il y aura d'autres problemes et l'utilisateur n'ira pas tres loin, mais ce sera plus comprehensible qu'une page blanche
2759
-	if (test_espace_prive() and _MEMORY_LIMIT_MIN > 8) {
2760
-		if ($memory = trim(ini_get('memory_limit')) and $memory != -1) {
2761
-			$unit = strtolower(substr($memory, -1));
2762
-			$memory = substr($memory, 0, -1);
2763
-			switch ($unit) {
2764
-				// Le modifieur 'G' est disponible depuis PHP 5.1.0
2765
-				case 'g':
2766
-					$memory *= 1024;
2767
-				case 'm':
2768
-					$memory *= 1024;
2769
-				case 'k':
2770
-					$memory *= 1024;
2771
-			}
2772
-			if ($memory < _MEMORY_LIMIT_MIN * 1024 * 1024) {
2773
-				@ini_set('memory_limit', $m = _MEMORY_LIMIT_MIN . 'M');
2774
-				if (trim(ini_get('memory_limit')) != $m) {
2775
-					if (!defined('_INTERDIRE_COMPACTE_HEAD_ECRIRE')) {
2776
-						define('_INTERDIRE_COMPACTE_HEAD_ECRIRE', true);
2777
-					} // evite une page blanche car on ne saura pas calculer la css dans ce hit
2778
-				}
2779
-			}
2780
-		} else {
2781
-			if (!defined('_INTERDIRE_COMPACTE_HEAD_ECRIRE')) {
2782
-				define('_INTERDIRE_COMPACTE_HEAD_ECRIRE', true);
2783
-			}
2784
-		} // evite une page blanche car on ne saura pas calculer la css dans ce hit
2785
-	}
2786
-	// Protocoles a normaliser dans les chaines de langues
2787
-	if (!defined('_PROTOCOLES_STD')) {
2788
-		define('_PROTOCOLES_STD', 'http|https|ftp|mailto|webcal');
2789
-	}
2790
-
2791
-	init_var_mode();
2623
+    static $too_late = 0;
2624
+    if ($too_late++) {
2625
+        return;
2626
+    }
2627
+
2628
+    // taille mini des login
2629
+    if (!defined('_LOGIN_TROP_COURT')) {
2630
+        define('_LOGIN_TROP_COURT', 4);
2631
+    }
2632
+
2633
+    // la taille maxi des logos (0 : pas de limite) (pas de define par defaut, ce n'est pas utile)
2634
+    #if (!defined('_LOGO_MAX_SIZE')) define('_LOGO_MAX_SIZE', 0); # poids en ko
2635
+    #if (!defined('_LOGO_MAX_WIDTH')) define('_LOGO_MAX_WIDTH', 0); # largeur en pixels
2636
+    #if (!defined('_LOGO_MAX_HEIGHT')) define('_LOGO_MAX_HEIGHT', 0); # hauteur en pixels
2637
+
2638
+    // la taille maxi des images (0 : pas de limite) (pas de define par defaut, ce n'est pas utile)
2639
+    #if (!defined('_DOC_MAX_SIZE')) define('_DOC_MAX_SIZE', 0); # poids en ko
2640
+    #if (!defined('_IMG_MAX_SIZE')) define('_IMG_MAX_SIZE', 0); # poids en ko
2641
+    #if (!defined('_IMG_MAX_WIDTH')) define('_IMG_MAX_WIDTH', 0); # largeur en pixels
2642
+    #if (!defined('_IMG_MAX_HEIGHT')) define('_IMG_MAX_HEIGHT', 0); # hauteur en pixels
2643
+
2644
+    if (!defined('_PASS_LONGUEUR_MINI')) {
2645
+        define('_PASS_LONGUEUR_MINI', 6);
2646
+    }
2647
+
2648
+
2649
+    // Qualite des images calculees automatiquement. C'est un nombre entre 0 et 100, meme pour imagick (on ramene a 0..1 par la suite)
2650
+    if (!defined('_IMG_QUALITE')) {
2651
+        define('_IMG_QUALITE', 85);
2652
+    } # valeur par defaut
2653
+    if (!defined('_IMG_GD_QUALITE')) {
2654
+        define('_IMG_GD_QUALITE', _IMG_QUALITE);
2655
+    } # surcharge pour la lib GD
2656
+    if (!defined('_IMG_CONVERT_QUALITE')) {
2657
+        define('_IMG_CONVERT_QUALITE', _IMG_QUALITE);
2658
+    } # surcharge pour imagick en ligne de commande
2659
+    // Historiquement la valeur pour imagick semble differente. Si ca n'est pas necessaire, il serait preferable de garder _IMG_QUALITE
2660
+    if (!defined('_IMG_IMAGICK_QUALITE')) {
2661
+        define('_IMG_IMAGICK_QUALITE', 75);
2662
+    } # surcharge pour imagick en PHP
2663
+
2664
+    if (!defined('_COPIE_LOCALE_MAX_SIZE')) {
2665
+        define('_COPIE_LOCALE_MAX_SIZE', 33554432);
2666
+    } // poids en octet
2667
+
2668
+    // qq chaines standard
2669
+    if (!defined('_ACCESS_FILE_NAME')) {
2670
+        define('_ACCESS_FILE_NAME', '.htaccess');
2671
+    }
2672
+    if (!defined('_AUTH_USER_FILE')) {
2673
+        define('_AUTH_USER_FILE', '.htpasswd');
2674
+    }
2675
+    if (!defined('_SPIP_DUMP')) {
2676
+        define('_SPIP_DUMP', 'dump@nom_site@@[email protected]');
2677
+    }
2678
+    if (!defined('_CACHE_RUBRIQUES')) {
2679
+        /** Fichier cache pour le navigateur de rubrique du bandeau */
2680
+        define('_CACHE_RUBRIQUES', _DIR_TMP . 'menu-rubriques-cache.txt');
2681
+    }
2682
+    if (!defined('_CACHE_RUBRIQUES_MAX')) {
2683
+        /** Nombre maxi de rubriques enfants affichées pour chaque rubrique du navigateur de rubrique du bandeau */
2684
+        define('_CACHE_RUBRIQUES_MAX', 500);
2685
+    }
2686
+
2687
+    if (!defined('_EXTENSION_SQUELETTES')) {
2688
+        define('_EXTENSION_SQUELETTES', 'html');
2689
+    }
2690
+
2691
+    if (!defined('_DOCTYPE_ECRIRE')) {
2692
+        /** Définit le doctype de l’espace privé */
2693
+        define('_DOCTYPE_ECRIRE', "<!DOCTYPE html>\n");
2694
+    }
2695
+    if (!defined('_DOCTYPE_AIDE')) {
2696
+        /** Définit le doctype de l’aide en ligne */
2697
+        define('_DOCTYPE_AIDE',
2698
+        "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Frameset//EN' 'http://www.w3.org/TR/1999/REC-html401-19991224/frameset.dtd'>");
2699
+    }
2700
+
2701
+    if (!defined('_SPIP_SCRIPT')) {
2702
+        /** L'adresse de base du site ; on peut mettre '' si la racine est gerée par
2703
+         * le script de l'espace public, alias index.php */
2704
+        define('_SPIP_SCRIPT', 'spip.php');
2705
+    }
2706
+    if (!defined('_SPIP_PAGE')) {
2707
+        /** Argument page, personalisable en cas de conflit avec un autre script */
2708
+        define('_SPIP_PAGE', 'page');
2709
+    }
2710
+
2711
+    // le script de l'espace prive
2712
+    // Mettre a "index.php" si DirectoryIndex ne le fait pas ou pb connexes:
2713
+    // les anciens IIS n'acceptent pas les POST sur ecrire/ (#419)
2714
+    // meme pb sur thttpd cf. https://forum.spip.net/fr_184153.html
2715
+    if (!defined('_SPIP_ECRIRE_SCRIPT')) {
2716
+        if (!empty($_SERVER['SERVER_SOFTWARE']) and preg_match(',IIS|thttpd,', $_SERVER['SERVER_SOFTWARE'])) {
2717
+            define('_SPIP_ECRIRE_SCRIPT', 'index.php');
2718
+        } else {
2719
+            define('_SPIP_ECRIRE_SCRIPT', '');
2720
+        }
2721
+    }
2722
+
2723
+
2724
+    if (!defined('_SPIP_AJAX')) {
2725
+        define('_SPIP_AJAX', ((!isset($_COOKIE['spip_accepte_ajax']))
2726
+            ? 1
2727
+            : (($_COOKIE['spip_accepte_ajax'] != -1) ? 1 : 0)));
2728
+    }
2729
+
2730
+    // La requete est-elle en ajax ?
2731
+    if (!defined('_AJAX')) {
2732
+        define('_AJAX',
2733
+            (isset($_SERVER['HTTP_X_REQUESTED_WITH']) # ajax jQuery
2734
+                or !empty($_REQUEST['var_ajax_redir']) # redirection 302 apres ajax jQuery
2735
+                or !empty($_REQUEST['var_ajaxcharset']) # compat ascendante pour plugins
2736
+                or !empty($_REQUEST['var_ajax']) # forms ajax & inclure ajax de spip
2737
+            )
2738
+            and empty($_REQUEST['var_noajax']) # horrible exception, car c'est pas parce que la requete est ajax jquery qu'il faut tuer tous les formulaires ajax qu'elle contient
2739
+        );
2740
+    }
2741
+
2742
+    # nombre de pixels maxi pour calcul de la vignette avec gd
2743
+    # au dela de 5500000 on considere que php n'est pas limite en memoire pour cette operation
2744
+    # les configurations limitees en memoire ont un seuil plutot vers 1MPixel
2745
+    if (!defined('_IMG_GD_MAX_PIXELS')) {
2746
+        define('_IMG_GD_MAX_PIXELS',
2747
+        (isset($GLOBALS['meta']['max_taille_vignettes']) and $GLOBALS['meta']['max_taille_vignettes'])
2748
+            ? $GLOBALS['meta']['max_taille_vignettes']
2749
+            : 0);
2750
+    }
2751
+
2752
+    if (!defined('_MEMORY_LIMIT_MIN')) {
2753
+        define('_MEMORY_LIMIT_MIN', 16);
2754
+    } // en Mo
2755
+    // si on est dans l'espace prive et si le besoin est superieur a 8Mo (qui est vraiment le standard)
2756
+    // on verifie que la memoire est suffisante pour le compactage css+js pour eviter la page blanche
2757
+    // il y aura d'autres problemes et l'utilisateur n'ira pas tres loin, mais ce sera plus comprehensible qu'une page blanche
2758
+    if (test_espace_prive() and _MEMORY_LIMIT_MIN > 8) {
2759
+        if ($memory = trim(ini_get('memory_limit')) and $memory != -1) {
2760
+            $unit = strtolower(substr($memory, -1));
2761
+            $memory = substr($memory, 0, -1);
2762
+            switch ($unit) {
2763
+                // Le modifieur 'G' est disponible depuis PHP 5.1.0
2764
+                case 'g':
2765
+                    $memory *= 1024;
2766
+                case 'm':
2767
+                    $memory *= 1024;
2768
+                case 'k':
2769
+                    $memory *= 1024;
2770
+            }
2771
+            if ($memory < _MEMORY_LIMIT_MIN * 1024 * 1024) {
2772
+                @ini_set('memory_limit', $m = _MEMORY_LIMIT_MIN . 'M');
2773
+                if (trim(ini_get('memory_limit')) != $m) {
2774
+                    if (!defined('_INTERDIRE_COMPACTE_HEAD_ECRIRE')) {
2775
+                        define('_INTERDIRE_COMPACTE_HEAD_ECRIRE', true);
2776
+                    } // evite une page blanche car on ne saura pas calculer la css dans ce hit
2777
+                }
2778
+            }
2779
+        } else {
2780
+            if (!defined('_INTERDIRE_COMPACTE_HEAD_ECRIRE')) {
2781
+                define('_INTERDIRE_COMPACTE_HEAD_ECRIRE', true);
2782
+            }
2783
+        } // evite une page blanche car on ne saura pas calculer la css dans ce hit
2784
+    }
2785
+    // Protocoles a normaliser dans les chaines de langues
2786
+    if (!defined('_PROTOCOLES_STD')) {
2787
+        define('_PROTOCOLES_STD', 'http|https|ftp|mailto|webcal');
2788
+    }
2789
+
2790
+    init_var_mode();
2792 2791
 }
2793 2792
 
2794 2793
 /**
@@ -2822,129 +2821,129 @@  discard block
 block discarded – undo
2822 2821
  * `   var_mode` (calcul ou recalcul).
2823 2822
  */
2824 2823
 function init_var_mode() {
2825
-	static $done = false;
2826
-	if (!$done) {
2827
-
2828
-		if (isset($_GET['var_mode'])) {
2829
-			$var_mode = explode(',', $_GET['var_mode']);
2830
-			// tout le monde peut calcul/recalcul
2831
-			if (!defined('_VAR_MODE')) {
2832
-				if (in_array('recalcul', $var_mode)) {
2833
-					define('_VAR_MODE', 'recalcul');
2834
-				} elseif (in_array('calcul', $var_mode)) {
2835
-					define('_VAR_MODE', 'calcul');
2836
-				}
2837
-			}
2838
-			$var_mode = array_diff($var_mode, array('calcul', 'recalcul'));
2839
-			if ($var_mode) {
2840
-				include_spip('inc/autoriser');
2841
-				// autoriser preview si preview seulement, et sinon autoriser debug
2842
-				if (autoriser(
2843
-					($_GET['var_mode'] == 'preview')
2844
-						? 'previsualiser'
2845
-						: 'debug'
2846
-				)) {
2847
-					if (in_array('traduction', $var_mode)) {
2848
-						// forcer le calcul pour passer dans traduire
2849
-						if (!defined('_VAR_MODE')) {
2850
-							define('_VAR_MODE', 'calcul');
2851
-						}
2852
-						// et ne pas enregistrer de cache pour ne pas trainer les surlignages sur d'autres pages
2853
-						if (!defined('_VAR_NOCACHE')) {
2854
-							define('_VAR_NOCACHE', true);
2855
-						}
2856
-						$var_mode = array_diff($var_mode, array('traduction'));
2857
-					}
2858
-					if (in_array('preview', $var_mode)) {
2859
-						// basculer sur les criteres de preview dans les boucles
2860
-						if (!defined('_VAR_PREVIEW')) {
2861
-							define('_VAR_PREVIEW', true);
2862
-						}
2863
-						// forcer le calcul
2864
-						if (!defined('_VAR_MODE')) {
2865
-							define('_VAR_MODE', 'calcul');
2866
-						}
2867
-						// et ne pas enregistrer de cache
2868
-						if (!defined('_VAR_NOCACHE')) {
2869
-							define('_VAR_NOCACHE', true);
2870
-						}
2871
-						$var_mode = array_diff($var_mode, array('preview'));
2872
-					}
2873
-					if (in_array('inclure', $var_mode)) {
2874
-						// forcer le compilo et ignorer les caches existants
2875
-						if (!defined('_VAR_MODE')) {
2876
-							define('_VAR_MODE', 'calcul');
2877
-						}
2878
-						if (!defined('_VAR_INCLURE')) {
2879
-							define('_VAR_INCLURE', true);
2880
-						}
2881
-						// et ne pas enregistrer de cache
2882
-						if (!defined('_VAR_NOCACHE')) {
2883
-							define('_VAR_NOCACHE', true);
2884
-						}
2885
-						$var_mode = array_diff($var_mode, array('inclure'));
2886
-					}
2887
-					if (in_array('urls', $var_mode)) {
2888
-						// forcer le compilo et ignorer les caches existants
2889
-						if (!defined('_VAR_MODE')) {
2890
-							define('_VAR_MODE', 'calcul');
2891
-						}
2892
-						if (!defined('_VAR_URLS')) {
2893
-							define('_VAR_URLS', true);
2894
-						}
2895
-						$var_mode = array_diff($var_mode, array('urls'));
2896
-					}
2897
-					if (in_array('images', $var_mode)) {
2898
-						// forcer le compilo et ignorer les caches existants
2899
-						if (!defined('_VAR_MODE')) {
2900
-							define('_VAR_MODE', 'calcul');
2901
-						}
2902
-						// indiquer qu'on doit recalculer les images
2903
-						if (!defined('_VAR_IMAGES')) {
2904
-							define('_VAR_IMAGES', true);
2905
-						}
2906
-						$var_mode = array_diff($var_mode, array('images'));
2907
-					}
2908
-					if (in_array('debug', $var_mode)) {
2909
-						if (!defined('_VAR_MODE')) {
2910
-							define('_VAR_MODE', 'debug');
2911
-						}
2912
-						// et ne pas enregistrer de cache
2913
-						if (!defined('_VAR_NOCACHE')) {
2914
-							define('_VAR_NOCACHE', true);
2915
-						}
2916
-						$var_mode = array_diff($var_mode, array('debug'));
2917
-					}
2918
-					if (count($var_mode) and !defined('_VAR_MODE')) {
2919
-						define('_VAR_MODE', reset($var_mode));
2920
-					}
2921
-					if (isset($GLOBALS['visiteur_session']['nom'])) {
2922
-						spip_log($GLOBALS['visiteur_session']['nom']
2923
-							. " " . _VAR_MODE);
2924
-					}
2925
-				} // pas autorise ?
2926
-				else {
2927
-					// si on n'est pas connecte on se redirige
2928
-					if (!$GLOBALS['visiteur_session']) {
2929
-						include_spip('inc/headers');
2930
-						redirige_par_entete(generer_url_public('login',
2931
-							'url=' . rawurlencode(
2932
-								parametre_url(self(), 'var_mode', $_GET['var_mode'], '&')
2933
-							), true));
2934
-					}
2935
-					// sinon tant pis
2936
-				}
2937
-			}
2938
-		}
2939
-		if (!defined('_VAR_MODE')) {
2940
-			/**
2941
-			 * Indique le mode de calcul ou d'affichage de la page.
2942
-			 * @see init_var_mode()
2943
-			 */
2944
-			define('_VAR_MODE', false);
2945
-		}
2946
-		$done = true;
2947
-	}
2824
+    static $done = false;
2825
+    if (!$done) {
2826
+
2827
+        if (isset($_GET['var_mode'])) {
2828
+            $var_mode = explode(',', $_GET['var_mode']);
2829
+            // tout le monde peut calcul/recalcul
2830
+            if (!defined('_VAR_MODE')) {
2831
+                if (in_array('recalcul', $var_mode)) {
2832
+                    define('_VAR_MODE', 'recalcul');
2833
+                } elseif (in_array('calcul', $var_mode)) {
2834
+                    define('_VAR_MODE', 'calcul');
2835
+                }
2836
+            }
2837
+            $var_mode = array_diff($var_mode, array('calcul', 'recalcul'));
2838
+            if ($var_mode) {
2839
+                include_spip('inc/autoriser');
2840
+                // autoriser preview si preview seulement, et sinon autoriser debug
2841
+                if (autoriser(
2842
+                    ($_GET['var_mode'] == 'preview')
2843
+                        ? 'previsualiser'
2844
+                        : 'debug'
2845
+                )) {
2846
+                    if (in_array('traduction', $var_mode)) {
2847
+                        // forcer le calcul pour passer dans traduire
2848
+                        if (!defined('_VAR_MODE')) {
2849
+                            define('_VAR_MODE', 'calcul');
2850
+                        }
2851
+                        // et ne pas enregistrer de cache pour ne pas trainer les surlignages sur d'autres pages
2852
+                        if (!defined('_VAR_NOCACHE')) {
2853
+                            define('_VAR_NOCACHE', true);
2854
+                        }
2855
+                        $var_mode = array_diff($var_mode, array('traduction'));
2856
+                    }
2857
+                    if (in_array('preview', $var_mode)) {
2858
+                        // basculer sur les criteres de preview dans les boucles
2859
+                        if (!defined('_VAR_PREVIEW')) {
2860
+                            define('_VAR_PREVIEW', true);
2861
+                        }
2862
+                        // forcer le calcul
2863
+                        if (!defined('_VAR_MODE')) {
2864
+                            define('_VAR_MODE', 'calcul');
2865
+                        }
2866
+                        // et ne pas enregistrer de cache
2867
+                        if (!defined('_VAR_NOCACHE')) {
2868
+                            define('_VAR_NOCACHE', true);
2869
+                        }
2870
+                        $var_mode = array_diff($var_mode, array('preview'));
2871
+                    }
2872
+                    if (in_array('inclure', $var_mode)) {
2873
+                        // forcer le compilo et ignorer les caches existants
2874
+                        if (!defined('_VAR_MODE')) {
2875
+                            define('_VAR_MODE', 'calcul');
2876
+                        }
2877
+                        if (!defined('_VAR_INCLURE')) {
2878
+                            define('_VAR_INCLURE', true);
2879
+                        }
2880
+                        // et ne pas enregistrer de cache
2881
+                        if (!defined('_VAR_NOCACHE')) {
2882
+                            define('_VAR_NOCACHE', true);
2883
+                        }
2884
+                        $var_mode = array_diff($var_mode, array('inclure'));
2885
+                    }
2886
+                    if (in_array('urls', $var_mode)) {
2887
+                        // forcer le compilo et ignorer les caches existants
2888
+                        if (!defined('_VAR_MODE')) {
2889
+                            define('_VAR_MODE', 'calcul');
2890
+                        }
2891
+                        if (!defined('_VAR_URLS')) {
2892
+                            define('_VAR_URLS', true);
2893
+                        }
2894
+                        $var_mode = array_diff($var_mode, array('urls'));
2895
+                    }
2896
+                    if (in_array('images', $var_mode)) {
2897
+                        // forcer le compilo et ignorer les caches existants
2898
+                        if (!defined('_VAR_MODE')) {
2899
+                            define('_VAR_MODE', 'calcul');
2900
+                        }
2901
+                        // indiquer qu'on doit recalculer les images
2902
+                        if (!defined('_VAR_IMAGES')) {
2903
+                            define('_VAR_IMAGES', true);
2904
+                        }
2905
+                        $var_mode = array_diff($var_mode, array('images'));
2906
+                    }
2907
+                    if (in_array('debug', $var_mode)) {
2908
+                        if (!defined('_VAR_MODE')) {
2909
+                            define('_VAR_MODE', 'debug');
2910
+                        }
2911
+                        // et ne pas enregistrer de cache
2912
+                        if (!defined('_VAR_NOCACHE')) {
2913
+                            define('_VAR_NOCACHE', true);
2914
+                        }
2915
+                        $var_mode = array_diff($var_mode, array('debug'));
2916
+                    }
2917
+                    if (count($var_mode) and !defined('_VAR_MODE')) {
2918
+                        define('_VAR_MODE', reset($var_mode));
2919
+                    }
2920
+                    if (isset($GLOBALS['visiteur_session']['nom'])) {
2921
+                        spip_log($GLOBALS['visiteur_session']['nom']
2922
+                            . " " . _VAR_MODE);
2923
+                    }
2924
+                } // pas autorise ?
2925
+                else {
2926
+                    // si on n'est pas connecte on se redirige
2927
+                    if (!$GLOBALS['visiteur_session']) {
2928
+                        include_spip('inc/headers');
2929
+                        redirige_par_entete(generer_url_public('login',
2930
+                            'url=' . rawurlencode(
2931
+                                parametre_url(self(), 'var_mode', $_GET['var_mode'], '&')
2932
+                            ), true));
2933
+                    }
2934
+                    // sinon tant pis
2935
+                }
2936
+            }
2937
+        }
2938
+        if (!defined('_VAR_MODE')) {
2939
+            /**
2940
+             * Indique le mode de calcul ou d'affichage de la page.
2941
+             * @see init_var_mode()
2942
+             */
2943
+            define('_VAR_MODE', false);
2944
+        }
2945
+        $done = true;
2946
+    }
2948 2947
 }
2949 2948
 
2950 2949
 // Annuler les magic quotes \' sur GET POST COOKIE et GLOBALS ;
@@ -2952,85 +2951,85 @@  discard block
 block discarded – undo
2952 2951
 // la commande is_readable('chemin/vers/fichier/interdit%00truc_normal')
2953 2952
 // https://code.spip.net/@spip_desinfecte
2954 2953
 function spip_desinfecte(&$t, $deep = true) {
2955
-	foreach ($t as $key => $val) {
2956
-		if (is_string($t[$key])) {
2957
-			$t[$key] = str_replace(chr(0), '-', $t[$key]);
2958
-		} // traiter aussi les "texte_plus" de article_edit
2959
-		else {
2960
-			if ($deep and is_array($t[$key]) and $key !== 'GLOBALS') {
2961
-				spip_desinfecte($t[$key], $deep);
2962
-			}
2963
-		}
2964
-	}
2954
+    foreach ($t as $key => $val) {
2955
+        if (is_string($t[$key])) {
2956
+            $t[$key] = str_replace(chr(0), '-', $t[$key]);
2957
+        } // traiter aussi les "texte_plus" de article_edit
2958
+        else {
2959
+            if ($deep and is_array($t[$key]) and $key !== 'GLOBALS') {
2960
+                spip_desinfecte($t[$key], $deep);
2961
+            }
2962
+        }
2963
+    }
2965 2964
 }
2966 2965
 
2967 2966
 //  retourne le statut du visiteur s'il s'annonce
2968 2967
 
2969 2968
 // https://code.spip.net/@verifier_visiteur
2970 2969
 function verifier_visiteur() {
2971
-	// Rq: pour que cette fonction marche depuis mes_options
2972
-	// il faut forcer l'init si ce n'est fait
2973
-	// mais on risque de perturber des plugins en initialisant trop tot
2974
-	// certaines constantes
2975
-	@spip_initialisation_core(
2976
-		(_DIR_RACINE . _NOM_PERMANENTS_INACCESSIBLES),
2977
-		(_DIR_RACINE . _NOM_PERMANENTS_ACCESSIBLES),
2978
-		(_DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES),
2979
-		(_DIR_RACINE . _NOM_TEMPORAIRES_ACCESSIBLES)
2980
-	);
2981
-
2982
-	// Demarrer une session NON AUTHENTIFIEE si on donne son nom
2983
-	// dans un formulaire sans login (ex: #FORMULAIRE_FORUM)
2984
-	// Attention on separe bien session_nom et nom, pour eviter
2985
-	// les melanges entre donnees SQL et variables plus aleatoires
2986
-	$variables_session = array('session_nom', 'session_email');
2987
-	foreach ($variables_session as $var) {
2988
-		if (_request($var) !== null) {
2989
-			$init = true;
2990
-			break;
2991
-		}
2992
-	}
2993
-	if (isset($init)) {
2994
-		#@spip_initialisation_suite();
2995
-		$session = charger_fonction('session', 'inc');
2996
-		$session();
2997
-		include_spip('inc/texte');
2998
-		foreach ($variables_session as $var) {
2999
-			if (($a = _request($var)) !== null) {
3000
-				$GLOBALS['visiteur_session'][$var] = safehtml($a);
3001
-			}
3002
-		}
3003
-		if (!isset($GLOBALS['visiteur_session']['id_auteur'])) {
3004
-			$GLOBALS['visiteur_session']['id_auteur'] = 0;
3005
-		}
3006
-		$session($GLOBALS['visiteur_session']);
3007
-
3008
-		return 0;
3009
-	}
3010
-
3011
-	$h = (isset($_SERVER['PHP_AUTH_USER']) and !$GLOBALS['ignore_auth_http']);
3012
-	if ($h or isset($_COOKIE['spip_session']) or isset($_COOKIE[$GLOBALS['cookie_prefix'] . '_session'])) {
3013
-
3014
-		$session = charger_fonction('session', 'inc');
3015
-		if ($session()) {
3016
-			return $GLOBALS['visiteur_session']['statut'];
3017
-		}
3018
-		if ($h and isset($_SERVER['PHP_AUTH_PW'])) {
3019
-			include_spip('inc/auth');
3020
-			$h = lire_php_auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
3021
-		}
3022
-		if ($h) {
3023
-			$GLOBALS['visiteur_session'] = $h;
3024
-
3025
-			return $GLOBALS['visiteur_session']['statut'];
3026
-		}
3027
-	}
3028
-
3029
-	// au moins son navigateur nous dit la langue preferee de cet inconnu
3030
-	include_spip('inc/lang');
3031
-	utiliser_langue_visiteur();
3032
-
3033
-	return false;
2970
+    // Rq: pour que cette fonction marche depuis mes_options
2971
+    // il faut forcer l'init si ce n'est fait
2972
+    // mais on risque de perturber des plugins en initialisant trop tot
2973
+    // certaines constantes
2974
+    @spip_initialisation_core(
2975
+        (_DIR_RACINE . _NOM_PERMANENTS_INACCESSIBLES),
2976
+        (_DIR_RACINE . _NOM_PERMANENTS_ACCESSIBLES),
2977
+        (_DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES),
2978
+        (_DIR_RACINE . _NOM_TEMPORAIRES_ACCESSIBLES)
2979
+    );
2980
+
2981
+    // Demarrer une session NON AUTHENTIFIEE si on donne son nom
2982
+    // dans un formulaire sans login (ex: #FORMULAIRE_FORUM)
2983
+    // Attention on separe bien session_nom et nom, pour eviter
2984
+    // les melanges entre donnees SQL et variables plus aleatoires
2985
+    $variables_session = array('session_nom', 'session_email');
2986
+    foreach ($variables_session as $var) {
2987
+        if (_request($var) !== null) {
2988
+            $init = true;
2989
+            break;
2990
+        }
2991
+    }
2992
+    if (isset($init)) {
2993
+        #@spip_initialisation_suite();
2994
+        $session = charger_fonction('session', 'inc');
2995
+        $session();
2996
+        include_spip('inc/texte');
2997
+        foreach ($variables_session as $var) {
2998
+            if (($a = _request($var)) !== null) {
2999
+                $GLOBALS['visiteur_session'][$var] = safehtml($a);
3000
+            }
3001
+        }
3002
+        if (!isset($GLOBALS['visiteur_session']['id_auteur'])) {
3003
+            $GLOBALS['visiteur_session']['id_auteur'] = 0;
3004
+        }
3005
+        $session($GLOBALS['visiteur_session']);
3006
+
3007
+        return 0;
3008
+    }
3009
+
3010
+    $h = (isset($_SERVER['PHP_AUTH_USER']) and !$GLOBALS['ignore_auth_http']);
3011
+    if ($h or isset($_COOKIE['spip_session']) or isset($_COOKIE[$GLOBALS['cookie_prefix'] . '_session'])) {
3012
+
3013
+        $session = charger_fonction('session', 'inc');
3014
+        if ($session()) {
3015
+            return $GLOBALS['visiteur_session']['statut'];
3016
+        }
3017
+        if ($h and isset($_SERVER['PHP_AUTH_PW'])) {
3018
+            include_spip('inc/auth');
3019
+            $h = lire_php_auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
3020
+        }
3021
+        if ($h) {
3022
+            $GLOBALS['visiteur_session'] = $h;
3023
+
3024
+            return $GLOBALS['visiteur_session']['statut'];
3025
+        }
3026
+    }
3027
+
3028
+    // au moins son navigateur nous dit la langue preferee de cet inconnu
3029
+    include_spip('inc/lang');
3030
+    utiliser_langue_visiteur();
3031
+
3032
+    return false;
3034 3033
 }
3035 3034
 
3036 3035
 
@@ -3053,21 +3052,21 @@  discard block
 block discarded – undo
3053 3052
  *     - string Langue utilisée.
3054 3053
  **/
3055 3054
 function lang_select($lang = null) {
3056
-	static $pile_langues = array();
3057
-	if (!function_exists('changer_langue')) {
3058
-		include_spip('inc/lang');
3059
-	}
3060
-	if ($lang === null) {
3061
-		$lang = array_pop($pile_langues);
3062
-	} else {
3063
-		array_push($pile_langues, $GLOBALS['spip_lang']);
3064
-	}
3065
-	if (isset($GLOBALS['spip_lang']) and $lang == $GLOBALS['spip_lang']) {
3066
-		return $lang;
3067
-	}
3068
-	changer_langue($lang);
3055
+    static $pile_langues = array();
3056
+    if (!function_exists('changer_langue')) {
3057
+        include_spip('inc/lang');
3058
+    }
3059
+    if ($lang === null) {
3060
+        $lang = array_pop($pile_langues);
3061
+    } else {
3062
+        array_push($pile_langues, $GLOBALS['spip_lang']);
3063
+    }
3064
+    if (isset($GLOBALS['spip_lang']) and $lang == $GLOBALS['spip_lang']) {
3065
+        return $lang;
3066
+    }
3067
+    changer_langue($lang);
3069 3068
 
3070
-	return $lang;
3069
+    return $lang;
3071 3070
 }
3072 3071
 
3073 3072
 /**
@@ -3084,19 +3083,19 @@  discard block
 block discarded – undo
3084 3083
  *     Identifiant de la session
3085 3084
  **/
3086 3085
 function spip_session($force = false) {
3087
-	static $session;
3088
-	if ($force or !isset($session)) {
3089
-		$s = pipeline('definir_session',
3090
-			$GLOBALS['visiteur_session']
3091
-				? serialize($GLOBALS['visiteur_session'])
3092
-				. '_' . @$_COOKIE['spip_session']
3093
-				: ''
3094
-		);
3095
-		$session = $s ? substr(md5($s), 0, 8) : '';
3096
-	}
3086
+    static $session;
3087
+    if ($force or !isset($session)) {
3088
+        $s = pipeline('definir_session',
3089
+            $GLOBALS['visiteur_session']
3090
+                ? serialize($GLOBALS['visiteur_session'])
3091
+                . '_' . @$_COOKIE['spip_session']
3092
+                : ''
3093
+        );
3094
+        $session = $s ? substr(md5($s), 0, 8) : '';
3095
+    }
3097 3096
 
3098
-	#spip_log('session: '.$session);
3099
-	return $session;
3097
+    #spip_log('session: '.$session);
3098
+    return $session;
3100 3099
 }
3101 3100
 
3102 3101
 
@@ -3115,9 +3114,9 @@  discard block
 block discarded – undo
3115 3114
  *    Lien sur une icone d'aide
3116 3115
  **/
3117 3116
 function aider($aide = '', $distante = false) {
3118
-	$aider = charger_fonction('aide', 'inc', true);
3117
+    $aider = charger_fonction('aide', 'inc', true);
3119 3118
 
3120
-	return $aider ? $aider($aide, '', array(), $distante) : '';
3119
+    return $aider ? $aider($aide, '', array(), $distante) : '';
3121 3120
 }
3122 3121
 
3123 3122
 /**
@@ -3127,24 +3126,24 @@  discard block
 block discarded – undo
3127 3126
  */
3128 3127
 function exec_info_dist() {
3129 3128
 
3130
-	include_spip('inc/autoriser');
3131
-	if (autoriser('phpinfos')) {
3132
-		$cookies_masques = ['spip_session', 'PHPSESSID'];
3133
-		$cookies_backup = [];
3134
-		foreach ($cookies_masques as $k) {
3135
-			if (!empty($_COOKIE[$k])) {
3136
-				$cookies_backup[$k] = $_COOKIE[$k];
3137
-				$_COOKIE[$k] = '******************************';
3138
-			}
3139
-		}
3140
-		phpinfo();
3141
-		foreach ($cookies_backup as $k => $v) {
3142
-			$_COOKIE[$k] = $v;
3143
-		}
3144
-	} else {
3145
-		include_spip('inc/filtres');
3146
-		sinon_interdire_acces();
3147
-	}
3129
+    include_spip('inc/autoriser');
3130
+    if (autoriser('phpinfos')) {
3131
+        $cookies_masques = ['spip_session', 'PHPSESSID'];
3132
+        $cookies_backup = [];
3133
+        foreach ($cookies_masques as $k) {
3134
+            if (!empty($_COOKIE[$k])) {
3135
+                $cookies_backup[$k] = $_COOKIE[$k];
3136
+                $_COOKIE[$k] = '******************************';
3137
+            }
3138
+        }
3139
+        phpinfo();
3140
+        foreach ($cookies_backup as $k => $v) {
3141
+            $_COOKIE[$k] = $v;
3142
+        }
3143
+    } else {
3144
+        include_spip('inc/filtres');
3145
+        sinon_interdire_acces();
3146
+    }
3148 3147
 }
3149 3148
 
3150 3149
 /**
@@ -3164,13 +3163,13 @@  discard block
 block discarded – undo
3164 3163
  *     - string si $message à false.
3165 3164
  **/
3166 3165
 function erreur_squelette($message = '', $lieu = '') {
3167
-	$debusquer = charger_fonction('debusquer', 'public');
3168
-	if (is_array($lieu)) {
3169
-		include_spip('public/compiler');
3170
-		$lieu = reconstruire_contexte_compil($lieu);
3171
-	}
3166
+    $debusquer = charger_fonction('debusquer', 'public');
3167
+    if (is_array($lieu)) {
3168
+        include_spip('public/compiler');
3169
+        $lieu = reconstruire_contexte_compil($lieu);
3170
+    }
3172 3171
 
3173
-	return $debusquer($message, $lieu);
3172
+    return $debusquer($message, $lieu);
3174 3173
 }
3175 3174
 
3176 3175
 /**
@@ -3207,109 +3206,109 @@  discard block
 block discarded – undo
3207 3206
  *     - ou tableau d'information sur le squelette.
3208 3207
  */
3209 3208
 function recuperer_fond($fond, $contexte = array(), $options = array(), $connect = '') {
3210
-	if (!function_exists('evaluer_fond')) {
3211
-		include_spip('public/assembler');
3212
-	}
3213
-	// assurer la compat avec l'ancienne syntaxe
3214
-	// (trim etait le 3eme argument, par defaut a true)
3215
-	if (!is_array($options)) {
3216
-		$options = array('trim' => $options);
3217
-	}
3218
-	if (!isset($options['trim'])) {
3219
-		$options['trim'] = true;
3220
-	}
3221
-
3222
-	if (isset($contexte['connect'])) {
3223
-		$connect = $contexte['connect'];
3224
-		unset($contexte['connect']);
3225
-	}
3226
-
3227
-	$texte = "";
3228
-	$pages = array();
3229
-	$lang_select = '';
3230
-	if (!isset($options['etoile']) or !$options['etoile']) {
3231
-		// Si on a inclus sans fixer le critere de lang, on prend la langue courante
3232
-		if (!isset($contexte['lang'])) {
3233
-			$contexte['lang'] = $GLOBALS['spip_lang'];
3234
-		}
3235
-
3236
-		if ($contexte['lang'] != $GLOBALS['meta']['langue_site']) {
3237
-			$lang_select = lang_select($contexte['lang']);
3238
-		}
3239
-	}
3240
-
3241
-	if (!isset($GLOBALS['_INC_PUBLIC'])) {
3242
-		$GLOBALS['_INC_PUBLIC'] = 0;
3243
-	}
3244
-
3245
-	$GLOBALS['_INC_PUBLIC']++;
3246
-
3247
-	// fix #4235
3248
-	$cache_utilise_session_appelant	= (isset($GLOBALS['cache_utilise_session']) ? $GLOBALS['cache_utilise_session'] : null);
3249
-
3250
-
3251
-	foreach (is_array($fond) ? $fond : array($fond) as $f) {
3209
+    if (!function_exists('evaluer_fond')) {
3210
+        include_spip('public/assembler');
3211
+    }
3212
+    // assurer la compat avec l'ancienne syntaxe
3213
+    // (trim etait le 3eme argument, par defaut a true)
3214
+    if (!is_array($options)) {
3215
+        $options = array('trim' => $options);
3216
+    }
3217
+    if (!isset($options['trim'])) {
3218
+        $options['trim'] = true;
3219
+    }
3220
+
3221
+    if (isset($contexte['connect'])) {
3222
+        $connect = $contexte['connect'];
3223
+        unset($contexte['connect']);
3224
+    }
3225
+
3226
+    $texte = "";
3227
+    $pages = array();
3228
+    $lang_select = '';
3229
+    if (!isset($options['etoile']) or !$options['etoile']) {
3230
+        // Si on a inclus sans fixer le critere de lang, on prend la langue courante
3231
+        if (!isset($contexte['lang'])) {
3232
+            $contexte['lang'] = $GLOBALS['spip_lang'];
3233
+        }
3234
+
3235
+        if ($contexte['lang'] != $GLOBALS['meta']['langue_site']) {
3236
+            $lang_select = lang_select($contexte['lang']);
3237
+        }
3238
+    }
3239
+
3240
+    if (!isset($GLOBALS['_INC_PUBLIC'])) {
3241
+        $GLOBALS['_INC_PUBLIC'] = 0;
3242
+    }
3243
+
3244
+    $GLOBALS['_INC_PUBLIC']++;
3245
+
3246
+    // fix #4235
3247
+    $cache_utilise_session_appelant	= (isset($GLOBALS['cache_utilise_session']) ? $GLOBALS['cache_utilise_session'] : null);
3248
+
3249
+
3250
+    foreach (is_array($fond) ? $fond : array($fond) as $f) {
3252 3251
 		
3253
-		unset($GLOBALS['cache_utilise_session']);	// fix #4235
3254
-
3255
-		$page = evaluer_fond($f, $contexte, $connect);
3256
-		if ($page === '') {
3257
-			$c = isset($options['compil']) ? $options['compil'] : '';
3258
-			$a = array('fichier' => $f);
3259
-			$erreur = _T('info_erreur_squelette2', $a); // squelette introuvable
3260
-			erreur_squelette($erreur, $c);
3261
-			// eviter des erreurs strictes ensuite sur $page['cle'] en PHP >= 5.4
3262
-			$page = array('texte' => '', 'erreur' => $erreur);
3263
-		}
3264
-
3265
-		$page = pipeline('recuperer_fond', array(
3266
-			'args' => array('fond' => $f, 'contexte' => $contexte, 'options' => $options, 'connect' => $connect),
3267
-			'data' => $page
3268
-		));
3269
-		if (isset($options['ajax']) and $options['ajax']) {
3270
-			if (!function_exists('encoder_contexte_ajax')) {
3271
-				include_spip('inc/filtres');
3272
-			}
3273
-			$page['texte'] = encoder_contexte_ajax(
3274
-				array_merge(
3275
-					$contexte,
3276
-					array('fond' => $f),
3277
-					($connect ? array('connect' => $connect) : array())
3278
-				),
3279
-				'',
3280
-				$page['texte'],
3281
-				$options['ajax']
3282
-			);
3283
-		}
3284
-
3285
-		if (isset($options['raw']) and $options['raw']) {
3286
-			$pages[] = $page;
3287
-		} else {
3288
-			$texte .= $options['trim'] ? rtrim($page['texte']) : $page['texte'];
3289
-		}
3252
+        unset($GLOBALS['cache_utilise_session']);	// fix #4235
3253
+
3254
+        $page = evaluer_fond($f, $contexte, $connect);
3255
+        if ($page === '') {
3256
+            $c = isset($options['compil']) ? $options['compil'] : '';
3257
+            $a = array('fichier' => $f);
3258
+            $erreur = _T('info_erreur_squelette2', $a); // squelette introuvable
3259
+            erreur_squelette($erreur, $c);
3260
+            // eviter des erreurs strictes ensuite sur $page['cle'] en PHP >= 5.4
3261
+            $page = array('texte' => '', 'erreur' => $erreur);
3262
+        }
3263
+
3264
+        $page = pipeline('recuperer_fond', array(
3265
+            'args' => array('fond' => $f, 'contexte' => $contexte, 'options' => $options, 'connect' => $connect),
3266
+            'data' => $page
3267
+        ));
3268
+        if (isset($options['ajax']) and $options['ajax']) {
3269
+            if (!function_exists('encoder_contexte_ajax')) {
3270
+                include_spip('inc/filtres');
3271
+            }
3272
+            $page['texte'] = encoder_contexte_ajax(
3273
+                array_merge(
3274
+                    $contexte,
3275
+                    array('fond' => $f),
3276
+                    ($connect ? array('connect' => $connect) : array())
3277
+                ),
3278
+                '',
3279
+                $page['texte'],
3280
+                $options['ajax']
3281
+            );
3282
+        }
3283
+
3284
+        if (isset($options['raw']) and $options['raw']) {
3285
+            $pages[] = $page;
3286
+        } else {
3287
+            $texte .= $options['trim'] ? rtrim($page['texte']) : $page['texte'];
3288
+        }
3290 3289
 		
3291
-		// contamination de la session appelante, pour les inclusions statiques
3292
-		if (isset($page['invalideurs']['session'])){
3293
-			$cache_utilise_session_appelant = $page['invalideurs']['session'];
3294
-		}
3295
-	}
3290
+        // contamination de la session appelante, pour les inclusions statiques
3291
+        if (isset($page['invalideurs']['session'])){
3292
+            $cache_utilise_session_appelant = $page['invalideurs']['session'];
3293
+        }
3294
+    }
3296 3295
 
3297
-	// restaurer le sessionnement du contexte appelant, 
3298
-	// éventuellement contaminé si on vient de récupérer une inclusion statique sessionnée
3299
-	if (isset($cache_utilise_session_appelant)) {
3300
-		$GLOBALS['cache_utilise_session'] = $cache_utilise_session_appelant;
3301
-	}
3296
+    // restaurer le sessionnement du contexte appelant, 
3297
+    // éventuellement contaminé si on vient de récupérer une inclusion statique sessionnée
3298
+    if (isset($cache_utilise_session_appelant)) {
3299
+        $GLOBALS['cache_utilise_session'] = $cache_utilise_session_appelant;
3300
+    }
3302 3301
 
3303
-	$GLOBALS['_INC_PUBLIC']--;
3302
+    $GLOBALS['_INC_PUBLIC']--;
3304 3303
 
3305
-	if ($lang_select) {
3306
-		lang_select();
3307
-	}
3308
-	if (isset($options['raw']) and $options['raw']) {
3309
-		return is_array($fond) ? $pages : reset($pages);
3310
-	} else {
3311
-		return $options['trim'] ? ltrim($texte) : $texte;
3312
-	}
3304
+    if ($lang_select) {
3305
+        lang_select();
3306
+    }
3307
+    if (isset($options['raw']) and $options['raw']) {
3308
+        return is_array($fond) ? $pages : reset($pages);
3309
+    } else {
3310
+        return $options['trim'] ? ltrim($texte) : $texte;
3311
+    }
3313 3312
 }
3314 3313
 
3315 3314
 /**
@@ -3319,7 +3318,7 @@  discard block
 block discarded – undo
3319 3318
  * @return string
3320 3319
  */
3321 3320
 function trouve_modele($nom) {
3322
-	return trouver_fond($nom, 'modeles/');
3321
+    return trouver_fond($nom, 'modeles/');
3323 3322
 }
3324 3323
 
3325 3324
 /**
@@ -3335,21 +3334,21 @@  discard block
 block discarded – undo
3335 3334
  * @return array|string
3336 3335
  */
3337 3336
 function trouver_fond($nom, $dir = '', $pathinfo = false) {
3338
-	$f = find_in_path($nom . '.' . _EXTENSION_SQUELETTES, $dir ? rtrim($dir, '/') . '/' : '');
3339
-	if (!$pathinfo) {
3340
-		return $f;
3341
-	}
3342
-	// renvoyer un tableau detaille si $pathinfo==true
3343
-	$p = pathinfo($f);
3344
-	if (!isset($p['extension']) or !$p['extension']) {
3345
-		$p['extension'] = _EXTENSION_SQUELETTES;
3346
-	}
3347
-	if (!isset($p['extension']) or !$p['filename']) {
3348
-		$p['filename'] = ($p['basename'] ? substr($p['basename'], 0, -strlen($p['extension']) - 1) : '');
3349
-	}
3350
-	$p['fond'] = ($f ? substr($f, 0, -strlen($p['extension']) - 1) : '');
3337
+    $f = find_in_path($nom . '.' . _EXTENSION_SQUELETTES, $dir ? rtrim($dir, '/') . '/' : '');
3338
+    if (!$pathinfo) {
3339
+        return $f;
3340
+    }
3341
+    // renvoyer un tableau detaille si $pathinfo==true
3342
+    $p = pathinfo($f);
3343
+    if (!isset($p['extension']) or !$p['extension']) {
3344
+        $p['extension'] = _EXTENSION_SQUELETTES;
3345
+    }
3346
+    if (!isset($p['extension']) or !$p['filename']) {
3347
+        $p['filename'] = ($p['basename'] ? substr($p['basename'], 0, -strlen($p['extension']) - 1) : '');
3348
+    }
3349
+    $p['fond'] = ($f ? substr($f, 0, -strlen($p['extension']) - 1) : '');
3351 3350
 
3352
-	return $p;
3351
+    return $p;
3353 3352
 }
3354 3353
 
3355 3354
 /**
@@ -3370,24 +3369,24 @@  discard block
 block discarded – undo
3370 3369
  *     Nom de l'exec, sinon chaîne vide.
3371 3370
  **/
3372 3371
 function tester_url_ecrire($nom) {
3373
-	static $exec = array();
3374
-	if (isset($exec[$nom])) {
3375
-		return $exec[$nom];
3376
-	}
3377
-	// tester si c'est une page en squelette
3378
-	if (trouver_fond($nom, 'prive/squelettes/contenu/')) {
3379
-		return $exec[$nom] = 'fond';
3380
-	} // compat skels orthogonaux version precedente
3381
-	elseif (trouver_fond($nom, 'prive/exec/')) {
3382
-		return $exec[$nom] = 'fond_monobloc';
3383
-	} // echafaudage d'un fond !
3384
-	elseif (include_spip('public/styliser_par_z') and z_echafaudable($nom)) {
3385
-		return $exec[$nom] = 'fond';
3386
-	}
3387
-	// attention, il ne faut pas inclure l'exec ici
3388
-	// car sinon #URL_ECRIRE provoque des inclusions
3389
-	// et des define intrusifs potentiels
3390
-	return $exec[$nom] = ((find_in_path("{$nom}.php", 'exec/') or charger_fonction($nom, 'exec', true)) ? $nom : '');
3372
+    static $exec = array();
3373
+    if (isset($exec[$nom])) {
3374
+        return $exec[$nom];
3375
+    }
3376
+    // tester si c'est une page en squelette
3377
+    if (trouver_fond($nom, 'prive/squelettes/contenu/')) {
3378
+        return $exec[$nom] = 'fond';
3379
+    } // compat skels orthogonaux version precedente
3380
+    elseif (trouver_fond($nom, 'prive/exec/')) {
3381
+        return $exec[$nom] = 'fond_monobloc';
3382
+    } // echafaudage d'un fond !
3383
+    elseif (include_spip('public/styliser_par_z') and z_echafaudable($nom)) {
3384
+        return $exec[$nom] = 'fond';
3385
+    }
3386
+    // attention, il ne faut pas inclure l'exec ici
3387
+    // car sinon #URL_ECRIRE provoque des inclusions
3388
+    // et des define intrusifs potentiels
3389
+    return $exec[$nom] = ((find_in_path("{$nom}.php", 'exec/') or charger_fonction($nom, 'exec', true)) ? $nom : '');
3391 3390
 }
3392 3391
 
3393 3392
 
@@ -3403,10 +3402,10 @@  discard block
 block discarded – undo
3403 3402
  * @return bool true si le module est chargé
3404 3403
  **/
3405 3404
 function charger_php_extension($module) {
3406
-	if (extension_loaded($module)) {
3407
-		return true;
3408
-	}
3409
-	return false;
3405
+    if (extension_loaded($module)) {
3406
+        return true;
3407
+    }
3408
+    return false;
3410 3409
 }
3411 3410
 
3412 3411
 
@@ -3417,8 +3416,8 @@  discard block
 block discarded – undo
3417 3416
  *     true si et seulement si la configuration autorise le code HTML5 sur le site public
3418 3417
  **/
3419 3418
 function html5_permis() {
3420
-	return (isset($GLOBALS['meta']['version_html_max'])
3421
-		and ('html5' == $GLOBALS['meta']['version_html_max']));
3419
+    return (isset($GLOBALS['meta']['version_html_max'])
3420
+        and ('html5' == $GLOBALS['meta']['version_html_max']));
3422 3421
 }
3423 3422
 
3424 3423
 /**
@@ -3428,30 +3427,30 @@  discard block
 block discarded – undo
3428 3427
  * @return array
3429 3428
  */
3430 3429
 function formats_image_acceptables($gd = null, $svg_allowed = true) {
3431
-	$formats = null;
3432
-	if (!is_null($gd)) {
3433
-		$config = ($gd ? "gd_formats" : "formats_graphiques");
3434
-		if (isset($GLOBALS['meta'][$config])) {
3435
-			$formats = $GLOBALS['meta'][$config];
3436
-			$formats = explode(',', $formats);
3437
-			$formats = array_filter($formats);
3438
-			$formats = array_map('trim', $formats);
3439
-		}
3440
-	}
3441
-	if (is_null($formats)) {
3442
-		include_spip('inc/filtres_images_lib_mini');
3443
-		$formats = _image_extensions_acceptees_en_entree();
3444
-	}
3445
-
3446
-	if ($svg_allowed) {
3447
-		if (!in_array('svg', $formats)) {
3448
-			$formats[] = 'svg';
3449
-		}
3450
-	}
3451
-	else {
3452
-		$formats = array_diff($formats, ['svg']);
3453
-	}
3454
-	return $formats;
3430
+    $formats = null;
3431
+    if (!is_null($gd)) {
3432
+        $config = ($gd ? "gd_formats" : "formats_graphiques");
3433
+        if (isset($GLOBALS['meta'][$config])) {
3434
+            $formats = $GLOBALS['meta'][$config];
3435
+            $formats = explode(',', $formats);
3436
+            $formats = array_filter($formats);
3437
+            $formats = array_map('trim', $formats);
3438
+        }
3439
+    }
3440
+    if (is_null($formats)) {
3441
+        include_spip('inc/filtres_images_lib_mini');
3442
+        $formats = _image_extensions_acceptees_en_entree();
3443
+    }
3444
+
3445
+    if ($svg_allowed) {
3446
+        if (!in_array('svg', $formats)) {
3447
+            $formats[] = 'svg';
3448
+        }
3449
+    }
3450
+    else {
3451
+        $formats = array_diff($formats, ['svg']);
3452
+    }
3453
+    return $formats;
3455 3454
 }
3456 3455
 
3457 3456
 /**
@@ -3460,21 +3459,21 @@  discard block
 block discarded – undo
3460 3459
  * @return array|bool
3461 3460
  */
3462 3461
 function spip_getimagesize($fichier) {
3463
-	if (!$imagesize = @getimagesize($fichier)) {
3462
+    if (!$imagesize = @getimagesize($fichier)) {
3464 3463
 
3465
-		include_spip("inc/svg");
3466
-		if ($attrs = svg_lire_attributs($fichier)) {
3467
-			list($width, $height, $viewbox) = svg_getimagesize_from_attr($attrs);
3468
-			$imagesize = [
3469
-				$width,
3470
-				$height,
3471
-				IMAGETYPE_SVG,
3472
-				"width=\"{$width}\" height=\"{$height}\"",
3473
-				"mime" => "image/svg+xml"
3474
-			];
3475
-		}
3476
-	}
3477
-	return $imagesize;
3464
+        include_spip("inc/svg");
3465
+        if ($attrs = svg_lire_attributs($fichier)) {
3466
+            list($width, $height, $viewbox) = svg_getimagesize_from_attr($attrs);
3467
+            $imagesize = [
3468
+                $width,
3469
+                $height,
3470
+                IMAGETYPE_SVG,
3471
+                "width=\"{$width}\" height=\"{$height}\"",
3472
+                "mime" => "image/svg+xml"
3473
+            ];
3474
+        }
3475
+    }
3476
+    return $imagesize;
3478 3477
 }
3479 3478
 
3480 3479
 
@@ -3494,7 +3493,7 @@  discard block
 block discarded – undo
3494 3493
  * @return mixed Valeur de la meta.
3495 3494
  **/
3496 3495
 function lire_meta($nom) {
3497
-	return isset($GLOBALS['meta'][$nom]) ? $GLOBALS['meta'][$nom] : null;
3496
+    return isset($GLOBALS['meta'][$nom]) ? $GLOBALS['meta'][$nom] : null;
3498 3497
 }
3499 3498
 
3500 3499
 
@@ -3516,130 +3515,130 @@  discard block
 block discarded – undo
3516 3515
  * @param string $statut
3517 3516
  */
3518 3517
 function avertir_auteurs($nom, $message, $statut = '') {
3519
-	$alertes = $GLOBALS['meta']['message_alertes_auteurs'];
3520
-	if (!$alertes
3521
-		or !is_array($alertes = unserialize($alertes))
3522
-	) {
3523
-		$alertes = array();
3524
-	}
3518
+    $alertes = $GLOBALS['meta']['message_alertes_auteurs'];
3519
+    if (!$alertes
3520
+        or !is_array($alertes = unserialize($alertes))
3521
+    ) {
3522
+        $alertes = array();
3523
+    }
3525 3524
 
3526
-	if (!isset($alertes[$statut])) {
3527
-		$alertes[$statut] = array();
3528
-	}
3529
-	$alertes[$statut][$nom] = $message;
3530
-	ecrire_meta("message_alertes_auteurs", serialize($alertes));
3525
+    if (!isset($alertes[$statut])) {
3526
+        $alertes[$statut] = array();
3527
+    }
3528
+    $alertes[$statut][$nom] = $message;
3529
+    ecrire_meta("message_alertes_auteurs", serialize($alertes));
3531 3530
 }
3532 3531
 
3533 3532
 if (PHP_VERSION_ID < 50500) {
3534
-	if (!function_exists('array_column')) {
3535
-		/**
3536
-		 * Returns the values from a single column of the input array, identified by
3537
-		 * the $columnKey.
3538
-		 *
3539
-		 * Optionally, you may provide an $indexKey to index the values in the returned
3540
-		 * array by the values from the $indexKey column in the input array.
3541
-		 *
3542
-		 * @link http://php.net/manual/fr/function.array-column.php
3543
-		 * @link https://github.com/ramsey/array_column/blob/master/src/array_column.php
3544
-		 * @copyright Copyright (c) Ben Ramsey (http://benramsey.com)
3545
-		 * @license http://opensource.org/licenses/MIT MIT
3546
-		 *
3547
-		 * @param array $input A multi-dimensional array (record set) from which to pull
3548
-		 *                     a column of values.
3549
-		 * @param mixed $columnKey The column of values to return. This value may be the
3550
-		 *                         integer key of the column you wish to retrieve, or it
3551
-		 *                         may be the string key name for an associative array.
3552
-		 * @param mixed $indexKey (Optional.) The column to use as the index/keys for
3553
-		 *                        the returned array. This value may be the integer key
3554
-		 *                        of the column, or it may be the string key name.
3555
-		 * @return array
3556
-		 */
3557
-		function array_column($input = null, $columnKey = null, $indexKey = null)
3558
-		{
3559
-			// Using func_get_args() in order to check for proper number of
3560
-			// parameters and trigger errors exactly as the built-in array_column()
3561
-			// does in PHP 5.5.
3562
-			$argc = func_num_args();
3563
-			$params = func_get_args();
3564
-
3565
-			if ($argc < 2) {
3566
-				trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
3567
-				return null;
3568
-			}
3569
-
3570
-			if (!is_array($params[0])) {
3571
-				trigger_error(
3572
-					'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
3573
-					E_USER_WARNING
3574
-				);
3575
-				return null;
3576
-			}
3577
-
3578
-			if (!is_int($params[1])
3579
-				&& !is_float($params[1])
3580
-				&& !is_string($params[1])
3581
-				&& $params[1] !== null
3582
-				&& !(is_object($params[1]) && method_exists($params[1], '__toString'))
3583
-			) {
3584
-				trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
3585
-				return false;
3586
-			}
3587
-
3588
-			if (isset($params[2])
3589
-				&& !is_int($params[2])
3590
-				&& !is_float($params[2])
3591
-				&& !is_string($params[2])
3592
-				&& !(is_object($params[2]) && method_exists($params[2], '__toString'))
3593
-			) {
3594
-				trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
3595
-				return false;
3596
-			}
3597
-
3598
-			$paramsInput = $params[0];
3599
-			$paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
3600
-
3601
-			$paramsIndexKey = null;
3602
-			if (isset($params[2])) {
3603
-				if (is_float($params[2]) || is_int($params[2])) {
3604
-					$paramsIndexKey = (int) $params[2];
3605
-				} else {
3606
-					$paramsIndexKey = (string) $params[2];
3607
-				}
3608
-			}
3609
-
3610
-			$resultArray = array();
3611
-
3612
-			foreach ($paramsInput as $row) {
3613
-				$key = $value = null;
3614
-				$keySet = $valueSet = false;
3615
-
3616
-				if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
3617
-					$keySet = true;
3618
-					$key = (string) $row[$paramsIndexKey];
3619
-				}
3620
-
3621
-				if ($paramsColumnKey === null) {
3622
-					$valueSet = true;
3623
-					$value = $row;
3624
-				} elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
3625
-					$valueSet = true;
3626
-					$value = $row[$paramsColumnKey];
3627
-				}
3628
-
3629
-				if ($valueSet) {
3630
-					if ($keySet) {
3631
-						$resultArray[$key] = $value;
3632
-					} else {
3633
-						$resultArray[] = $value;
3634
-					}
3635
-				}
3636
-
3637
-			}
3638
-
3639
-			return $resultArray;
3640
-		}
3641
-
3642
-	}
3533
+    if (!function_exists('array_column')) {
3534
+        /**
3535
+         * Returns the values from a single column of the input array, identified by
3536
+         * the $columnKey.
3537
+         *
3538
+         * Optionally, you may provide an $indexKey to index the values in the returned
3539
+         * array by the values from the $indexKey column in the input array.
3540
+         *
3541
+         * @link http://php.net/manual/fr/function.array-column.php
3542
+         * @link https://github.com/ramsey/array_column/blob/master/src/array_column.php
3543
+         * @copyright Copyright (c) Ben Ramsey (http://benramsey.com)
3544
+         * @license http://opensource.org/licenses/MIT MIT
3545
+         *
3546
+         * @param array $input A multi-dimensional array (record set) from which to pull
3547
+         *                     a column of values.
3548
+         * @param mixed $columnKey The column of values to return. This value may be the
3549
+         *                         integer key of the column you wish to retrieve, or it
3550
+         *                         may be the string key name for an associative array.
3551
+         * @param mixed $indexKey (Optional.) The column to use as the index/keys for
3552
+         *                        the returned array. This value may be the integer key
3553
+         *                        of the column, or it may be the string key name.
3554
+         * @return array
3555
+         */
3556
+        function array_column($input = null, $columnKey = null, $indexKey = null)
3557
+        {
3558
+            // Using func_get_args() in order to check for proper number of
3559
+            // parameters and trigger errors exactly as the built-in array_column()
3560
+            // does in PHP 5.5.
3561
+            $argc = func_num_args();
3562
+            $params = func_get_args();
3563
+
3564
+            if ($argc < 2) {
3565
+                trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
3566
+                return null;
3567
+            }
3568
+
3569
+            if (!is_array($params[0])) {
3570
+                trigger_error(
3571
+                    'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
3572
+                    E_USER_WARNING
3573
+                );
3574
+                return null;
3575
+            }
3576
+
3577
+            if (!is_int($params[1])
3578
+                && !is_float($params[1])
3579
+                && !is_string($params[1])
3580
+                && $params[1] !== null
3581
+                && !(is_object($params[1]) && method_exists($params[1], '__toString'))
3582
+            ) {
3583
+                trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
3584
+                return false;
3585
+            }
3586
+
3587
+            if (isset($params[2])
3588
+                && !is_int($params[2])
3589
+                && !is_float($params[2])
3590
+                && !is_string($params[2])
3591
+                && !(is_object($params[2]) && method_exists($params[2], '__toString'))
3592
+            ) {
3593
+                trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
3594
+                return false;
3595
+            }
3596
+
3597
+            $paramsInput = $params[0];
3598
+            $paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
3599
+
3600
+            $paramsIndexKey = null;
3601
+            if (isset($params[2])) {
3602
+                if (is_float($params[2]) || is_int($params[2])) {
3603
+                    $paramsIndexKey = (int) $params[2];
3604
+                } else {
3605
+                    $paramsIndexKey = (string) $params[2];
3606
+                }
3607
+            }
3608
+
3609
+            $resultArray = array();
3610
+
3611
+            foreach ($paramsInput as $row) {
3612
+                $key = $value = null;
3613
+                $keySet = $valueSet = false;
3614
+
3615
+                if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
3616
+                    $keySet = true;
3617
+                    $key = (string) $row[$paramsIndexKey];
3618
+                }
3619
+
3620
+                if ($paramsColumnKey === null) {
3621
+                    $valueSet = true;
3622
+                    $value = $row;
3623
+                } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
3624
+                    $valueSet = true;
3625
+                    $value = $row[$paramsColumnKey];
3626
+                }
3627
+
3628
+                if ($valueSet) {
3629
+                    if ($keySet) {
3630
+                        $resultArray[$key] = $value;
3631
+                    } else {
3632
+                        $resultArray[] = $value;
3633
+                    }
3634
+                }
3635
+
3636
+            }
3637
+
3638
+            return $resultArray;
3639
+        }
3640
+
3641
+    }
3643 3642
 }
3644 3643
 
3645 3644
 /**
@@ -3653,8 +3652,8 @@  discard block
 block discarded – undo
3653 3652
  * @return string|string[]
3654 3653
  */
3655 3654
 function spip_sanitize_classname($classes) {
3656
-	if (is_array($classes)) {
3657
-		return array_map('spip_sanitize_classname', $classes);
3658
-	}
3659
-	return preg_replace("/[^ 0-9a-z_\-+@]/i", "", $classes);
3655
+    if (is_array($classes)) {
3656
+        return array_map('spip_sanitize_classname', $classes);
3657
+    }
3658
+    return preg_replace("/[^ 0-9a-z_\-+@]/i", "", $classes);
3660 3659
 }
Please login to merge, or discard this patch.
Braces   +5 added lines, -6 removed lines patch added patch discarded remove patch
@@ -1429,8 +1429,7 @@  discard block
 block discarded – undo
1429 1429
 		and $f = find_in_theme("$file_svg_generique")) {
1430 1430
 		if ($fsize = substr($f,0,-6) . $m[1] . ".svg" and file_exists($fsize)) {
1431 1431
 			return $themefiles["$subdir$file"] = $fsize;
1432
-		}
1433
-		else {
1432
+		} else {
1434 1433
 			return $themefiles["$subdir$file"] = "$f?".$m[1]."px";
1435 1434
 		}
1436 1435
 	}
@@ -2374,12 +2373,13 @@  discard block
 block discarded – undo
2374 2373
 		define('_DIR_CHMOD', $pi);
2375 2374
 	}
2376 2375
 
2377
-	if (!isset($GLOBALS['test_dirs']))
2378
-		// Pas $pi car il est bon de le mettre hors ecriture apres intstall
2376
+	if (!isset($GLOBALS['test_dirs'])) {
2377
+			// Pas $pi car il est bon de le mettre hors ecriture apres intstall
2379 2378
 		// il sera rajoute automatiquement si besoin a l'etape 2 de l'install
2380 2379
 	{
2381 2380
 		$GLOBALS['test_dirs'] = array($pa, $ti, $ta);
2382 2381
 	}
2382
+	}
2383 2383
 
2384 2384
 	// Declaration des fichiers
2385 2385
 
@@ -3447,8 +3447,7 @@  discard block
 block discarded – undo
3447 3447
 		if (!in_array('svg', $formats)) {
3448 3448
 			$formats[] = 'svg';
3449 3449
 		}
3450
-	}
3451
-	else {
3450
+	} else {
3452 3451
 		$formats = array_diff($formats, ['svg']);
3453 3452
 	}
3454 3453
 	return $formats;
Please login to merge, or discard this patch.