Completed
Push — master ( 6c9939...4ccfda )
by cam
01:06
created
ecrire/inc/puce_statut.php 1 patch
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -18,18 +18,18 @@  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
 if (!defined('_ACTIVER_PUCE_RAPIDE')) {
25
-	/**
26
-	 * Activer le changement rapide de statut sur les listes d'objets ?
27
-	 *
28
-	 * Peut ralentir un site sur des listes très longues.
29
-	 *
30
-	 * @var bool
31
-	 **/
32
-	define('_ACTIVER_PUCE_RAPIDE', true);
25
+    /**
26
+     * Activer le changement rapide de statut sur les listes d'objets ?
27
+     *
28
+     * Peut ralentir un site sur des listes très longues.
29
+     *
30
+     * @var bool
31
+     **/
32
+    define('_ACTIVER_PUCE_RAPIDE', true);
33 33
 }
34 34
 
35 35
 /**
@@ -57,31 +57,31 @@  discard block
 block discarded – undo
57 57
  *     Code HTML de l'image de puce de statut à insérer (et du menu de changement si présent)
58 58
  */
59 59
 function inc_puce_statut_dist(
60
-	$id_objet,
61
-	$statut,
62
-	$id_parent,
63
-	$type,
64
-	$ajax = false,
65
-	$menu_rapide = _ACTIVER_PUCE_RAPIDE
60
+    $id_objet,
61
+    $statut,
62
+    $id_parent,
63
+    $type,
64
+    $ajax = false,
65
+    $menu_rapide = _ACTIVER_PUCE_RAPIDE
66 66
 ) {
67
-	static $f_puce_statut = [];
68
-	$type = objet_type($type);
69
-	// cas prioritaire : fonction perso, qui permet aussi de gerer les cas historiques
70
-	if (!isset($f_puce_statut[$type]) or is_null($f_puce_statut[$type])) {
71
-		$f_puce_statut[$type] = charger_fonction($type, 'puce_statut', true);
72
-	}
73
-	if ($f_puce_statut[$type]) {
74
-		return $f_puce_statut[$type]($id_objet, $statut, $id_parent, $type, $ajax, $menu_rapide);
75
-	}
76
-
77
-	// si statut_image trouve quelque chose (et '' est quelque chose)
78
-	// composer une puce, avec si possible changement rapide
79
-	elseif (!is_null($puce = puce_statut_changement_rapide($id_objet, $statut, $id_parent, $type, $ajax, $menu_rapide))) {
80
-		return $puce;
81
-	} // sinon fausse puce avec le type de l'image
82
-	else {
83
-		return http_img_pack("$type-16.png", '');
84
-	}
67
+    static $f_puce_statut = [];
68
+    $type = objet_type($type);
69
+    // cas prioritaire : fonction perso, qui permet aussi de gerer les cas historiques
70
+    if (!isset($f_puce_statut[$type]) or is_null($f_puce_statut[$type])) {
71
+        $f_puce_statut[$type] = charger_fonction($type, 'puce_statut', true);
72
+    }
73
+    if ($f_puce_statut[$type]) {
74
+        return $f_puce_statut[$type]($id_objet, $statut, $id_parent, $type, $ajax, $menu_rapide);
75
+    }
76
+
77
+    // si statut_image trouve quelque chose (et '' est quelque chose)
78
+    // composer une puce, avec si possible changement rapide
79
+    elseif (!is_null($puce = puce_statut_changement_rapide($id_objet, $statut, $id_parent, $type, $ajax, $menu_rapide))) {
80
+        return $puce;
81
+    } // sinon fausse puce avec le type de l'image
82
+    else {
83
+        return http_img_pack("$type-16.png", '');
84
+    }
85 85
 }
86 86
 
87 87
 /**
@@ -110,41 +110,41 @@  discard block
 block discarded – undo
110 110
  *   null si pas capable de déterminer l'image
111 111
  */
112 112
 function statut_image($objet, $statut) {
113
-	$src = null;
114
-	$table = table_objet_sql($objet);
115
-	$desc = lister_tables_objets_sql($table);
116
-	if (isset($desc['statut_images'])) {
117
-		// si une declaration statut_images
118
-		// mais rien pour le statut demande, ne rien afficher
119
-		$src = '';
120
-		if (isset($desc['statut_images'][$statut])) {
121
-			$src = $desc['statut_images'][$statut];
122
-		} // sinon image par defaut ?
123
-		elseif (isset($desc['statut_images'][0])) {
124
-			$src = $desc['statut_images'][0];
125
-		}
126
-	} else {
127
-		switch ($statut) {
128
-			case 'prepa':
129
-				$src = 'puce-preparer-xx.svg?12px';
130
-				break;
131
-			case 'prop':
132
-				$src = 'puce-proposer-xx.svg?12px';
133
-				break;
134
-			case 'publie':
135
-				$src = 'puce-publier-xx.svg?12px';
136
-				break;
137
-			case 'refuse':
138
-				$src = 'puce-refuser-xx.svg?12px';
139
-				break;
140
-			case 'poubelle':
141
-			case 'poub':
142
-				$src = 'puce-supprimer-xx.svg?12px';
143
-				break;
144
-		}
145
-	}
146
-
147
-	return $src;
113
+    $src = null;
114
+    $table = table_objet_sql($objet);
115
+    $desc = lister_tables_objets_sql($table);
116
+    if (isset($desc['statut_images'])) {
117
+        // si une declaration statut_images
118
+        // mais rien pour le statut demande, ne rien afficher
119
+        $src = '';
120
+        if (isset($desc['statut_images'][$statut])) {
121
+            $src = $desc['statut_images'][$statut];
122
+        } // sinon image par defaut ?
123
+        elseif (isset($desc['statut_images'][0])) {
124
+            $src = $desc['statut_images'][0];
125
+        }
126
+    } else {
127
+        switch ($statut) {
128
+            case 'prepa':
129
+                $src = 'puce-preparer-xx.svg?12px';
130
+                break;
131
+            case 'prop':
132
+                $src = 'puce-proposer-xx.svg?12px';
133
+                break;
134
+            case 'publie':
135
+                $src = 'puce-publier-xx.svg?12px';
136
+                break;
137
+            case 'refuse':
138
+                $src = 'puce-refuser-xx.svg?12px';
139
+                break;
140
+            case 'poubelle':
141
+            case 'poub':
142
+                $src = 'puce-supprimer-xx.svg?12px';
143
+                break;
144
+        }
145
+    }
146
+
147
+    return $src;
148 148
 }
149 149
 
150 150
 /**
@@ -172,40 +172,40 @@  discard block
 block discarded – undo
172 172
  * @return string
173 173
  */
174 174
 function statut_titre($objet, $statut) {
175
-	$titre = '';
176
-	$table = table_objet_sql($objet);
177
-	$desc = lister_tables_objets_sql($table);
178
-	if (isset($desc['statut_titres'])) {
179
-		// si une declaration statut_titres
180
-		// mais rien pour le statut demande, ne rien afficher
181
-		if (isset($desc['statut_titres'][$statut])) {
182
-			$titre = $desc['statut_titres'][$statut];
183
-		} // sinon image par defaut ?
184
-		elseif (isset($desc['statut_titres'][0])) {
185
-			$titre = $desc['statut_titres'][0];
186
-		}
187
-	} else {
188
-		switch ($statut) {
189
-			case 'prepa':
190
-				$titre = 'texte_statut_en_cours_redaction';
191
-				break;
192
-			case 'prop':
193
-				$titre = 'texte_statut_propose_evaluation';
194
-				break;
195
-			case 'publie':
196
-				$titre = 'texte_statut_publie';
197
-				break;
198
-			case 'refuse':
199
-				$titre = 'texte_statut_refuse';
200
-				break;
201
-			case 'poubelle':
202
-			case 'poub':
203
-				$titre = 'texte_statut_poubelle';
204
-				break;
205
-		}
206
-	}
207
-
208
-	return $titre ? _T($titre) : '';
175
+    $titre = '';
176
+    $table = table_objet_sql($objet);
177
+    $desc = lister_tables_objets_sql($table);
178
+    if (isset($desc['statut_titres'])) {
179
+        // si une declaration statut_titres
180
+        // mais rien pour le statut demande, ne rien afficher
181
+        if (isset($desc['statut_titres'][$statut])) {
182
+            $titre = $desc['statut_titres'][$statut];
183
+        } // sinon image par defaut ?
184
+        elseif (isset($desc['statut_titres'][0])) {
185
+            $titre = $desc['statut_titres'][0];
186
+        }
187
+    } else {
188
+        switch ($statut) {
189
+            case 'prepa':
190
+                $titre = 'texte_statut_en_cours_redaction';
191
+                break;
192
+            case 'prop':
193
+                $titre = 'texte_statut_propose_evaluation';
194
+                break;
195
+            case 'publie':
196
+                $titre = 'texte_statut_publie';
197
+                break;
198
+            case 'refuse':
199
+                $titre = 'texte_statut_refuse';
200
+                break;
201
+            case 'poubelle':
202
+            case 'poub':
203
+                $titre = 'texte_statut_poubelle';
204
+                break;
205
+        }
206
+    }
207
+
208
+    return $titre ? _T($titre) : '';
209 209
 }
210 210
 
211 211
 
@@ -225,37 +225,37 @@  discard block
 block discarded – undo
225 225
  * @return string
226 226
  */
227 227
 function statut_texte_instituer($objet, $statut) {
228
-	$texte = '';
229
-	$table = table_objet_sql($objet);
230
-	$desc = lister_tables_objets_sql($table);
231
-	if (isset($desc['statut_textes_instituer'])) {
232
-		// si une declaration statut_titres
233
-		// mais rien pour le statut demande, ne rien afficher
234
-		if (isset($desc['statut_textes_instituer'][$statut])) {
235
-			$texte = $desc['statut_textes_instituer'][$statut];
236
-		}
237
-	} else {
238
-		switch ($statut) {
239
-			case 'prepa':
240
-				$texte = 'texte_statut_en_cours_redaction';
241
-				break;
242
-			case 'prop':
243
-				$texte = 'texte_statut_propose_evaluation';
244
-				break;
245
-			case 'publie':
246
-				$texte = 'texte_statut_publie';
247
-				break;
248
-			case 'refuse':
249
-				$texte = 'texte_statut_refuse';
250
-				break;
251
-			case 'poubelle':
252
-			case 'poub':
253
-				$texte = 'texte_statut_poubelle';
254
-				break;
255
-		}
256
-	}
257
-
258
-	return $texte ? _T($texte) : '';
228
+    $texte = '';
229
+    $table = table_objet_sql($objet);
230
+    $desc = lister_tables_objets_sql($table);
231
+    if (isset($desc['statut_textes_instituer'])) {
232
+        // si une declaration statut_titres
233
+        // mais rien pour le statut demande, ne rien afficher
234
+        if (isset($desc['statut_textes_instituer'][$statut])) {
235
+            $texte = $desc['statut_textes_instituer'][$statut];
236
+        }
237
+    } else {
238
+        switch ($statut) {
239
+            case 'prepa':
240
+                $texte = 'texte_statut_en_cours_redaction';
241
+                break;
242
+            case 'prop':
243
+                $texte = 'texte_statut_propose_evaluation';
244
+                break;
245
+            case 'publie':
246
+                $texte = 'texte_statut_publie';
247
+                break;
248
+            case 'refuse':
249
+                $texte = 'texte_statut_refuse';
250
+                break;
251
+            case 'poubelle':
252
+            case 'poub':
253
+                $texte = 'texte_statut_poubelle';
254
+                break;
255
+        }
256
+    }
257
+
258
+    return $texte ? _T($texte) : '';
259 259
 }
260 260
 
261 261
 
@@ -275,16 +275,16 @@  discard block
 block discarded – undo
275 275
  * @return string
276 276
  */
277 277
 function puce_statut_auteur_dist($id, $statut, $id_parent, $type, $ajax = '', $menu_rapide = _ACTIVER_PUCE_RAPIDE) {
278
-	$img = statut_image('auteur', $statut);
279
-	if (!$img) {
280
-		return '';
281
-	}
282
-	$alt = statut_titre('auteur', $statut);
278
+    $img = statut_image('auteur', $statut);
279
+    if (!$img) {
280
+        return '';
281
+    }
282
+    $alt = statut_titre('auteur', $statut);
283 283
 
284
-	$fond = '';
285
-	$titre = '';
284
+    $fond = '';
285
+    $titre = '';
286 286
 
287
-	/*
287
+    /*
288 288
 	if ($type != 'auteur') {
289 289
 	  $img2 = chemin_image('del-16.png');
290 290
 	  $titre = _T('titre_image_redacteur');
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 	}
295 295
 	*/
296 296
 
297
-	return http_img_pack($img, $alt, $fond, $alt);
297
+    return http_img_pack($img, $alt, $fond, $alt);
298 298
 }
299 299
 
300 300
 
301 301
 function puce_statut_rubrique_dist($id, $statut, $id_rubrique, $type, $ajax = '', $menu_rapide = _ACTIVER_PUCE_RAPIDE) {
302
-	return http_img_pack('rubrique-16.png', '');
302
+    return http_img_pack('rubrique-16.png', '');
303 303
 }
304 304
 
305 305
 /**
@@ -323,110 +323,110 @@  discard block
 block discarded – undo
323 323
  *     Code HTML de l'image de puce de statut à insérer (et du menu de changement si présent)
324 324
  **/
325 325
 function puce_statut_changement_rapide(
326
-	$id,
327
-	$statut,
328
-	$id_rubrique,
329
-	$type = 'article',
330
-	$ajax = false,
331
-	$menu_rapide = _ACTIVER_PUCE_RAPIDE
326
+    $id,
327
+    $statut,
328
+    $id_rubrique,
329
+    $type = 'article',
330
+    $ajax = false,
331
+    $menu_rapide = _ACTIVER_PUCE_RAPIDE
332 332
 ) {
333
-	$src = statut_image($type, $statut);
334
-	if (!$src) {
335
-		return $src;
336
-	}
337
-
338
-	if (
339
-		!$id
340
-		or !_SPIP_AJAX
341
-		or !$menu_rapide
342
-	) {
343
-		$ajax_node = '';
344
-	} else {
345
-		$ajax_node = " class='imgstatut$type$id'";
346
-	}
347
-
348
-
349
-	$t = statut_titre($type, $statut);
350
-	$inser_puce = http_img_pack($src, $t, $ajax_node, $t);
351
-
352
-	if (!$ajax_node) {
353
-		return $inser_puce;
354
-	}
355
-
356
-	$table = table_objet_sql($type);
357
-	$desc = lister_tables_objets_sql($table);
358
-	if (!isset($desc['statut_textes_instituer'])) {
359
-		return $inser_puce;
360
-	}
361
-
362
-	if (!function_exists('autoriser')) {
363
-		include_spip('inc/autoriser');
364
-	}
365
-
366
-	// cas ou l'on a un parent connu (devrait disparaitre au profit du second cas plus generique)
367
-	if ($id_rubrique) {
368
-		if (!autoriser('publierdans', 'rubrique', $id_rubrique)) {
369
-			return $inser_puce;
370
-		}
371
-	} // si pas d'id_rubrique fourni, tester directement instituer type avec le statut publie
372
-	else {
373
-		if (!autoriser('instituer', $type, $id, null, ['statut' => 'publie'])) {
374
-			return $inser_puce;
375
-		}
376
-	}
377
-
378
-	$coord = array_flip(array_keys($desc['statut_textes_instituer']));
379
-	if (!isset($coord[$statut])) {
380
-		return $inser_puce;
381
-	}
382
-
383
-	$unit = 18/*widh de img*/ + 0/*padding*/
384
-	;
385
-	$margin = 0; /* marge a gauche + droite */
386
-	$zero = 0 /*border*/ + $margin / 2 + 0 /*padding*/
387
-	;
388
-	$clip = $zero + ($unit * $coord[$statut]);
389
-
390
-	if ($ajax) {
391
-		$width = $unit * (is_countable($desc['statut_textes_instituer']) ? count($desc['statut_textes_instituer']) : 0) + $margin;
392
-		$out = "<span class='puce_objet_fixe $type'>"
393
-			. $inser_puce
394
-			. '</span>'
395
-			. "<span class='puce_objet_popup $type statutdecal$type$id' style='width:{$width}px;margin-left:-{$clip}px;'>";
396
-		$i = 0;
397
-		foreach ($desc['statut_textes_instituer'] as $s => $t) {
398
-			$out .= afficher_script_statut($id, $type, -$zero - $i++ * $unit, statut_image($type, $s), $s, _T($t));
399
-		}
400
-		$out .= '</span>';
401
-
402
-		return $out;
403
-	} else {
404
-		$nom = 'puce_statut_';
405
-		$action = generer_url_ecrire('puce_statut', '', true);
406
-		$lang_dir = lang_dir(lang_typo());
407
-
408
-		return "<span class='puce_objet $type' id='$nom$type$id' dir='$lang_dir' data-puce-nom='$nom' data-puce-type='$type' data-puce-id='$id' data-puce-action='$action'>"
409
-		. $inser_puce
410
-		. '</span>';
411
-	}
333
+    $src = statut_image($type, $statut);
334
+    if (!$src) {
335
+        return $src;
336
+    }
337
+
338
+    if (
339
+        !$id
340
+        or !_SPIP_AJAX
341
+        or !$menu_rapide
342
+    ) {
343
+        $ajax_node = '';
344
+    } else {
345
+        $ajax_node = " class='imgstatut$type$id'";
346
+    }
347
+
348
+
349
+    $t = statut_titre($type, $statut);
350
+    $inser_puce = http_img_pack($src, $t, $ajax_node, $t);
351
+
352
+    if (!$ajax_node) {
353
+        return $inser_puce;
354
+    }
355
+
356
+    $table = table_objet_sql($type);
357
+    $desc = lister_tables_objets_sql($table);
358
+    if (!isset($desc['statut_textes_instituer'])) {
359
+        return $inser_puce;
360
+    }
361
+
362
+    if (!function_exists('autoriser')) {
363
+        include_spip('inc/autoriser');
364
+    }
365
+
366
+    // cas ou l'on a un parent connu (devrait disparaitre au profit du second cas plus generique)
367
+    if ($id_rubrique) {
368
+        if (!autoriser('publierdans', 'rubrique', $id_rubrique)) {
369
+            return $inser_puce;
370
+        }
371
+    } // si pas d'id_rubrique fourni, tester directement instituer type avec le statut publie
372
+    else {
373
+        if (!autoriser('instituer', $type, $id, null, ['statut' => 'publie'])) {
374
+            return $inser_puce;
375
+        }
376
+    }
377
+
378
+    $coord = array_flip(array_keys($desc['statut_textes_instituer']));
379
+    if (!isset($coord[$statut])) {
380
+        return $inser_puce;
381
+    }
382
+
383
+    $unit = 18/*widh de img*/ + 0/*padding*/
384
+    ;
385
+    $margin = 0; /* marge a gauche + droite */
386
+    $zero = 0 /*border*/ + $margin / 2 + 0 /*padding*/
387
+    ;
388
+    $clip = $zero + ($unit * $coord[$statut]);
389
+
390
+    if ($ajax) {
391
+        $width = $unit * (is_countable($desc['statut_textes_instituer']) ? count($desc['statut_textes_instituer']) : 0) + $margin;
392
+        $out = "<span class='puce_objet_fixe $type'>"
393
+            . $inser_puce
394
+            . '</span>'
395
+            . "<span class='puce_objet_popup $type statutdecal$type$id' style='width:{$width}px;margin-left:-{$clip}px;'>";
396
+        $i = 0;
397
+        foreach ($desc['statut_textes_instituer'] as $s => $t) {
398
+            $out .= afficher_script_statut($id, $type, -$zero - $i++ * $unit, statut_image($type, $s), $s, _T($t));
399
+        }
400
+        $out .= '</span>';
401
+
402
+        return $out;
403
+    } else {
404
+        $nom = 'puce_statut_';
405
+        $action = generer_url_ecrire('puce_statut', '', true);
406
+        $lang_dir = lang_dir(lang_typo());
407
+
408
+        return "<span class='puce_objet $type' id='$nom$type$id' dir='$lang_dir' data-puce-nom='$nom' data-puce-type='$type' data-puce-id='$id' data-puce-action='$action'>"
409
+        . $inser_puce
410
+        . '</span>';
411
+    }
412 412
 }
413 413
 
414 414
 
415 415
 function afficher_script_statut($id, $type, $n, $img, $statut, $titre, $act = '') {
416
-	$h = generer_action_auteur('instituer_objet', "$type-$id-$statut");
417
-	$t = supprimer_tags($titre);
416
+    $h = generer_action_auteur('instituer_objet', "$type-$id-$statut");
417
+    $t = supprimer_tags($titre);
418 418
 
419
-	return "<a href=\"#\" data-puce-id=\"$id\" data-puce-type=\"$type\" data-puce-decal=\"$n\" data-puce-action=\"$h\" title=\"$t\"$act>" . http_img_pack($img, $t) . '</a>';
419
+    return "<a href=\"#\" data-puce-id=\"$id\" data-puce-type=\"$type\" data-puce-decal=\"$n\" data-puce-action=\"$h\" title=\"$t\"$act>" . http_img_pack($img, $t) . '</a>';
420 420
 }
421 421
 
422 422
 // compat
423 423
 // La couleur du statut
424 424
 
425 425
 function puce_statut($statut, $atts = '') {
426
-	$src = statut_image('article', $statut);
427
-	if (!$src) {
428
-		return '';
429
-	}
426
+    $src = statut_image('article', $statut);
427
+    if (!$src) {
428
+        return '';
429
+    }
430 430
 
431
-	return http_img_pack($src, statut_titre('article', $statut), $atts);
431
+    return http_img_pack($src, statut_titre('article', $statut), $atts);
432 432
 }
Please login to merge, or discard this patch.
ecrire/inc/texte_mini.php 1 patch
Indentation   +401 added lines, -401 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
 include_spip('inc/filtres');
23 23
 include_spip('inc/lang');
@@ -39,21 +39,21 @@  discard block
 block discarded – undo
39 39
  **/
40 40
 function definir_puce() {
41 41
 
42
-	// Attention au sens, qui n'est pas defini de la meme facon dans
43
-	// l'espace prive (spip_lang est la langue de l'interface, lang_dir
44
-	// celle du texte) et public (spip_lang est la langue du texte)
45
-	$dir = _DIR_RESTREINT ? lang_dir() : lang_dir($GLOBALS['spip_lang']);
42
+    // Attention au sens, qui n'est pas defini de la meme facon dans
43
+    // l'espace prive (spip_lang est la langue de l'interface, lang_dir
44
+    // celle du texte) et public (spip_lang est la langue du texte)
45
+    $dir = _DIR_RESTREINT ? lang_dir() : lang_dir($GLOBALS['spip_lang']);
46 46
 
47
-	$p = 'puce' . (test_espace_prive() ? '_prive' : '');
48
-	if ($dir == 'rtl') {
49
-		$p .= '_rtl';
50
-	}
47
+    $p = 'puce' . (test_espace_prive() ? '_prive' : '');
48
+    if ($dir == 'rtl') {
49
+        $p .= '_rtl';
50
+    }
51 51
 
52
-	if (!isset($GLOBALS[$p])) {
53
-		$GLOBALS[$p] = '<span class="spip-puce ' . $dir . '"><b>–</b></span>';
54
-	}
52
+    if (!isset($GLOBALS[$p])) {
53
+        $GLOBALS[$p] = '<span class="spip-puce ' . $dir . '"><b>–</b></span>';
54
+    }
55 55
 
56
-	return $GLOBALS[$p];
56
+    return $GLOBALS[$p];
57 57
 }
58 58
 
59 59
 
@@ -61,14 +61,14 @@  discard block
 block discarded – undo
61 61
 // dont on souhaite qu'ils provoquent un saut de paragraphe
62 62
 
63 63
 if (!defined('_BALISES_BLOCS')) {
64
-	define(
65
-		'_BALISES_BLOCS',
66
-		'address|applet|article|aside|blockquote|button|center|d[ltd]|div|fieldset|fig(ure|caption)|footer|form|h[1-6r]|hgroup|head|header|iframe|li|map|marquee|nav|noscript|object|ol|pre|section|t(able|[rdh]|body|foot|extarea)|ul|script|style'
67
-	);
64
+    define(
65
+        '_BALISES_BLOCS',
66
+        'address|applet|article|aside|blockquote|button|center|d[ltd]|div|fieldset|fig(ure|caption)|footer|form|h[1-6r]|hgroup|head|header|iframe|li|map|marquee|nav|noscript|object|ol|pre|section|t(able|[rdh]|body|foot|extarea)|ul|script|style'
67
+    );
68 68
 }
69 69
 
70 70
 if (!defined('_BALISES_BLOCS_REGEXP')) {
71
-	define('_BALISES_BLOCS_REGEXP', ',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS');
71
+    define('_BALISES_BLOCS_REGEXP', ',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS');
72 72
 }
73 73
 
74 74
 //
@@ -80,111 +80,111 @@  discard block
 block discarded – undo
80 80
 // echappe est un div ou un span
81 81
 // https://code.spip.net/@code_echappement
82 82
 function code_echappement($rempl, $source = '', $no_transform = false, $mode = null) {
83
-	if (!strlen($rempl)) {
84
-		return '';
85
-	}
86
-
87
-	// Tester si on echappe en span ou en div
88
-	if (is_null($mode) or !in_array($mode, ['div', 'span'])) {
89
-		$mode = preg_match(',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS', $rempl) ? 'div' : 'span';
90
-	}
91
-
92
-	// Decouper en morceaux, base64 a des probleme selon la taille de la pile
93
-	$taille = 30000;
94
-	$return = '';
95
-	for ($i = 0; $i < strlen($rempl); $i += $taille) {
96
-		// Convertir en base64 et cacher dans un attribut
97
-		// utiliser les " pour eviter le re-encodage de ' et &#8217
98
-		$base64 = base64_encode(substr($rempl, $i, $taille));
99
-		$return .= "<$mode class=\"base64$source\" title=\"$base64\"></$mode>";
100
-	}
101
-
102
-	return $return;
83
+    if (!strlen($rempl)) {
84
+        return '';
85
+    }
86
+
87
+    // Tester si on echappe en span ou en div
88
+    if (is_null($mode) or !in_array($mode, ['div', 'span'])) {
89
+        $mode = preg_match(',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS', $rempl) ? 'div' : 'span';
90
+    }
91
+
92
+    // Decouper en morceaux, base64 a des probleme selon la taille de la pile
93
+    $taille = 30000;
94
+    $return = '';
95
+    for ($i = 0; $i < strlen($rempl); $i += $taille) {
96
+        // Convertir en base64 et cacher dans un attribut
97
+        // utiliser les " pour eviter le re-encodage de ' et &#8217
98
+        $base64 = base64_encode(substr($rempl, $i, $taille));
99
+        $return .= "<$mode class=\"base64$source\" title=\"$base64\"></$mode>";
100
+    }
101
+
102
+    return $return;
103 103
 }
104 104
 
105 105
 
106 106
 // Echapper les <html>...</ html>
107 107
 // https://code.spip.net/@traiter_echap_html_dist
108 108
 function traiter_echap_html_dist($regs) {
109
-	return $regs[3];
109
+    return $regs[3];
110 110
 }
111 111
 
112 112
 // Echapper les <pre>...</ pre>
113 113
 function traiter_echap_pre_dist($regs) {
114
-	// echapper les <code> dans <pre>
115
-	$pre = $regs[3];
116
-
117
-	// echapper les < dans <code>
118
-	// on utilise _PROTEGE_BLOCS pour simplifier le code et la maintenance, mais on est interesse que par <code>
119
-	if (
120
-		strpos($pre, '<') !== false
121
-		and preg_match_all(_PROTEGE_BLOCS, $pre, $matches, PREG_SET_ORDER)
122
-	) {
123
-		foreach ($matches as $m) {
124
-			if ($m[1] === 'code') {
125
-				$code = '<code' . $m[2] . '>' . spip_htmlspecialchars($m[3]) . '</code>';
126
-				$pre = str_replace($m[0], $code, $pre);
127
-			}
128
-		}
129
-	}
130
-	return "<pre>$pre</pre>";
114
+    // echapper les <code> dans <pre>
115
+    $pre = $regs[3];
116
+
117
+    // echapper les < dans <code>
118
+    // on utilise _PROTEGE_BLOCS pour simplifier le code et la maintenance, mais on est interesse que par <code>
119
+    if (
120
+        strpos($pre, '<') !== false
121
+        and preg_match_all(_PROTEGE_BLOCS, $pre, $matches, PREG_SET_ORDER)
122
+    ) {
123
+        foreach ($matches as $m) {
124
+            if ($m[1] === 'code') {
125
+                $code = '<code' . $m[2] . '>' . spip_htmlspecialchars($m[3]) . '</code>';
126
+                $pre = str_replace($m[0], $code, $pre);
127
+            }
128
+        }
129
+    }
130
+    return "<pre>$pre</pre>";
131 131
 }
132 132
 
133 133
 // Echapper les <code>...</ code>
134 134
 // https://code.spip.net/@traiter_echap_code_dist
135 135
 function traiter_echap_code_dist($regs) {
136
-	[, , $att, $corps] = $regs;
137
-	$echap = spip_htmlspecialchars($corps); // il ne faut pas passer dans entites_html, ne pas transformer les &#xxx; du code !
138
-
139
-	// ne pas mettre le <div...> s'il n'y a qu'une ligne
140
-	if (is_int(strpos($echap, "\n"))) {
141
-		// supprimer les sauts de ligne debut/fin
142
-		// (mais pas les espaces => ascii art).
143
-		$echap = preg_replace("/^[\n\r]+|[\n\r]+$/s", '', $echap);
144
-		$echap = nl2br($echap);
145
-		$echap = "<div style='text-align: left;' "
146
-			. "class='spip_code' dir='ltr'><code$att>"
147
-			. $echap . '</code></div>';
148
-	} else {
149
-		$echap = "<code$att class='spip_code' dir='ltr'>" . $echap . '</code>';
150
-	}
151
-
152
-	$echap = str_replace("\t", '&nbsp; &nbsp; &nbsp; &nbsp; ', $echap);
153
-	$echap = str_replace('  ', ' &nbsp;', $echap);
154
-
155
-	return $echap;
136
+    [, , $att, $corps] = $regs;
137
+    $echap = spip_htmlspecialchars($corps); // il ne faut pas passer dans entites_html, ne pas transformer les &#xxx; du code !
138
+
139
+    // ne pas mettre le <div...> s'il n'y a qu'une ligne
140
+    if (is_int(strpos($echap, "\n"))) {
141
+        // supprimer les sauts de ligne debut/fin
142
+        // (mais pas les espaces => ascii art).
143
+        $echap = preg_replace("/^[\n\r]+|[\n\r]+$/s", '', $echap);
144
+        $echap = nl2br($echap);
145
+        $echap = "<div style='text-align: left;' "
146
+            . "class='spip_code' dir='ltr'><code$att>"
147
+            . $echap . '</code></div>';
148
+    } else {
149
+        $echap = "<code$att class='spip_code' dir='ltr'>" . $echap . '</code>';
150
+    }
151
+
152
+    $echap = str_replace("\t", '&nbsp; &nbsp; &nbsp; &nbsp; ', $echap);
153
+    $echap = str_replace('  ', ' &nbsp;', $echap);
154
+
155
+    return $echap;
156 156
 }
157 157
 
158 158
 // Echapper les <cadre>...</ cadre> aka <frame>...</ frame>
159 159
 // https://code.spip.net/@traiter_echap_cadre_dist
160 160
 function traiter_echap_cadre_dist($regs) {
161
-	$echap = trim(entites_html($regs[3]));
162
-	// compter les lignes un peu plus finement qu'avec les \n
163
-	$lignes = explode("\n", trim($echap));
164
-	$n = 0;
165
-	foreach ($lignes as $l) {
166
-		$n += floor(strlen($l) / 60) + 1;
167
-	}
168
-	$n = max($n, 2);
169
-	$echap = "\n<textarea readonly='readonly' cols='40' rows='$n' class='spip_cadre' dir='ltr'>$echap</textarea>";
170
-
171
-	return $echap;
161
+    $echap = trim(entites_html($regs[3]));
162
+    // compter les lignes un peu plus finement qu'avec les \n
163
+    $lignes = explode("\n", trim($echap));
164
+    $n = 0;
165
+    foreach ($lignes as $l) {
166
+        $n += floor(strlen($l) / 60) + 1;
167
+    }
168
+    $n = max($n, 2);
169
+    $echap = "\n<textarea readonly='readonly' cols='40' rows='$n' class='spip_cadre' dir='ltr'>$echap</textarea>";
170
+
171
+    return $echap;
172 172
 }
173 173
 
174 174
 // https://code.spip.net/@traiter_echap_frame_dist
175 175
 function traiter_echap_frame_dist($regs) {
176
-	return traiter_echap_cadre_dist($regs);
176
+    return traiter_echap_cadre_dist($regs);
177 177
 }
178 178
 
179 179
 // https://code.spip.net/@traiter_echap_script_dist
180 180
 function traiter_echap_script_dist($regs) {
181
-	// rendre joli (et inactif) si c'est un script language=php
182
-	if (preg_match(',<script\b[^>]+php,ims', $regs[0])) {
183
-		return highlight_string($regs[0], true);
184
-	}
181
+    // rendre joli (et inactif) si c'est un script language=php
182
+    if (preg_match(',<script\b[^>]+php,ims', $regs[0])) {
183
+        return highlight_string($regs[0], true);
184
+    }
185 185
 
186
-	// Cas normal : le script passe tel quel
187
-	return $regs[0];
186
+    // Cas normal : le script passe tel quel
187
+    return $regs[0];
188 188
 }
189 189
 
190 190
 define('_PROTEGE_BLOCS', ',<(html|pre|code|cadre|frame|script|style)(\s[^>]*)?>(.*)</\1>,UimsS');
@@ -204,79 +204,79 @@  discard block
 block discarded – undo
204 204
  * @return string|string[]
205 205
  */
206 206
 function echappe_html(
207
-	$letexte,
208
-	$source = '',
209
-	$no_transform = false,
210
-	$preg = '',
211
-	$callback_prefix = ''
207
+    $letexte,
208
+    $source = '',
209
+    $no_transform = false,
210
+    $preg = '',
211
+    $callback_prefix = ''
212 212
 ) {
213
-	if (!is_string($letexte) or !strlen($letexte)) {
214
-		return $letexte;
215
-	}
216
-
217
-	// si le texte recu est long PCRE risque d'exploser, on
218
-	// fait donc un mic-mac pour augmenter pcre.backtrack_limit
219
-	if (($len = strlen($letexte)) > 100000) {
220
-		if (!$old = @ini_get('pcre.backtrack_limit')) {
221
-			$old = 100000;
222
-		}
223
-		if ($len > $old) {
224
-			$a = @ini_set('pcre.backtrack_limit', $len);
225
-			spip_log("ini_set pcre.backtrack_limit=$len ($old)");
226
-		}
227
-	}
228
-
229
-	if (
230
-		($preg or strpos($letexte, '<') !== false)
231
-		and preg_match_all($preg ?: _PROTEGE_BLOCS, $letexte, $matches, PREG_SET_ORDER)
232
-	) {
233
-		foreach ($matches as $regs) {
234
-			// echappements tels quels ?
235
-			if ($no_transform) {
236
-				$echap = $regs[0];
237
-			} // sinon les traiter selon le cas
238
-			else {
239
-				if (
240
-					function_exists($f = $callback_prefix . 'traiter_echap_' . strtolower($regs[1]))
241
-					or function_exists($f = $f . '_dist')
242
-				) {
243
-					$echap = $f($regs);
244
-				}
245
-			}
246
-
247
-			$p = strpos($letexte, (string) $regs[0]);
248
-			$letexte = substr_replace($letexte, code_echappement($echap, $source, $no_transform), $p, strlen($regs[0]));
249
-		}
250
-	}
251
-
252
-	if ($no_transform) {
253
-		return $letexte;
254
-	}
255
-
256
-	// Echapper le php pour faire joli (ici, c'est pas pour la securite)
257
-	// seulement si on a echappe les <script>
258
-	// (derogatoire car on ne peut pas faire passer < ? ... ? >
259
-	// dans une callback autonommee
260
-	if (strpos($preg ?: _PROTEGE_BLOCS, 'script') !== false) {
261
-		if (
262
-			strpos($letexte, '<' . '?') !== false and preg_match_all(
263
-				',<[?].*($|[?]>),UisS',
264
-				$letexte,
265
-				$matches,
266
-				PREG_SET_ORDER
267
-			)
268
-		) {
269
-			foreach ($matches as $regs) {
270
-				$letexte = str_replace(
271
-					$regs[0],
272
-					code_echappement(highlight_string($regs[0], true), $source),
273
-					$letexte
274
-				);
275
-			}
276
-		}
277
-	}
278
-
279
-	return $letexte;
213
+    if (!is_string($letexte) or !strlen($letexte)) {
214
+        return $letexte;
215
+    }
216
+
217
+    // si le texte recu est long PCRE risque d'exploser, on
218
+    // fait donc un mic-mac pour augmenter pcre.backtrack_limit
219
+    if (($len = strlen($letexte)) > 100000) {
220
+        if (!$old = @ini_get('pcre.backtrack_limit')) {
221
+            $old = 100000;
222
+        }
223
+        if ($len > $old) {
224
+            $a = @ini_set('pcre.backtrack_limit', $len);
225
+            spip_log("ini_set pcre.backtrack_limit=$len ($old)");
226
+        }
227
+    }
228
+
229
+    if (
230
+        ($preg or strpos($letexte, '<') !== false)
231
+        and preg_match_all($preg ?: _PROTEGE_BLOCS, $letexte, $matches, PREG_SET_ORDER)
232
+    ) {
233
+        foreach ($matches as $regs) {
234
+            // echappements tels quels ?
235
+            if ($no_transform) {
236
+                $echap = $regs[0];
237
+            } // sinon les traiter selon le cas
238
+            else {
239
+                if (
240
+                    function_exists($f = $callback_prefix . 'traiter_echap_' . strtolower($regs[1]))
241
+                    or function_exists($f = $f . '_dist')
242
+                ) {
243
+                    $echap = $f($regs);
244
+                }
245
+            }
246
+
247
+            $p = strpos($letexte, (string) $regs[0]);
248
+            $letexte = substr_replace($letexte, code_echappement($echap, $source, $no_transform), $p, strlen($regs[0]));
249
+        }
250
+    }
251
+
252
+    if ($no_transform) {
253
+        return $letexte;
254
+    }
255
+
256
+    // Echapper le php pour faire joli (ici, c'est pas pour la securite)
257
+    // seulement si on a echappe les <script>
258
+    // (derogatoire car on ne peut pas faire passer < ? ... ? >
259
+    // dans une callback autonommee
260
+    if (strpos($preg ?: _PROTEGE_BLOCS, 'script') !== false) {
261
+        if (
262
+            strpos($letexte, '<' . '?') !== false and preg_match_all(
263
+                ',<[?].*($|[?]>),UisS',
264
+                $letexte,
265
+                $matches,
266
+                PREG_SET_ORDER
267
+            )
268
+        ) {
269
+            foreach ($matches as $regs) {
270
+                $letexte = str_replace(
271
+                    $regs[0],
272
+                    code_echappement(highlight_string($regs[0], true), $source),
273
+                    $letexte
274
+                );
275
+            }
276
+        }
277
+    }
278
+
279
+    return $letexte;
280 280
 }
281 281
 
282 282
 //
@@ -285,58 +285,58 @@  discard block
 block discarded – undo
285 285
 // par propre() : exemple dans multi et dans typo()
286 286
 // https://code.spip.net/@echappe_retour
287 287
 function echappe_retour($letexte, $source = '', $filtre = '') {
288
-	if (strpos($letexte, (string) "base64$source")) {
289
-		# spip_log(spip_htmlspecialchars($letexte));  ## pour les curieux
290
-		$max_prof = 5;
291
-		while (
292
-			strpos($letexte, '<') !== false
293
-			and
294
-			preg_match_all(
295
-				',<(span|div)\sclass=[\'"]base64' . $source . '[\'"]\s(.*)>\s*</\1>,UmsS',
296
-				$letexte,
297
-				$regs,
298
-				PREG_SET_ORDER
299
-			)
300
-			and $max_prof--
301
-		) {
302
-			foreach ($regs as $reg) {
303
-				$rempl = base64_decode(extraire_attribut($reg[0], 'title'));
304
-				// recherche d'attributs supplementaires
305
-				$at = [];
306
-				foreach (['lang', 'dir'] as $attr) {
307
-					if ($a = extraire_attribut($reg[0], $attr)) {
308
-						$at[$attr] = $a;
309
-					}
310
-				}
311
-				if ($at) {
312
-					$rempl = '<' . $reg[1] . '>' . $rempl . '</' . $reg[1] . '>';
313
-					foreach ($at as $attr => $a) {
314
-						$rempl = inserer_attribut($rempl, $attr, $a);
315
-					}
316
-				}
317
-				if ($filtre) {
318
-					$rempl = $filtre($rempl);
319
-				}
320
-				$letexte = str_replace($reg[0], $rempl, $letexte);
321
-			}
322
-		}
323
-	}
324
-
325
-	return $letexte;
288
+    if (strpos($letexte, (string) "base64$source")) {
289
+        # spip_log(spip_htmlspecialchars($letexte));  ## pour les curieux
290
+        $max_prof = 5;
291
+        while (
292
+            strpos($letexte, '<') !== false
293
+            and
294
+            preg_match_all(
295
+                ',<(span|div)\sclass=[\'"]base64' . $source . '[\'"]\s(.*)>\s*</\1>,UmsS',
296
+                $letexte,
297
+                $regs,
298
+                PREG_SET_ORDER
299
+            )
300
+            and $max_prof--
301
+        ) {
302
+            foreach ($regs as $reg) {
303
+                $rempl = base64_decode(extraire_attribut($reg[0], 'title'));
304
+                // recherche d'attributs supplementaires
305
+                $at = [];
306
+                foreach (['lang', 'dir'] as $attr) {
307
+                    if ($a = extraire_attribut($reg[0], $attr)) {
308
+                        $at[$attr] = $a;
309
+                    }
310
+                }
311
+                if ($at) {
312
+                    $rempl = '<' . $reg[1] . '>' . $rempl . '</' . $reg[1] . '>';
313
+                    foreach ($at as $attr => $a) {
314
+                        $rempl = inserer_attribut($rempl, $attr, $a);
315
+                    }
316
+                }
317
+                if ($filtre) {
318
+                    $rempl = $filtre($rempl);
319
+                }
320
+                $letexte = str_replace($reg[0], $rempl, $letexte);
321
+            }
322
+        }
323
+    }
324
+
325
+    return $letexte;
326 326
 }
327 327
 
328 328
 // Reinserer le javascript de confiance (venant des modeles)
329 329
 
330 330
 // https://code.spip.net/@echappe_retour_modeles
331 331
 function echappe_retour_modeles($letexte, $interdire_scripts = false) {
332
-	$letexte = echappe_retour($letexte);
332
+    $letexte = echappe_retour($letexte);
333 333
 
334
-	// Dans les appels directs hors squelette, securiser aussi ici
335
-	if ($interdire_scripts) {
336
-		$letexte = interdire_scripts($letexte);
337
-	}
334
+    // Dans les appels directs hors squelette, securiser aussi ici
335
+    if ($interdire_scripts) {
336
+        $letexte = interdire_scripts($letexte);
337
+    }
338 338
 
339
-	return trim($letexte);
339
+    return trim($letexte);
340 340
 }
341 341
 
342 342
 
@@ -364,132 +364,132 @@  discard block
 block discarded – undo
364 364
  *     Texte coupé
365 365
  **/
366 366
 function couper($texte, $taille = 50, $suite = null) {
367
-	if (!($length = strlen($texte)) or $taille <= 0) {
368
-		return '';
369
-	}
370
-	$offset = 400 + 2 * $taille;
371
-	while (
372
-		$offset < $length
373
-		and strlen(preg_replace(',<(!--|\w|/)[^>]+>,Uims', '', substr($texte, 0, $offset))) < $taille
374
-	) {
375
-		$offset = 2 * $offset;
376
-	}
377
-	if (
378
-		$offset < $length
379
-		&& ($p_tag_ouvrant = strpos($texte, '<', $offset)) !== null
380
-	) {
381
-		$p_tag_fermant = strpos($texte, '>', $offset);
382
-		if ($p_tag_fermant && ($p_tag_fermant < $p_tag_ouvrant)) {
383
-			$offset = $p_tag_fermant + 1;
384
-		} // prolonger la coupe jusqu'au tag fermant suivant eventuel
385
-	}
386
-	$texte = substr($texte, 0, $offset); /* eviter de travailler sur 10ko pour extraire 150 caracteres */
387
-
388
-	if (!function_exists('nettoyer_raccourcis_typo')) {
389
-		include_spip('inc/lien');
390
-	}
391
-	$texte = nettoyer_raccourcis_typo($texte);
392
-
393
-	// balises de sauts de ligne et paragraphe
394
-	$texte = preg_replace('/<p( [^>]*)?' . '>/', "\r", $texte);
395
-	$texte = preg_replace('/<br( [^>]*)?' . '>/', "\n", $texte);
396
-
397
-	// on repasse les doubles \n en \r que nettoyer_raccourcis_typo() a pu modifier
398
-	$texte = str_replace("\n\n", "\r", $texte);
399
-
400
-	// supprimer les tags
401
-	$texte = supprimer_tags($texte);
402
-	$texte = trim(str_replace("\n", ' ', $texte));
403
-	$texte .= "\n";  // marquer la fin
404
-
405
-	// corriger la longueur de coupe
406
-	// en fonction de la presence de caracteres utf
407
-	if ($GLOBALS['meta']['charset'] == 'utf-8') {
408
-		$long = charset2unicode($texte);
409
-		$long = spip_substr($long, 0, max($taille, 1));
410
-		$nbcharutf = preg_match_all('/(&#[0-9]{3,6};)/S', $long, $matches);
411
-		$taille += $nbcharutf;
412
-	}
413
-
414
-
415
-	// couper au mot precedent
416
-	$long = spip_substr($texte, 0, max($taille - 4, 1));
417
-	$u = $GLOBALS['meta']['pcre_u'];
418
-	$court = preg_replace("/([^\s][\s]+)[^\s]*\n?$/" . $u, "\\1", $long);
419
-	if (is_null($suite)) {
420
-		$suite = (defined('_COUPER_SUITE') ? _COUPER_SUITE : '&nbsp;(...)');
421
-	}
422
-	$points = $suite;
423
-
424
-	// trop court ? ne pas faire de (...)
425
-	if (spip_strlen($court) < max(0.75 * $taille, 2)) {
426
-		$points = '';
427
-		$long = spip_substr($texte, 0, $taille);
428
-		$texte = preg_replace("/([^\s][\s]+)[^\s]*\n?$/" . $u, "\\1", $long);
429
-		// encore trop court ? couper au caractere
430
-		if (spip_strlen($texte) < 0.75 * $taille) {
431
-			$texte = $long;
432
-		}
433
-	} else {
434
-		$texte = $court;
435
-	}
436
-
437
-	if (strpos($texte, "\n")) {  // la fin est encore la : c'est qu'on n'a pas de texte de suite
438
-	$points = '';
439
-	}
440
-
441
-	// remettre les paragraphes
442
-	$texte = preg_replace("/\r+/", "\n\n", $texte);
443
-
444
-	// supprimer l'eventuelle entite finale mal coupee
445
-	$texte = preg_replace('/&#?[a-z0-9]*$/S', '', $texte);
446
-
447
-	return quote_amp(trim($texte)) . $points;
367
+    if (!($length = strlen($texte)) or $taille <= 0) {
368
+        return '';
369
+    }
370
+    $offset = 400 + 2 * $taille;
371
+    while (
372
+        $offset < $length
373
+        and strlen(preg_replace(',<(!--|\w|/)[^>]+>,Uims', '', substr($texte, 0, $offset))) < $taille
374
+    ) {
375
+        $offset = 2 * $offset;
376
+    }
377
+    if (
378
+        $offset < $length
379
+        && ($p_tag_ouvrant = strpos($texte, '<', $offset)) !== null
380
+    ) {
381
+        $p_tag_fermant = strpos($texte, '>', $offset);
382
+        if ($p_tag_fermant && ($p_tag_fermant < $p_tag_ouvrant)) {
383
+            $offset = $p_tag_fermant + 1;
384
+        } // prolonger la coupe jusqu'au tag fermant suivant eventuel
385
+    }
386
+    $texte = substr($texte, 0, $offset); /* eviter de travailler sur 10ko pour extraire 150 caracteres */
387
+
388
+    if (!function_exists('nettoyer_raccourcis_typo')) {
389
+        include_spip('inc/lien');
390
+    }
391
+    $texte = nettoyer_raccourcis_typo($texte);
392
+
393
+    // balises de sauts de ligne et paragraphe
394
+    $texte = preg_replace('/<p( [^>]*)?' . '>/', "\r", $texte);
395
+    $texte = preg_replace('/<br( [^>]*)?' . '>/', "\n", $texte);
396
+
397
+    // on repasse les doubles \n en \r que nettoyer_raccourcis_typo() a pu modifier
398
+    $texte = str_replace("\n\n", "\r", $texte);
399
+
400
+    // supprimer les tags
401
+    $texte = supprimer_tags($texte);
402
+    $texte = trim(str_replace("\n", ' ', $texte));
403
+    $texte .= "\n";  // marquer la fin
404
+
405
+    // corriger la longueur de coupe
406
+    // en fonction de la presence de caracteres utf
407
+    if ($GLOBALS['meta']['charset'] == 'utf-8') {
408
+        $long = charset2unicode($texte);
409
+        $long = spip_substr($long, 0, max($taille, 1));
410
+        $nbcharutf = preg_match_all('/(&#[0-9]{3,6};)/S', $long, $matches);
411
+        $taille += $nbcharutf;
412
+    }
413
+
414
+
415
+    // couper au mot precedent
416
+    $long = spip_substr($texte, 0, max($taille - 4, 1));
417
+    $u = $GLOBALS['meta']['pcre_u'];
418
+    $court = preg_replace("/([^\s][\s]+)[^\s]*\n?$/" . $u, "\\1", $long);
419
+    if (is_null($suite)) {
420
+        $suite = (defined('_COUPER_SUITE') ? _COUPER_SUITE : '&nbsp;(...)');
421
+    }
422
+    $points = $suite;
423
+
424
+    // trop court ? ne pas faire de (...)
425
+    if (spip_strlen($court) < max(0.75 * $taille, 2)) {
426
+        $points = '';
427
+        $long = spip_substr($texte, 0, $taille);
428
+        $texte = preg_replace("/([^\s][\s]+)[^\s]*\n?$/" . $u, "\\1", $long);
429
+        // encore trop court ? couper au caractere
430
+        if (spip_strlen($texte) < 0.75 * $taille) {
431
+            $texte = $long;
432
+        }
433
+    } else {
434
+        $texte = $court;
435
+    }
436
+
437
+    if (strpos($texte, "\n")) {  // la fin est encore la : c'est qu'on n'a pas de texte de suite
438
+    $points = '';
439
+    }
440
+
441
+    // remettre les paragraphes
442
+    $texte = preg_replace("/\r+/", "\n\n", $texte);
443
+
444
+    // supprimer l'eventuelle entite finale mal coupee
445
+    $texte = preg_replace('/&#?[a-z0-9]*$/S', '', $texte);
446
+
447
+    return quote_amp(trim($texte)) . $points;
448 448
 }
449 449
 
450 450
 
451 451
 // https://code.spip.net/@protege_js_modeles
452 452
 function protege_js_modeles($t) {
453
-	if (isset($GLOBALS['visiteur_session'])) {
454
-		if (preg_match_all(',<script.*?($|</script.),isS', $t, $r, PREG_SET_ORDER)) {
455
-			if (!defined('_PROTEGE_JS_MODELES')) {
456
-				include_spip('inc/acces');
457
-				define('_PROTEGE_JS_MODELES', creer_uniqid());
458
-			}
459
-			foreach ($r as $regs) {
460
-				$t = str_replace($regs[0], code_echappement($regs[0], 'javascript' . _PROTEGE_JS_MODELES), $t);
461
-			}
462
-		}
463
-		if (preg_match_all(',<\?php.*?($|\?' . '>),isS', $t, $r, PREG_SET_ORDER)) {
464
-			if (!defined('_PROTEGE_PHP_MODELES')) {
465
-				include_spip('inc/acces');
466
-				define('_PROTEGE_PHP_MODELES', creer_uniqid());
467
-			}
468
-			foreach ($r as $regs) {
469
-				$t = str_replace($regs[0], code_echappement($regs[0], 'php' . _PROTEGE_PHP_MODELES), $t);
470
-			}
471
-		}
472
-	}
473
-
474
-	return $t;
453
+    if (isset($GLOBALS['visiteur_session'])) {
454
+        if (preg_match_all(',<script.*?($|</script.),isS', $t, $r, PREG_SET_ORDER)) {
455
+            if (!defined('_PROTEGE_JS_MODELES')) {
456
+                include_spip('inc/acces');
457
+                define('_PROTEGE_JS_MODELES', creer_uniqid());
458
+            }
459
+            foreach ($r as $regs) {
460
+                $t = str_replace($regs[0], code_echappement($regs[0], 'javascript' . _PROTEGE_JS_MODELES), $t);
461
+            }
462
+        }
463
+        if (preg_match_all(',<\?php.*?($|\?' . '>),isS', $t, $r, PREG_SET_ORDER)) {
464
+            if (!defined('_PROTEGE_PHP_MODELES')) {
465
+                include_spip('inc/acces');
466
+                define('_PROTEGE_PHP_MODELES', creer_uniqid());
467
+            }
468
+            foreach ($r as $regs) {
469
+                $t = str_replace($regs[0], code_echappement($regs[0], 'php' . _PROTEGE_PHP_MODELES), $t);
470
+            }
471
+        }
472
+    }
473
+
474
+    return $t;
475 475
 }
476 476
 
477 477
 
478 478
 function echapper_faux_tags($letexte) {
479
-	if (strpos($letexte, '<') === false) {
480
-		return $letexte;
481
-	}
482
-	$textMatches = preg_split(',(</?[a-z!][^<>]*>),', $letexte, -1, PREG_SPLIT_DELIM_CAPTURE);
483
-
484
-	$letexte = '';
485
-	while (is_countable($textMatches) ? count($textMatches) : 0) {
486
-		// un texte a echapper
487
-		$letexte .= str_replace('<', '&lt;', array_shift($textMatches));
488
-		// un tag html qui a servit a faite le split
489
-		$letexte .= array_shift($textMatches);
490
-	}
491
-
492
-	return $letexte;
479
+    if (strpos($letexte, '<') === false) {
480
+        return $letexte;
481
+    }
482
+    $textMatches = preg_split(',(</?[a-z!][^<>]*>),', $letexte, -1, PREG_SPLIT_DELIM_CAPTURE);
483
+
484
+    $letexte = '';
485
+    while (is_countable($textMatches) ? count($textMatches) : 0) {
486
+        // un texte a echapper
487
+        $letexte .= str_replace('<', '&lt;', array_shift($textMatches));
488
+        // un tag html qui a servit a faite le split
489
+        $letexte .= array_shift($textMatches);
490
+    }
491
+
492
+    return $letexte;
493 493
 }
494 494
 
495 495
 /**
@@ -502,47 +502,47 @@  discard block
 block discarded – undo
502 502
  * @return string
503 503
  */
504 504
 function echapper_html_suspect($texte, $strict = true) {
505
-	static $echapper_html_suspect;
506
-	if (!$texte or !is_string($texte)) {
507
-		return $texte;
508
-	}
509
-
510
-	if (!isset($echapper_html_suspect)) {
511
-		$echapper_html_suspect = charger_fonction('echapper_html_suspect', 'inc', true);
512
-	}
513
-	// si fonction personalisee, on delegue
514
-	if ($echapper_html_suspect) {
515
-		return $echapper_html_suspect($texte, $strict);
516
-	}
517
-
518
-	if (
519
-		strpos($texte, '<') === false
520
-		or strpos($texte, '=') === false
521
-	) {
522
-		return $texte;
523
-	}
524
-
525
-	// quand c'est du texte qui passe par propre on est plus coulant tant qu'il y a pas d'attribut du type onxxx=
526
-	// car sinon on declenche sur les modeles ou ressources
527
-	if (
528
-		!$strict and
529
-		(strpos($texte, 'on') === false or !preg_match(",<\w+.*\bon\w+\s*=,UimsS", $texte))
530
-	) {
531
-		return $texte;
532
-	}
533
-
534
-	// on teste sur strlen car safehtml supprime le contenu dangereux
535
-	// mais il peut aussi changer des ' en " sur les attributs html,
536
-	// donc un test d'egalite est trop strict
537
-	if (strlen(safehtml($texte)) !== strlen($texte)) {
538
-		$texte = str_replace('<', '&lt;', $texte);
539
-		if (!function_exists('attribut_html')) {
540
-			include_spip('inc/filtres');
541
-		}
542
-		$texte = "<mark class='danger-js' title='" . attribut_html(_T('erreur_contenu_suspect')) . "'>⚠️</mark> " . $texte;
543
-	}
544
-
545
-	return $texte;
505
+    static $echapper_html_suspect;
506
+    if (!$texte or !is_string($texte)) {
507
+        return $texte;
508
+    }
509
+
510
+    if (!isset($echapper_html_suspect)) {
511
+        $echapper_html_suspect = charger_fonction('echapper_html_suspect', 'inc', true);
512
+    }
513
+    // si fonction personalisee, on delegue
514
+    if ($echapper_html_suspect) {
515
+        return $echapper_html_suspect($texte, $strict);
516
+    }
517
+
518
+    if (
519
+        strpos($texte, '<') === false
520
+        or strpos($texte, '=') === false
521
+    ) {
522
+        return $texte;
523
+    }
524
+
525
+    // quand c'est du texte qui passe par propre on est plus coulant tant qu'il y a pas d'attribut du type onxxx=
526
+    // car sinon on declenche sur les modeles ou ressources
527
+    if (
528
+        !$strict and
529
+        (strpos($texte, 'on') === false or !preg_match(",<\w+.*\bon\w+\s*=,UimsS", $texte))
530
+    ) {
531
+        return $texte;
532
+    }
533
+
534
+    // on teste sur strlen car safehtml supprime le contenu dangereux
535
+    // mais il peut aussi changer des ' en " sur les attributs html,
536
+    // donc un test d'egalite est trop strict
537
+    if (strlen(safehtml($texte)) !== strlen($texte)) {
538
+        $texte = str_replace('<', '&lt;', $texte);
539
+        if (!function_exists('attribut_html')) {
540
+            include_spip('inc/filtres');
541
+        }
542
+        $texte = "<mark class='danger-js' title='" . attribut_html(_T('erreur_contenu_suspect')) . "'>⚠️</mark> " . $texte;
543
+    }
544
+
545
+    return $texte;
546 546
 }
547 547
 
548 548
 
@@ -563,30 +563,30 @@  discard block
 block discarded – undo
563 563
  *      Texte sécurisé
564 564
  **/
565 565
 function safehtml($t) {
566
-	static $safehtml;
567
-
568
-	if (!$t or !is_string($t)) {
569
-		return $t;
570
-	}
571
-	# attention safehtml nettoie deux ou trois caracteres de plus. A voir
572
-	if (strpos($t, '<') === false) {
573
-		return str_replace("\x00", '', $t);
574
-	}
575
-
576
-	if (!function_exists('interdire_scripts')) {
577
-		include_spip('inc/texte');
578
-	}
579
-	$t = interdire_scripts($t); // jolifier le php
580
-	$t = echappe_js($t);
581
-
582
-	if (!isset($safehtml)) {
583
-		$safehtml = charger_fonction('safehtml', 'inc', true);
584
-	}
585
-	if ($safehtml) {
586
-		$t = $safehtml($t);
587
-	}
588
-
589
-	return interdire_scripts($t); // interdire le php (2 precautions)
566
+    static $safehtml;
567
+
568
+    if (!$t or !is_string($t)) {
569
+        return $t;
570
+    }
571
+    # attention safehtml nettoie deux ou trois caracteres de plus. A voir
572
+    if (strpos($t, '<') === false) {
573
+        return str_replace("\x00", '', $t);
574
+    }
575
+
576
+    if (!function_exists('interdire_scripts')) {
577
+        include_spip('inc/texte');
578
+    }
579
+    $t = interdire_scripts($t); // jolifier le php
580
+    $t = echappe_js($t);
581
+
582
+    if (!isset($safehtml)) {
583
+        $safehtml = charger_fonction('safehtml', 'inc', true);
584
+    }
585
+    if ($safehtml) {
586
+        $t = $safehtml($t);
587
+    }
588
+
589
+    return interdire_scripts($t); // interdire le php (2 precautions)
590 590
 }
591 591
 
592 592
 
@@ -608,13 +608,13 @@  discard block
 block discarded – undo
608 608
  *     Texte sans les modèles d'image
609 609
  **/
610 610
 function supprime_img($letexte, $message = null) {
611
-	if ($message === null) {
612
-		$message = '(' . _T('img_indisponible') . ')';
613
-	}
614
-
615
-	return preg_replace(
616
-		',<(img|doc|emb)([0-9]+)(\|([^>]*))?' . '\s*/?' . '>,i',
617
-		$message,
618
-		$letexte
619
-	);
611
+    if ($message === null) {
612
+        $message = '(' . _T('img_indisponible') . ')';
613
+    }
614
+
615
+    return preg_replace(
616
+        ',<(img|doc|emb)([0-9]+)(\|([^>]*))?' . '\s*/?' . '>,i',
617
+        $message,
618
+        $letexte
619
+    );
620 620
 }
Please login to merge, or discard this patch.
ecrire/inc/math.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 
13 13
 //
14 14
 if (!defined('_ECRIRE_INC_VERSION')) {
15
-	return;
15
+    return;
16 16
 }
17 17
 
18 18
 //
@@ -22,54 +22,54 @@  discard block
 block discarded – undo
22 22
 // https://code.spip.net/@image_math
23 23
 function produire_image_math($tex) {
24 24
 
25
-	switch ($GLOBALS['traiter_math']) {
26
-		// Attention: mathml desactiv'e pour l'instant
27
-		case 'mathml':
28
-			$ext = '.xhtml';
29
-			$server = $GLOBALS['mathml_server'];
30
-			break;
31
-		case 'tex':
32
-			$ext = '.png';
33
-			$server = $GLOBALS['tex_server'];
34
-			break;
35
-		default:
36
-			return $tex;
37
-	}
38
-
39
-	// Regarder dans le repertoire local des images TeX et blocs MathML
40
-	if (!@is_dir($dir_tex = _DIR_VAR . 'cache-TeX/')) {
41
-		@mkdir($dir_tex, _SPIP_CHMOD);
42
-	}
43
-	$fichier = $dir_tex . md5(trim($tex)) . $ext;
44
-
45
-
46
-	if (!@file_exists($fichier)) {
47
-		// Aller chercher l'image sur le serveur
48
-		if ($server) {
49
-			spip_log($url = $server . '?' . rawurlencode($tex));
50
-			include_spip('inc/distant');
51
-			recuperer_url($url, ['file' => $fichier]);
52
-		}
53
-	}
54
-
55
-
56
-	// Composer la reponse selon presence ou non de l'image
57
-	$tex = entites_html($tex);
58
-	if (@file_exists($fichier)) {
59
-		// MathML
60
-		if ($GLOBALS['traiter_math'] == 'mathml') {
61
-			return implode('', file($fichier));
62
-		} // TeX
63
-		else {
64
-			[, , , $size] = @spip_getimagesize($fichier);
65
-			$alt = "alt=\"$tex\" title=\"$tex\"";
66
-
67
-			return "<img src=\"$fichier\" style=\"vertical-align:middle;\" $size $alt />";
68
-		}
69
-	} else // pas de fichier
70
-	{
71
-		return "<tt><span class='spip_code' dir='ltr'>$tex</span></tt>";
72
-	}
25
+    switch ($GLOBALS['traiter_math']) {
26
+        // Attention: mathml desactiv'e pour l'instant
27
+        case 'mathml':
28
+            $ext = '.xhtml';
29
+            $server = $GLOBALS['mathml_server'];
30
+            break;
31
+        case 'tex':
32
+            $ext = '.png';
33
+            $server = $GLOBALS['tex_server'];
34
+            break;
35
+        default:
36
+            return $tex;
37
+    }
38
+
39
+    // Regarder dans le repertoire local des images TeX et blocs MathML
40
+    if (!@is_dir($dir_tex = _DIR_VAR . 'cache-TeX/')) {
41
+        @mkdir($dir_tex, _SPIP_CHMOD);
42
+    }
43
+    $fichier = $dir_tex . md5(trim($tex)) . $ext;
44
+
45
+
46
+    if (!@file_exists($fichier)) {
47
+        // Aller chercher l'image sur le serveur
48
+        if ($server) {
49
+            spip_log($url = $server . '?' . rawurlencode($tex));
50
+            include_spip('inc/distant');
51
+            recuperer_url($url, ['file' => $fichier]);
52
+        }
53
+    }
54
+
55
+
56
+    // Composer la reponse selon presence ou non de l'image
57
+    $tex = entites_html($tex);
58
+    if (@file_exists($fichier)) {
59
+        // MathML
60
+        if ($GLOBALS['traiter_math'] == 'mathml') {
61
+            return implode('', file($fichier));
62
+        } // TeX
63
+        else {
64
+            [, , , $size] = @spip_getimagesize($fichier);
65
+            $alt = "alt=\"$tex\" title=\"$tex\"";
66
+
67
+            return "<img src=\"$fichier\" style=\"vertical-align:middle;\" $size $alt />";
68
+        }
69
+    } else // pas de fichier
70
+    {
71
+        return "<tt><span class='spip_code' dir='ltr'>$tex</span></tt>";
72
+    }
73 73
 }
74 74
 
75 75
 
@@ -104,52 +104,52 @@  discard block
 block discarded – undo
104 104
  */
105 105
 function traiter_math($letexte, $source = '', $defaire_amp = false) {
106 106
 
107
-	$texte_a_voir = $letexte;
108
-	while (($debut = strpos($texte_a_voir, '<math>')) !== false) {
109
-		if (!$fin = strpos($texte_a_voir, '</math>')) {
110
-			$fin = strlen($texte_a_voir);
111
-		}
112
-
113
-		$texte_debut = substr($texte_a_voir, 0, $debut);
114
-		$texte_milieu = substr(
115
-			$texte_a_voir,
116
-			$debut + strlen('<math>'),
117
-			$fin - $debut - strlen('<math>')
118
-		);
119
-		$texte_fin = substr(
120
-			$texte_a_voir,
121
-			$fin + strlen('</math>'),
122
-			strlen($texte_a_voir)
123
-		);
124
-
125
-		// Les doubles $$x^2$$ en mode 'div'
126
-		while ((preg_match(',[$][$]([^$]+)[$][$],', $texte_milieu, $regs))) {
127
-			$expression = $regs[1];
128
-			if ($defaire_amp) {
129
-				$expression = str_replace('&amp;', '&', $expression);
130
-			}
131
-			$echap = "\n<p class=\"spip\" style=\"text-align: center;\">" . produire_image_math($expression) . "</p>\n";
132
-			$pos = strpos($texte_milieu, (string) $regs[0]);
133
-			$texte_milieu = substr($texte_milieu, 0, $pos)
134
-				. code_echappement($echap, $source)
135
-				. substr($texte_milieu, $pos + strlen($regs[0]));
136
-		}
137
-
138
-		// Les simples $x^2$ en mode 'span'
139
-		while ((preg_match(',[$]([^$]+)[$],', $texte_milieu, $regs))) {
140
-			$expression = $regs[1];
141
-			if ($defaire_amp) {
142
-				$expression = str_replace('&amp;', '&', $expression);
143
-			}
144
-			$echap = produire_image_math($expression);
145
-			$pos = strpos($texte_milieu, (string) $regs[0]);
146
-			$texte_milieu = substr($texte_milieu, 0, $pos)
147
-				. code_echappement($echap, $source)
148
-				. substr($texte_milieu, $pos + strlen($regs[0]));
149
-		}
150
-
151
-		$texte_a_voir = $texte_debut . $texte_milieu . $texte_fin;
152
-	}
153
-
154
-	return $texte_a_voir;
107
+    $texte_a_voir = $letexte;
108
+    while (($debut = strpos($texte_a_voir, '<math>')) !== false) {
109
+        if (!$fin = strpos($texte_a_voir, '</math>')) {
110
+            $fin = strlen($texte_a_voir);
111
+        }
112
+
113
+        $texte_debut = substr($texte_a_voir, 0, $debut);
114
+        $texte_milieu = substr(
115
+            $texte_a_voir,
116
+            $debut + strlen('<math>'),
117
+            $fin - $debut - strlen('<math>')
118
+        );
119
+        $texte_fin = substr(
120
+            $texte_a_voir,
121
+            $fin + strlen('</math>'),
122
+            strlen($texte_a_voir)
123
+        );
124
+
125
+        // Les doubles $$x^2$$ en mode 'div'
126
+        while ((preg_match(',[$][$]([^$]+)[$][$],', $texte_milieu, $regs))) {
127
+            $expression = $regs[1];
128
+            if ($defaire_amp) {
129
+                $expression = str_replace('&amp;', '&', $expression);
130
+            }
131
+            $echap = "\n<p class=\"spip\" style=\"text-align: center;\">" . produire_image_math($expression) . "</p>\n";
132
+            $pos = strpos($texte_milieu, (string) $regs[0]);
133
+            $texte_milieu = substr($texte_milieu, 0, $pos)
134
+                . code_echappement($echap, $source)
135
+                . substr($texte_milieu, $pos + strlen($regs[0]));
136
+        }
137
+
138
+        // Les simples $x^2$ en mode 'span'
139
+        while ((preg_match(',[$]([^$]+)[$],', $texte_milieu, $regs))) {
140
+            $expression = $regs[1];
141
+            if ($defaire_amp) {
142
+                $expression = str_replace('&amp;', '&', $expression);
143
+            }
144
+            $echap = produire_image_math($expression);
145
+            $pos = strpos($texte_milieu, (string) $regs[0]);
146
+            $texte_milieu = substr($texte_milieu, 0, $pos)
147
+                . code_echappement($echap, $source)
148
+                . substr($texte_milieu, $pos + strlen($regs[0]));
149
+        }
150
+
151
+        $texte_a_voir = $texte_debut . $texte_milieu . $texte_fin;
152
+    }
153
+
154
+    return $texte_a_voir;
155 155
 }
Please login to merge, or discard this patch.
ecrire/inc/securiser_action.php 1 patch
Indentation   +213 added lines, -213 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
 /**
@@ -50,19 +50,19 @@  discard block
 block discarded – undo
50 50
  * @return array|string
51 51
  */
52 52
 function inc_securiser_action_dist($action = '', $arg = '', $redirect = '', $mode = false, $att = '', $public = false) {
53
-	if ($action) {
54
-		return securiser_action_auteur($action, $arg, $redirect, $mode, $att, $public);
55
-	} else {
56
-		$arg = _request('arg');
57
-		$hash = _request('hash');
58
-		$action = _request('action') ?: _request('formulaire_action');
59
-		if ($a = verifier_action_auteur("$action-$arg", $hash)) {
60
-			return $arg;
61
-		}
62
-		include_spip('inc/minipres');
63
-		echo minipres();
64
-		exit;
65
-	}
53
+    if ($action) {
54
+        return securiser_action_auteur($action, $arg, $redirect, $mode, $att, $public);
55
+    } else {
56
+        $arg = _request('arg');
57
+        $hash = _request('hash');
58
+        $action = _request('action') ?: _request('formulaire_action');
59
+        if ($a = verifier_action_auteur("$action-$arg", $hash)) {
60
+            return $arg;
61
+        }
62
+        include_spip('inc/minipres');
63
+        echo minipres();
64
+        exit;
65
+    }
66 66
 }
67 67
 
68 68
 /**
@@ -81,29 +81,29 @@  discard block
 block discarded – undo
81 81
  */
82 82
 function demander_confirmation_avant_action($titre, $titre_bouton, $url_action = null) {
83 83
 
84
-	if (!$url_action) {
85
-		$url_action = self();
86
-		$action = _request('action');
87
-		$url_action = parametre_url($url_action, 'action', $action, '&');
88
-	}
89
-	else {
90
-		$action = parametre_url($url_action, 'action');
91
-	}
92
-
93
-	$arg = parametre_url($url_action, 'arg');
94
-	$confirm = md5("$action:$arg:" . realpath(__FILE__));
95
-	if (_request('confirm_action') === $confirm) {
96
-		return true;
97
-	}
98
-
99
-	$url_confirm = parametre_url($url_action, 'confirm_action', $confirm, '&');
100
-	include_spip('inc/filtres');
101
-	$bouton_action = bouton_action($titre_bouton, $url_confirm);
102
-	$corps = "<div style='text-align:center;'>$bouton_action</div>";
103
-
104
-	include_spip('inc/minipres');
105
-	echo minipres($titre, $corps);
106
-	exit;
84
+    if (!$url_action) {
85
+        $url_action = self();
86
+        $action = _request('action');
87
+        $url_action = parametre_url($url_action, 'action', $action, '&');
88
+    }
89
+    else {
90
+        $action = parametre_url($url_action, 'action');
91
+    }
92
+
93
+    $arg = parametre_url($url_action, 'arg');
94
+    $confirm = md5("$action:$arg:" . realpath(__FILE__));
95
+    if (_request('confirm_action') === $confirm) {
96
+        return true;
97
+    }
98
+
99
+    $url_confirm = parametre_url($url_action, 'confirm_action', $confirm, '&');
100
+    include_spip('inc/filtres');
101
+    $bouton_action = bouton_action($titre_bouton, $url_confirm);
102
+    $corps = "<div style='text-align:center;'>$bouton_action</div>";
103
+
104
+    include_spip('inc/minipres');
105
+    echo minipres($titre, $corps);
106
+    exit;
107 107
 }
108 108
 
109 109
 /**
@@ -135,34 +135,34 @@  discard block
 block discarded – undo
135 135
  */
136 136
 function securiser_action_auteur($action, $arg, $redirect = '', $mode = false, $att = '', $public = false) {
137 137
 
138
-	// mode URL ou array
139
-	if (!is_string($mode)) {
140
-		$hash = calculer_action_auteur("$action-$arg", is_numeric($att) ? $att : null);
141
-
142
-		$r = rawurlencode($redirect);
143
-		if ($mode === -1) {
144
-			return ['action' => $action, 'arg' => $arg, 'hash' => $hash];
145
-		} else {
146
-			return generer_url_action(
147
-				$action,
148
-				'arg=' . rawurlencode($arg) . "&hash=$hash" . (!$r ? '' : "&redirect=$r"),
149
-				$mode,
150
-				$public
151
-			);
152
-		}
153
-	}
154
-
155
-	// mode formulaire
156
-	$hash = calculer_action_auteur("$action-$arg");
157
-	$att .= " style='margin: 0px; border: 0px'";
158
-	if ($redirect) {
159
-		$redirect = "\n\t\t<input name='redirect' type='hidden' value='" . str_replace("'", '&#39;', $redirect) . "' />";
160
-	}
161
-	$mode .= $redirect . "
138
+    // mode URL ou array
139
+    if (!is_string($mode)) {
140
+        $hash = calculer_action_auteur("$action-$arg", is_numeric($att) ? $att : null);
141
+
142
+        $r = rawurlencode($redirect);
143
+        if ($mode === -1) {
144
+            return ['action' => $action, 'arg' => $arg, 'hash' => $hash];
145
+        } else {
146
+            return generer_url_action(
147
+                $action,
148
+                'arg=' . rawurlencode($arg) . "&hash=$hash" . (!$r ? '' : "&redirect=$r"),
149
+                $mode,
150
+                $public
151
+            );
152
+        }
153
+    }
154
+
155
+    // mode formulaire
156
+    $hash = calculer_action_auteur("$action-$arg");
157
+    $att .= " style='margin: 0px; border: 0px'";
158
+    if ($redirect) {
159
+        $redirect = "\n\t\t<input name='redirect' type='hidden' value='" . str_replace("'", '&#39;', $redirect) . "' />";
160
+    }
161
+    $mode .= $redirect . "
162 162
 <input name='hash' type='hidden' value='$hash' />
163 163
 <input name='arg' type='hidden' value='$arg' />";
164 164
 
165
-	return generer_form_action($action, $mode, $att, $public);
165
+    return generer_form_action($action, $mode, $att, $public);
166 166
 }
167 167
 
168 168
 /**
@@ -172,48 +172,48 @@  discard block
 block discarded – undo
172 172
  * @return array
173 173
  */
174 174
 function caracteriser_auteur($id_auteur = null) {
175
-	static $caracterisation = [];
176
-
177
-	if (is_null($id_auteur) and !isset($GLOBALS['visiteur_session']['id_auteur'])) {
178
-		// si l'auteur courant n'est pas connu alors qu'il peut demander une action
179
-		// c'est une connexion par php_auth ou 1 instal, on se rabat sur le cookie.
180
-		// S'il n'avait pas le droit de realiser cette action, le hash sera faux.
181
-		if (
182
-			isset($_COOKIE['spip_session'])
183
-			and (preg_match('/^(\d+)/', $_COOKIE['spip_session'], $r))
184
-		) {
185
-			return [$r[1], ''];
186
-			// Necessaire aux forums anonymes.
187
-			// Pour le reste, ca echouera.
188
-		} else {
189
-			return ['0', ''];
190
-		}
191
-	}
192
-	// Eviter l'acces SQL si le pass est connu de PHP
193
-	if (is_null($id_auteur)) {
194
-		$id_auteur = $GLOBALS['visiteur_session']['id_auteur'] ?? 0;
195
-		if (isset($GLOBALS['visiteur_session']['pass']) and $GLOBALS['visiteur_session']['pass']) {
196
-			return $caracterisation[$id_auteur] = [$id_auteur, $GLOBALS['visiteur_session']['pass']];
197
-		}
198
-	}
199
-
200
-	if (isset($caracterisation[$id_auteur])) {
201
-		return $caracterisation[$id_auteur];
202
-	}
203
-
204
-	if ($id_auteur) {
205
-		include_spip('base/abstract_sql');
206
-		$t = sql_fetsel('id_auteur, pass', 'spip_auteurs', "id_auteur=$id_auteur");
207
-		if ($t) {
208
-			return $caracterisation[$id_auteur] = [$t['id_auteur'], $t['pass']];
209
-		}
210
-		include_spip('inc/minipres');
211
-		echo minipres();
212
-		exit;
213
-	} // Visiteur anonyme, pour ls forums par exemple
214
-	else {
215
-		return ['0', ''];
216
-	}
175
+    static $caracterisation = [];
176
+
177
+    if (is_null($id_auteur) and !isset($GLOBALS['visiteur_session']['id_auteur'])) {
178
+        // si l'auteur courant n'est pas connu alors qu'il peut demander une action
179
+        // c'est une connexion par php_auth ou 1 instal, on se rabat sur le cookie.
180
+        // S'il n'avait pas le droit de realiser cette action, le hash sera faux.
181
+        if (
182
+            isset($_COOKIE['spip_session'])
183
+            and (preg_match('/^(\d+)/', $_COOKIE['spip_session'], $r))
184
+        ) {
185
+            return [$r[1], ''];
186
+            // Necessaire aux forums anonymes.
187
+            // Pour le reste, ca echouera.
188
+        } else {
189
+            return ['0', ''];
190
+        }
191
+    }
192
+    // Eviter l'acces SQL si le pass est connu de PHP
193
+    if (is_null($id_auteur)) {
194
+        $id_auteur = $GLOBALS['visiteur_session']['id_auteur'] ?? 0;
195
+        if (isset($GLOBALS['visiteur_session']['pass']) and $GLOBALS['visiteur_session']['pass']) {
196
+            return $caracterisation[$id_auteur] = [$id_auteur, $GLOBALS['visiteur_session']['pass']];
197
+        }
198
+    }
199
+
200
+    if (isset($caracterisation[$id_auteur])) {
201
+        return $caracterisation[$id_auteur];
202
+    }
203
+
204
+    if ($id_auteur) {
205
+        include_spip('base/abstract_sql');
206
+        $t = sql_fetsel('id_auteur, pass', 'spip_auteurs', "id_auteur=$id_auteur");
207
+        if ($t) {
208
+            return $caracterisation[$id_auteur] = [$t['id_auteur'], $t['pass']];
209
+        }
210
+        include_spip('inc/minipres');
211
+        echo minipres();
212
+        exit;
213
+    } // Visiteur anonyme, pour ls forums par exemple
214
+    else {
215
+        return ['0', ''];
216
+    }
217 217
 }
218 218
 
219 219
 /**
@@ -228,28 +228,28 @@  discard block
 block discarded – undo
228 228
  * @return string
229 229
  */
230 230
 function _action_auteur($action, $id_auteur, $pass, $alea) {
231
-	static $sha = [];
232
-	if (!isset($sha[$id_auteur . $pass . $alea])) {
233
-		if (!isset($GLOBALS['meta'][$alea])) {
234
-			if (!$exec = _request('exec') or !autoriser_sans_cookie($exec)) {
235
-				include_spip('inc/acces');
236
-				charger_aleas();
237
-				if (empty($GLOBALS['meta'][$alea])) {
238
-					include_spip('inc/minipres');
239
-					echo minipres();
240
-					spip_log("$alea indisponible");
241
-					exit;
242
-				}
243
-			}
244
-		}
245
-		include_spip('auth/sha256.inc');
246
-		$sha[$id_auteur . $pass . $alea] = spip_sha256($id_auteur . $pass . @$GLOBALS['meta'][$alea]);
247
-	}
248
-	if (function_exists('sha1')) {
249
-		return sha1($action . $sha[$id_auteur . $pass . $alea]);
250
-	} else {
251
-		return md5($action . $sha[$id_auteur . $pass . $alea]);
252
-	}
231
+    static $sha = [];
232
+    if (!isset($sha[$id_auteur . $pass . $alea])) {
233
+        if (!isset($GLOBALS['meta'][$alea])) {
234
+            if (!$exec = _request('exec') or !autoriser_sans_cookie($exec)) {
235
+                include_spip('inc/acces');
236
+                charger_aleas();
237
+                if (empty($GLOBALS['meta'][$alea])) {
238
+                    include_spip('inc/minipres');
239
+                    echo minipres();
240
+                    spip_log("$alea indisponible");
241
+                    exit;
242
+                }
243
+            }
244
+        }
245
+        include_spip('auth/sha256.inc');
246
+        $sha[$id_auteur . $pass . $alea] = spip_sha256($id_auteur . $pass . @$GLOBALS['meta'][$alea]);
247
+    }
248
+    if (function_exists('sha1')) {
249
+        return sha1($action . $sha[$id_auteur . $pass . $alea]);
250
+    } else {
251
+        return md5($action . $sha[$id_auteur . $pass . $alea]);
252
+    }
253 253
 }
254 254
 
255 255
 /**
@@ -260,9 +260,9 @@  discard block
 block discarded – undo
260 260
  * @return string
261 261
  */
262 262
 function calculer_action_auteur($action, $id_auteur = null) {
263
-	[$id_auteur, $pass] = caracteriser_auteur($id_auteur);
263
+    [$id_auteur, $pass] = caracteriser_auteur($id_auteur);
264 264
 
265
-	return _action_auteur($action, $id_auteur, $pass, 'alea_ephemere');
265
+    return _action_auteur($action, $id_auteur, $pass, 'alea_ephemere');
266 266
 }
267 267
 
268 268
 
@@ -275,15 +275,15 @@  discard block
 block discarded – undo
275 275
  * @return bool
276 276
  */
277 277
 function verifier_action_auteur($action, $hash) {
278
-	[$id_auteur, $pass] = caracteriser_auteur();
279
-	if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere')) {
280
-		return true;
281
-	}
282
-	if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere_ancien')) {
283
-		return true;
284
-	}
285
-
286
-	return false;
278
+    [$id_auteur, $pass] = caracteriser_auteur();
279
+    if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere')) {
280
+        return true;
281
+    }
282
+    if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere_ancien')) {
283
+        return true;
284
+    }
285
+
286
+    return false;
287 287
 }
288 288
 
289 289
 //
@@ -299,29 +299,29 @@  discard block
 block discarded – undo
299 299
  * @return string
300 300
  */
301 301
 function secret_du_site() {
302
-	if (!isset($GLOBALS['meta']['secret_du_site'])) {
303
-		include_spip('base/abstract_sql');
304
-		$GLOBALS['meta']['secret_du_site'] = sql_getfetsel('valeur', 'spip_meta', "nom='secret_du_site'");
305
-	}
306
-	if (
307
-		!isset($GLOBALS['meta']['secret_du_site'])
308
-		or (strlen($GLOBALS['meta']['secret_du_site']) < 64)
309
-	) {
310
-		include_spip('inc/acces');
311
-		include_spip('auth/sha256.inc');
312
-		ecrire_meta(
313
-			'secret_du_site',
314
-			spip_sha256(
315
-				$_SERVER['DOCUMENT_ROOT']
316
-				. ($_SERVER['SERVER_SIGNATURE'] ?? '')
317
-				. creer_uniqid()
318
-			),
319
-			'non'
320
-		);
321
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
322
-	}
323
-
324
-	return $GLOBALS['meta']['secret_du_site'];
302
+    if (!isset($GLOBALS['meta']['secret_du_site'])) {
303
+        include_spip('base/abstract_sql');
304
+        $GLOBALS['meta']['secret_du_site'] = sql_getfetsel('valeur', 'spip_meta', "nom='secret_du_site'");
305
+    }
306
+    if (
307
+        !isset($GLOBALS['meta']['secret_du_site'])
308
+        or (strlen($GLOBALS['meta']['secret_du_site']) < 64)
309
+    ) {
310
+        include_spip('inc/acces');
311
+        include_spip('auth/sha256.inc');
312
+        ecrire_meta(
313
+            'secret_du_site',
314
+            spip_sha256(
315
+                $_SERVER['DOCUMENT_ROOT']
316
+                . ($_SERVER['SERVER_SIGNATURE'] ?? '')
317
+                . creer_uniqid()
318
+            ),
319
+            'non'
320
+        );
321
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
322
+    }
323
+
324
+    return $GLOBALS['meta']['secret_du_site'];
325 325
 }
326 326
 
327 327
 /**
@@ -331,11 +331,11 @@  discard block
 block discarded – undo
331 331
  * @return string
332 332
  */
333 333
 function calculer_cle_action($action) {
334
-	if (function_exists('sha1')) {
335
-		return sha1($action . secret_du_site());
336
-	} else {
337
-		return md5($action . secret_du_site());
338
-	}
334
+    if (function_exists('sha1')) {
335
+        return sha1($action . secret_du_site());
336
+    } else {
337
+        return md5($action . secret_du_site());
338
+    }
339 339
 }
340 340
 
341 341
 /**
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
  * @return bool
347 347
  */
348 348
 function verifier_cle_action($action, $cle) {
349
-	return ($cle == calculer_cle_action($action));
349
+    return ($cle == calculer_cle_action($action));
350 350
 }
351 351
 
352 352
 
@@ -363,19 +363,19 @@  discard block
 block discarded – undo
363 363
  * @return string Token, de la forme "{id}*{hash}"
364 364
  */
365 365
 function calculer_token_previsu($url, $id_auteur = null, $alea = 'alea_ephemere') {
366
-	if (is_null($id_auteur)) {
367
-		if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
368
-			$id_auteur = $GLOBALS['visiteur_session']['id_auteur'];
369
-		}
370
-	}
371
-	if (!$id_auteur = intval($id_auteur)) {
372
-		return '';
373
-	}
374
-	// On nettoie l’URL de tous les var_.
375
-	$url = nettoyer_uri_var($url);
376
-
377
-	$token = _action_auteur('previsualiser-' . $url, $id_auteur, null, $alea);
378
-	return "$id_auteur-$token";
366
+    if (is_null($id_auteur)) {
367
+        if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
368
+            $id_auteur = $GLOBALS['visiteur_session']['id_auteur'];
369
+        }
370
+    }
371
+    if (!$id_auteur = intval($id_auteur)) {
372
+        return '';
373
+    }
374
+    // On nettoie l’URL de tous les var_.
375
+    $url = nettoyer_uri_var($url);
376
+
377
+    $token = _action_auteur('previsualiser-' . $url, $id_auteur, null, $alea);
378
+    return "$id_auteur-$token";
379 379
 }
380 380
 
381 381
 
@@ -393,31 +393,31 @@  discard block
 block discarded – undo
393 393
  *     + Tableau (id auteur, type d’objet, id_objet) sinon.
394 394
  */
395 395
 function verifier_token_previsu($token) {
396
-	// retrouver auteur / hash
397
-	$e = explode('-', $token, 2);
398
-	if (count($e) == 2 and is_numeric(reset($e))) {
399
-		$id_auteur = intval(reset($e));
400
-	} else {
401
-		return false;
402
-	}
403
-
404
-	// calculer le type et id de l’url actuelle
405
-	include_spip('inc/urls');
406
-	include_spip('inc/filtres_mini');
407
-	$url = url_absolue(self());
408
-
409
-	// verifier le token
410
-	$_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere');
411
-	if (!$_token or $token !== $_token) {
412
-		$_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere_ancien');
413
-		if (!$_token or $token !== $_token) {
414
-			return false;
415
-		}
416
-	}
417
-
418
-	return [
419
-		'id_auteur' => $id_auteur,
420
-	];
396
+    // retrouver auteur / hash
397
+    $e = explode('-', $token, 2);
398
+    if (count($e) == 2 and is_numeric(reset($e))) {
399
+        $id_auteur = intval(reset($e));
400
+    } else {
401
+        return false;
402
+    }
403
+
404
+    // calculer le type et id de l’url actuelle
405
+    include_spip('inc/urls');
406
+    include_spip('inc/filtres_mini');
407
+    $url = url_absolue(self());
408
+
409
+    // verifier le token
410
+    $_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere');
411
+    if (!$_token or $token !== $_token) {
412
+        $_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere_ancien');
413
+        if (!$_token or $token !== $_token) {
414
+            return false;
415
+        }
416
+    }
417
+
418
+    return [
419
+        'id_auteur' => $id_auteur,
420
+    ];
421 421
 }
422 422
 
423 423
 /**
@@ -426,13 +426,13 @@  discard block
 block discarded – undo
426 426
  * @return bool|array
427 427
  */
428 428
 function decrire_token_previsu() {
429
-	static $desc = null;
430
-	if (is_null($desc)) {
431
-		if ($token = _request('var_previewtoken')) {
432
-			$desc = verifier_token_previsu($token);
433
-		} else {
434
-			$desc = false;
435
-		}
436
-	}
437
-	return $desc;
429
+    static $desc = null;
430
+    if (is_null($desc)) {
431
+        if ($token = _request('var_previewtoken')) {
432
+            $desc = verifier_token_previsu($token);
433
+        } else {
434
+            $desc = false;
435
+        }
436
+    }
437
+    return $desc;
438 438
 }
Please login to merge, or discard this patch.
ecrire/inc/auth.php 1 patch
Indentation   +447 added lines, -447 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
 include_spip('base/abstract_sql');
@@ -35,33 +35,33 @@  discard block
 block discarded – undo
35 35
  *  - une chaîne vide si autorisation à pénétrer dans l'espace privé.
36 36
  */
37 37
 function inc_auth_dist() {
38
-	$row = auth_mode();
38
+    $row = auth_mode();
39 39
 
40
-	if ($row) {
41
-		return auth_init_droits($row);
42
-	}
40
+    if ($row) {
41
+        return auth_init_droits($row);
42
+    }
43 43
 
44
-	if (!$GLOBALS['connect_login']) {
45
-		return auth_a_loger();
46
-	}
44
+    if (!$GLOBALS['connect_login']) {
45
+        return auth_a_loger();
46
+    }
47 47
 
48
-	// Cas ou l'auteur a ete identifie mais on n'a pas d'info sur lui
49
-	// C'est soit parce que la base est inutilisable,
50
-	// soit parce que la table des auteurs a changee (restauration etc)
51
-	// Pas la peine d'insister.
52
-	// Renvoyer le nom fautif et une URL de remise a zero
48
+    // Cas ou l'auteur a ete identifie mais on n'a pas d'info sur lui
49
+    // C'est soit parce que la base est inutilisable,
50
+    // soit parce que la table des auteurs a changee (restauration etc)
51
+    // Pas la peine d'insister.
52
+    // Renvoyer le nom fautif et une URL de remise a zero
53 53
 
54
-	if (spip_connect()) {
55
-		return [
56
-			'login' => $GLOBALS['connect_login'],
57
-			'site' => generer_url_public('', 'action=logout&amp;logout=prive')
58
-		];
59
-	}
54
+    if (spip_connect()) {
55
+        return [
56
+            'login' => $GLOBALS['connect_login'],
57
+            'site' => generer_url_public('', 'action=logout&amp;logout=prive')
58
+        ];
59
+    }
60 60
 
61
-	$n = intval(sql_errno());
62
-	spip_log("Erreur base de donnees $n " . sql_error());
61
+    $n = intval(sql_errno());
62
+    spip_log("Erreur base de donnees $n " . sql_error());
63 63
 
64
-	return $n ?: 1;
64
+    return $n ?: 1;
65 65
 }
66 66
 
67 67
 /**
@@ -73,39 +73,39 @@  discard block
 block discarded – undo
73 73
  * @return array|string
74 74
  */
75 75
 function auth_echec($raison) {
76
-	include_spip('inc/minipres');
77
-	include_spip('inc/headers');
78
-	// pas authentifie. Pourquoi ?
79
-	if (is_string($raison)) {
80
-		// redirection vers une page d'authentification
81
-		// on ne revient pas de cette fonction
82
-		// sauf si pb de header
83
-		$raison = redirige_formulaire($raison);
84
-	} elseif (is_int($raison)) {
85
-		// erreur SQL a afficher
86
-		$raison = minipres(
87
-			_T('info_travaux_titre'),
88
-			_T('titre_probleme_technique') . '<p><tt>' . sql_errno() . ' ' . sql_error() . '</tt></p>'
89
-		);
90
-	} elseif (@$raison['statut']) {
91
-		// un simple visiteur n'a pas acces a l'espace prive
92
-		spip_log('connexion refusee a ' . @$raison['id_auteur']);
93
-		$raison = minipres(_T('avis_erreur_connexion'), _T('avis_erreur_visiteur'));
94
-	} else {
95
-		// auteur en fin de droits ...
96
-		$h = $raison['site'];
97
-		$raison = minipres(
98
-			_T('avis_erreur_connexion'),
99
-			'<br /><br /><p>'
100
-			. _T('texte_inc_auth_1', ['auth_login' => $raison['login']])
101
-			. " <a href='$h'>"
102
-			. _T('texte_inc_auth_2')
103
-			. '</a>'
104
-			. _T('texte_inc_auth_3')
105
-		);
106
-	}
107
-
108
-	return $raison;
76
+    include_spip('inc/minipres');
77
+    include_spip('inc/headers');
78
+    // pas authentifie. Pourquoi ?
79
+    if (is_string($raison)) {
80
+        // redirection vers une page d'authentification
81
+        // on ne revient pas de cette fonction
82
+        // sauf si pb de header
83
+        $raison = redirige_formulaire($raison);
84
+    } elseif (is_int($raison)) {
85
+        // erreur SQL a afficher
86
+        $raison = minipres(
87
+            _T('info_travaux_titre'),
88
+            _T('titre_probleme_technique') . '<p><tt>' . sql_errno() . ' ' . sql_error() . '</tt></p>'
89
+        );
90
+    } elseif (@$raison['statut']) {
91
+        // un simple visiteur n'a pas acces a l'espace prive
92
+        spip_log('connexion refusee a ' . @$raison['id_auteur']);
93
+        $raison = minipres(_T('avis_erreur_connexion'), _T('avis_erreur_visiteur'));
94
+    } else {
95
+        // auteur en fin de droits ...
96
+        $h = $raison['site'];
97
+        $raison = minipres(
98
+            _T('avis_erreur_connexion'),
99
+            '<br /><br /><p>'
100
+            . _T('texte_inc_auth_1', ['auth_login' => $raison['login']])
101
+            . " <a href='$h'>"
102
+            . _T('texte_inc_auth_2')
103
+            . '</a>'
104
+            . _T('texte_inc_auth_3')
105
+        );
106
+    }
107
+
108
+    return $raison;
109 109
 }
110 110
 
111 111
 /**
@@ -115,81 +115,81 @@  discard block
 block discarded – undo
115 115
  * @return array|bool|string
116 116
  */
117 117
 function auth_mode() {
118
-	//
119
-	// Initialiser variables (eviter hacks par URL)
120
-	//
121
-	$GLOBALS['connect_login'] = '';
122
-	$id_auteur = null;
123
-	$GLOBALS['auth_can_disconnect'] = false;
124
-
125
-	//
126
-	// Recuperer les donnees d'identification
127
-	//
128
-	include_spip('inc/session');
129
-	// Session valide en cours ?
130
-	if (isset($_COOKIE['spip_session'])) {
131
-		$session = charger_fonction('session', 'inc');
132
-		if (
133
-			$id_auteur = $session()
134
-			or $id_auteur === 0 // reprise sur restauration
135
-		) {
136
-			$GLOBALS['auth_can_disconnect'] = true;
137
-			$GLOBALS['connect_login'] = session_get('login');
138
-		} else {
139
-			unset($_COOKIE['spip_session']);
140
-		}
141
-	}
142
-
143
-	// Essayer auth http si significatif
144
-	// (ignorer les login d'intranet independants de spip)
145
-	if (!$GLOBALS['ignore_auth_http']) {
146
-		if (
147
-			(isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])
148
-				and $r = lire_php_auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
149
-			or
150
-			// Si auth http differtente de basic, PHP_AUTH_PW
151
-			// est indisponible mais tentons quand meme pour
152
-			// autocreation via LDAP
153
-			(isset($_SERVER['REMOTE_USER'])
154
-				and $r = lire_php_auth($_SERVER['PHP_AUTH_USER'] = $_SERVER['REMOTE_USER'], ''))
155
-		) {
156
-			if (!$id_auteur) {
157
-				$_SERVER['PHP_AUTH_PW'] = '';
158
-				$GLOBALS['auth_can_disconnect'] = true;
159
-				$GLOBALS['visiteur_session'] = $r;
160
-				$GLOBALS['connect_login'] = session_get('login');
161
-				$id_auteur = $r['id_auteur'];
162
-			} else {
163
-				// cas de la session en plus de PHP_AUTH
164
-				/*				  if ($id_auteur != $r['id_auteur']){
118
+    //
119
+    // Initialiser variables (eviter hacks par URL)
120
+    //
121
+    $GLOBALS['connect_login'] = '';
122
+    $id_auteur = null;
123
+    $GLOBALS['auth_can_disconnect'] = false;
124
+
125
+    //
126
+    // Recuperer les donnees d'identification
127
+    //
128
+    include_spip('inc/session');
129
+    // Session valide en cours ?
130
+    if (isset($_COOKIE['spip_session'])) {
131
+        $session = charger_fonction('session', 'inc');
132
+        if (
133
+            $id_auteur = $session()
134
+            or $id_auteur === 0 // reprise sur restauration
135
+        ) {
136
+            $GLOBALS['auth_can_disconnect'] = true;
137
+            $GLOBALS['connect_login'] = session_get('login');
138
+        } else {
139
+            unset($_COOKIE['spip_session']);
140
+        }
141
+    }
142
+
143
+    // Essayer auth http si significatif
144
+    // (ignorer les login d'intranet independants de spip)
145
+    if (!$GLOBALS['ignore_auth_http']) {
146
+        if (
147
+            (isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])
148
+                and $r = lire_php_auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
149
+            or
150
+            // Si auth http differtente de basic, PHP_AUTH_PW
151
+            // est indisponible mais tentons quand meme pour
152
+            // autocreation via LDAP
153
+            (isset($_SERVER['REMOTE_USER'])
154
+                and $r = lire_php_auth($_SERVER['PHP_AUTH_USER'] = $_SERVER['REMOTE_USER'], ''))
155
+        ) {
156
+            if (!$id_auteur) {
157
+                $_SERVER['PHP_AUTH_PW'] = '';
158
+                $GLOBALS['auth_can_disconnect'] = true;
159
+                $GLOBALS['visiteur_session'] = $r;
160
+                $GLOBALS['connect_login'] = session_get('login');
161
+                $id_auteur = $r['id_auteur'];
162
+            } else {
163
+                // cas de la session en plus de PHP_AUTH
164
+                /*				  if ($id_auteur != $r['id_auteur']){
165 165
 					spip_log("vol de session $id_auteur" . join(', ', $r));
166 166
 				unset($_COOKIE['spip_session']);
167 167
 				$id_auteur = '';
168 168
 				} */
169
-			}
170
-		} else {
171
-			// Authentification .htaccess old style, car .htaccess semble
172
-			// souvent definir *aussi* PHP_AUTH_USER et PHP_AUTH_PW
173
-			if (isset($_SERVER['REMOTE_USER'])) {
174
-				$GLOBALS['connect_login'] = $_SERVER['REMOTE_USER'];
175
-			}
176
-		}
177
-	}
178
-
179
-	$where = (is_numeric($id_auteur)
180
-		/*AND $id_auteur>0*/ // reprise lors des restaurations
181
-	) ?
182
-		"id_auteur=$id_auteur" :
183
-		(!strlen($GLOBALS['connect_login']) ? '' : 'login=' . sql_quote($GLOBALS['connect_login'], '', 'text'));
184
-
185
-	if (!$where) {
186
-		return '';
187
-	}
188
-
189
-	// Trouver les autres infos dans la table auteurs.
190
-	// le champ 'quand' est utilise par l'agenda
191
-
192
-	return sql_fetsel('*, en_ligne AS quand', 'spip_auteurs', "$where AND statut!='5poubelle'");
169
+            }
170
+        } else {
171
+            // Authentification .htaccess old style, car .htaccess semble
172
+            // souvent definir *aussi* PHP_AUTH_USER et PHP_AUTH_PW
173
+            if (isset($_SERVER['REMOTE_USER'])) {
174
+                $GLOBALS['connect_login'] = $_SERVER['REMOTE_USER'];
175
+            }
176
+        }
177
+    }
178
+
179
+    $where = (is_numeric($id_auteur)
180
+        /*AND $id_auteur>0*/ // reprise lors des restaurations
181
+    ) ?
182
+        "id_auteur=$id_auteur" :
183
+        (!strlen($GLOBALS['connect_login']) ? '' : 'login=' . sql_quote($GLOBALS['connect_login'], '', 'text'));
184
+
185
+    if (!$where) {
186
+        return '';
187
+    }
188
+
189
+    // Trouver les autres infos dans la table auteurs.
190
+    // le champ 'quand' est utilise par l'agenda
191
+
192
+    return sql_fetsel('*, en_ligne AS quand', 'spip_auteurs', "$where AND statut!='5poubelle'");
193 193
 }
194 194
 
195 195
 /**
@@ -207,86 +207,86 @@  discard block
 block discarded – undo
207 207
  */
208 208
 function auth_init_droits($row) {
209 209
 
210
-	include_spip('inc/autoriser');
211
-	if (!autoriser('loger', '', 0, $row)) {
212
-		return false;
213
-	}
214
-
215
-
216
-	if ($row['statut'] == 'nouveau') {
217
-		include_spip('action/inscrire_auteur');
218
-		$row = confirmer_statut_inscription($row);
219
-	}
220
-
221
-	$GLOBALS['connect_id_auteur'] = $row['id_auteur'];
222
-	$GLOBALS['connect_login'] = $row['login'];
223
-	$GLOBALS['connect_statut'] = $row['statut'];
224
-
225
-	$GLOBALS['visiteur_session'] = array_merge((array)$GLOBALS['visiteur_session'], $row);
226
-
227
-	// au cas ou : ne pas memoriser les champs sensibles
228
-	unset($GLOBALS['visiteur_session']['pass']);
229
-	unset($GLOBALS['visiteur_session']['htpass']);
230
-	unset($GLOBALS['visiteur_session']['alea_actuel']);
231
-	unset($GLOBALS['visiteur_session']['alea_futur']);
232
-	unset($GLOBALS['visiteur_session']['ldap_password']);
233
-
234
-	// creer la session au besoin
235
-	if (!isset($_COOKIE['spip_session'])) {
236
-		$session = charger_fonction('session', 'inc');
237
-		$spip_session = $session($row);
238
-	}
239
-
240
-	// reinjecter les preferences_auteur apres le reset de spip_session
241
-	// car utilisees au retour par auth_loger()
242
-	$r = @unserialize($row['prefs']);
243
-	$GLOBALS['visiteur_session']['prefs'] = ($r ?: []);
244
-	// si prefs pas definies, les definir par defaut
245
-	if (!isset($GLOBALS['visiteur_session']['prefs']['couleur'])) {
246
-		$GLOBALS['visiteur_session']['prefs']['couleur'] = 2;
247
-		$GLOBALS['visiteur_session']['prefs']['display'] = 2;
248
-		$GLOBALS['visiteur_session']['prefs']['display_navigation'] = 'navigation_avec_icones';
249
-		$GLOBALS['visiteur_session']['prefs']['display_outils'] = 'oui';
250
-	}
251
-
252
-	$GLOBALS['visiteur_session'] = pipeline(
253
-		'preparer_visiteur_session',
254
-		['args' => ['row' => $row],
255
-		'data' => $GLOBALS['visiteur_session']]
256
-	);
257
-
258
-	// Etablir les droits selon le codage attendu
259
-	// dans ecrire/index.php ecrire/prive.php
260
-
261
-	// Pas autorise a acceder a ecrire ? renvoyer le tableau
262
-	// A noter : le premier appel a autoriser() a le bon gout
263
-	// d'initialiser $GLOBALS['visiteur_session']['restreint'],
264
-	// qui ne figure pas dans le fichier de session
265
-
266
-	if (!autoriser('ecrire')) {
267
-		return $row;
268
-	}
269
-
270
-	// autoriser('ecrire') ne laisse passer que les Admin et les Redac
271
-
272
-	auth_trace($row);
273
-
274
-	// Administrateurs
275
-	if (in_array($GLOBALS['connect_statut'], explode(',', _STATUT_AUTEUR_RUBRIQUE))) {
276
-		if (
277
-			isset($GLOBALS['visiteur_session']['restreint'])
278
-			and is_array($GLOBALS['visiteur_session']['restreint'])
279
-		) {
280
-			$GLOBALS['connect_id_rubrique'] = $GLOBALS['visiteur_session']['restreint'];
281
-		}
282
-		if ($GLOBALS['connect_statut'] == '0minirezo') {
283
-			$GLOBALS['connect_toutes_rubriques'] = !$GLOBALS['connect_id_rubrique'];
284
-		}
285
-	}
286
-
287
-	// Pour les redacteurs, inc_version a fait l'initialisation minimale
288
-
289
-	return ''; // i.e. pas de pb.
210
+    include_spip('inc/autoriser');
211
+    if (!autoriser('loger', '', 0, $row)) {
212
+        return false;
213
+    }
214
+
215
+
216
+    if ($row['statut'] == 'nouveau') {
217
+        include_spip('action/inscrire_auteur');
218
+        $row = confirmer_statut_inscription($row);
219
+    }
220
+
221
+    $GLOBALS['connect_id_auteur'] = $row['id_auteur'];
222
+    $GLOBALS['connect_login'] = $row['login'];
223
+    $GLOBALS['connect_statut'] = $row['statut'];
224
+
225
+    $GLOBALS['visiteur_session'] = array_merge((array)$GLOBALS['visiteur_session'], $row);
226
+
227
+    // au cas ou : ne pas memoriser les champs sensibles
228
+    unset($GLOBALS['visiteur_session']['pass']);
229
+    unset($GLOBALS['visiteur_session']['htpass']);
230
+    unset($GLOBALS['visiteur_session']['alea_actuel']);
231
+    unset($GLOBALS['visiteur_session']['alea_futur']);
232
+    unset($GLOBALS['visiteur_session']['ldap_password']);
233
+
234
+    // creer la session au besoin
235
+    if (!isset($_COOKIE['spip_session'])) {
236
+        $session = charger_fonction('session', 'inc');
237
+        $spip_session = $session($row);
238
+    }
239
+
240
+    // reinjecter les preferences_auteur apres le reset de spip_session
241
+    // car utilisees au retour par auth_loger()
242
+    $r = @unserialize($row['prefs']);
243
+    $GLOBALS['visiteur_session']['prefs'] = ($r ?: []);
244
+    // si prefs pas definies, les definir par defaut
245
+    if (!isset($GLOBALS['visiteur_session']['prefs']['couleur'])) {
246
+        $GLOBALS['visiteur_session']['prefs']['couleur'] = 2;
247
+        $GLOBALS['visiteur_session']['prefs']['display'] = 2;
248
+        $GLOBALS['visiteur_session']['prefs']['display_navigation'] = 'navigation_avec_icones';
249
+        $GLOBALS['visiteur_session']['prefs']['display_outils'] = 'oui';
250
+    }
251
+
252
+    $GLOBALS['visiteur_session'] = pipeline(
253
+        'preparer_visiteur_session',
254
+        ['args' => ['row' => $row],
255
+        'data' => $GLOBALS['visiteur_session']]
256
+    );
257
+
258
+    // Etablir les droits selon le codage attendu
259
+    // dans ecrire/index.php ecrire/prive.php
260
+
261
+    // Pas autorise a acceder a ecrire ? renvoyer le tableau
262
+    // A noter : le premier appel a autoriser() a le bon gout
263
+    // d'initialiser $GLOBALS['visiteur_session']['restreint'],
264
+    // qui ne figure pas dans le fichier de session
265
+
266
+    if (!autoriser('ecrire')) {
267
+        return $row;
268
+    }
269
+
270
+    // autoriser('ecrire') ne laisse passer que les Admin et les Redac
271
+
272
+    auth_trace($row);
273
+
274
+    // Administrateurs
275
+    if (in_array($GLOBALS['connect_statut'], explode(',', _STATUT_AUTEUR_RUBRIQUE))) {
276
+        if (
277
+            isset($GLOBALS['visiteur_session']['restreint'])
278
+            and is_array($GLOBALS['visiteur_session']['restreint'])
279
+        ) {
280
+            $GLOBALS['connect_id_rubrique'] = $GLOBALS['visiteur_session']['restreint'];
281
+        }
282
+        if ($GLOBALS['connect_statut'] == '0minirezo') {
283
+            $GLOBALS['connect_toutes_rubriques'] = !$GLOBALS['connect_id_rubrique'];
284
+        }
285
+    }
286
+
287
+    // Pour les redacteurs, inc_version a fait l'initialisation minimale
288
+
289
+    return ''; // i.e. pas de pb.
290 290
 }
291 291
 
292 292
 /**
@@ -295,23 +295,23 @@  discard block
 block discarded – undo
295 295
  * @return string
296 296
  */
297 297
 function auth_a_loger() {
298
-	$redirect = generer_url_public('login', 'url=' . rawurlencode(self('&', true)), '&');
299
-
300
-	// un echec au "bonjour" (login initial) quand le statut est
301
-	// inconnu signale sans doute un probleme de cookies
302
-	if (isset($_GET['bonjour'])) {
303
-		$redirect = parametre_url(
304
-			$redirect,
305
-			'var_erreur',
306
-			(!isset($GLOBALS['visiteur_session']['statut'])
307
-				? 'cookie'
308
-				: 'statut'
309
-			),
310
-			'&'
311
-		);
312
-	}
313
-
314
-	return $redirect;
298
+    $redirect = generer_url_public('login', 'url=' . rawurlencode(self('&', true)), '&');
299
+
300
+    // un echec au "bonjour" (login initial) quand le statut est
301
+    // inconnu signale sans doute un probleme de cookies
302
+    if (isset($_GET['bonjour'])) {
303
+        $redirect = parametre_url(
304
+            $redirect,
305
+            'var_erreur',
306
+            (!isset($GLOBALS['visiteur_session']['statut'])
307
+                ? 'cookie'
308
+                : 'statut'
309
+            ),
310
+            '&'
311
+        );
312
+    }
313
+
314
+    return $redirect;
315 315
 }
316 316
 
317 317
 /**
@@ -323,19 +323,19 @@  discard block
 block discarded – undo
323 323
  * @param null|string $date
324 324
  */
325 325
 function auth_trace($row, $date = null) {
326
-	// Indiquer la connexion. A la minute pres ca suffit.
327
-	if (!is_numeric($connect_quand = $row['quand'] ?? '')) {
328
-		$connect_quand = strtotime($connect_quand);
329
-	}
326
+    // Indiquer la connexion. A la minute pres ca suffit.
327
+    if (!is_numeric($connect_quand = $row['quand'] ?? '')) {
328
+        $connect_quand = strtotime($connect_quand);
329
+    }
330 330
 
331
-	$date ??= date('Y-m-d H:i:s');
331
+    $date ??= date('Y-m-d H:i:s');
332 332
 
333
-	if (abs(strtotime($date) - $connect_quand) >= 60) {
334
-		sql_updateq('spip_auteurs', ['en_ligne' => $date], 'id_auteur=' . intval($row['id_auteur']));
335
-		$row['en_ligne'] = $date;
336
-	}
333
+    if (abs(strtotime($date) - $connect_quand) >= 60) {
334
+        sql_updateq('spip_auteurs', ['en_ligne' => $date], 'id_auteur=' . intval($row['id_auteur']));
335
+        $row['en_ligne'] = $date;
336
+    }
337 337
 
338
-	pipeline('trig_auth_trace', ['args' => ['row' => $row, 'date' => $date]]);
338
+    pipeline('trig_auth_trace', ['args' => ['row' => $row, 'date' => $date]]);
339 339
 }
340 340
 
341 341
 
@@ -361,28 +361,28 @@  discard block
 block discarded – undo
361 361
  * @return mixed
362 362
  */
363 363
 function auth_administrer($fonction, $args, $defaut = false) {
364
-	$auth_methode = array_shift($args);
365
-	$auth_methode = $auth_methode ?: 'spip'; // valeur par defaut au cas ou
366
-	if (
367
-		$auth = charger_fonction($auth_methode, 'auth', true)
368
-		and function_exists($f = "auth_{$auth_methode}_$fonction")
369
-	) {
370
-		$res = call_user_func_array($f, $args);
371
-	} else {
372
-		$res = $defaut;
373
-	}
374
-	$res = pipeline(
375
-		'auth_administrer',
376
-		[
377
-			'args' => [
378
-				'fonction' => $fonction,
379
-				'methode' => $auth_methode,
380
-				'args' => $args
381
-			],
382
-			'data' => $res
383
-		]
384
-	);
385
-	return $res;
364
+    $auth_methode = array_shift($args);
365
+    $auth_methode = $auth_methode ?: 'spip'; // valeur par defaut au cas ou
366
+    if (
367
+        $auth = charger_fonction($auth_methode, 'auth', true)
368
+        and function_exists($f = "auth_{$auth_methode}_$fonction")
369
+    ) {
370
+        $res = call_user_func_array($f, $args);
371
+    } else {
372
+        $res = $defaut;
373
+    }
374
+    $res = pipeline(
375
+        'auth_administrer',
376
+        [
377
+            'args' => [
378
+                'fonction' => $fonction,
379
+                'methode' => $auth_methode,
380
+                'args' => $args
381
+            ],
382
+            'data' => $res
383
+        ]
384
+    );
385
+    return $res;
386 386
 }
387 387
 
388 388
 /**
@@ -392,11 +392,11 @@  discard block
 block discarded – undo
392 392
  * @return array
393 393
  */
394 394
 function auth_formulaire_login($flux) {
395
-	foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
396
-		$flux = auth_administrer('formulaire_login', [$methode, $flux], $flux);
397
-	}
395
+    foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
396
+        $flux = auth_administrer('formulaire_login', [$methode, $flux], $flux);
397
+    }
398 398
 
399
-	return $flux;
399
+    return $flux;
400 400
 }
401 401
 
402 402
 
@@ -410,19 +410,19 @@  discard block
 block discarded – undo
410 410
  * @return string/bool
411 411
  */
412 412
 function auth_retrouver_login($login, $serveur = '') {
413
-	if (!spip_connect($serveur)) {
414
-		include_spip('inc/minipres');
415
-		echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'));
416
-		exit;
417
-	}
418
-
419
-	foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
420
-		if ($auteur = auth_administrer('retrouver_login', [$methode, $login, $serveur])) {
421
-			return $auteur;
422
-		}
423
-	}
424
-
425
-	return false;
413
+    if (!spip_connect($serveur)) {
414
+        include_spip('inc/minipres');
415
+        echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'));
416
+        exit;
417
+    }
418
+
419
+    foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
420
+        if ($auteur = auth_administrer('retrouver_login', [$methode, $login, $serveur])) {
421
+            return $auteur;
422
+        }
423
+    }
424
+
425
+    return false;
426 426
 }
427 427
 
428 428
 /**
@@ -437,52 +437,52 @@  discard block
 block discarded – undo
437 437
  * @return array
438 438
  */
439 439
 function auth_informer_login($login, $serveur = '') {
440
-	if (
441
-		!$login
442
-		or !$login_base = auth_retrouver_login($login, $serveur)
443
-		or !$row = sql_fetsel('*', 'spip_auteurs', 'login=' . sql_quote($login_base, $serveur, 'text'), '', '', '', '', $serveur)
444
-	) {
445
-		// generer de fausses infos, mais credibles, pour eviter une attaque
446
-		// https://core.spip.net/issues/1758 + https://core.spip.net/issues/3691
447
-		include_spip('inc/securiser_action');
448
-		$fauxalea1 = md5('fauxalea' . secret_du_site() . $login . floor(date('U') / 86400));
449
-		$fauxalea2 = md5('fauxalea' . secret_du_site() . $login . ceil(date('U') / 86400));
450
-
451
-		$row = [
452
-			'login' => $login,
453
-			'cnx' => '0',
454
-			'logo' => '',
455
-			'alea_actuel' => substr_replace($fauxalea1, '.', 24, 0),
456
-			'alea_futur' => substr_replace($fauxalea2, '.', 24, 0)
457
-		];
458
-
459
-		// permettre d'autoriser l'envoi de password non crypte lorsque
460
-		// l'auteur n'est pas (encore) declare dans SPIP, par exemple pour les cas
461
-		// de premiere authentification via SPIP a une autre application.
462
-		if (defined('_AUTORISER_AUTH_FAIBLE') and _AUTORISER_AUTH_FAIBLE) {
463
-			$row['alea_actuel'] = '';
464
-			$row['alea_futur'] = '';
465
-		}
466
-
467
-		return $row;
468
-	}
469
-
470
-	$prefs = @unserialize($row['prefs']);
471
-	$infos = [
472
-		'id_auteur' => $row['id_auteur'],
473
-		'login' => $row['login'],
474
-		'cnx' => (isset($prefs['cnx']) and $prefs['cnx'] === 'perma') ? '1' : '0',
475
-		'logo' => recuperer_fond('formulaires/inc-logo_auteur', $row),
476
-	];
477
-
478
-	// desactiver le hash md5 si pas auteur spip ?
479
-	if ($row['source'] !== 'spip') {
480
-		$row['alea_actuel'] = '';
481
-		$row['alea_futur'] = '';
482
-	}
483
-	verifier_visiteur();
484
-
485
-	return auth_administrer('informer_login', [$row['source'], $infos, $row, $serveur], $infos);
440
+    if (
441
+        !$login
442
+        or !$login_base = auth_retrouver_login($login, $serveur)
443
+        or !$row = sql_fetsel('*', 'spip_auteurs', 'login=' . sql_quote($login_base, $serveur, 'text'), '', '', '', '', $serveur)
444
+    ) {
445
+        // generer de fausses infos, mais credibles, pour eviter une attaque
446
+        // https://core.spip.net/issues/1758 + https://core.spip.net/issues/3691
447
+        include_spip('inc/securiser_action');
448
+        $fauxalea1 = md5('fauxalea' . secret_du_site() . $login . floor(date('U') / 86400));
449
+        $fauxalea2 = md5('fauxalea' . secret_du_site() . $login . ceil(date('U') / 86400));
450
+
451
+        $row = [
452
+            'login' => $login,
453
+            'cnx' => '0',
454
+            'logo' => '',
455
+            'alea_actuel' => substr_replace($fauxalea1, '.', 24, 0),
456
+            'alea_futur' => substr_replace($fauxalea2, '.', 24, 0)
457
+        ];
458
+
459
+        // permettre d'autoriser l'envoi de password non crypte lorsque
460
+        // l'auteur n'est pas (encore) declare dans SPIP, par exemple pour les cas
461
+        // de premiere authentification via SPIP a une autre application.
462
+        if (defined('_AUTORISER_AUTH_FAIBLE') and _AUTORISER_AUTH_FAIBLE) {
463
+            $row['alea_actuel'] = '';
464
+            $row['alea_futur'] = '';
465
+        }
466
+
467
+        return $row;
468
+    }
469
+
470
+    $prefs = @unserialize($row['prefs']);
471
+    $infos = [
472
+        'id_auteur' => $row['id_auteur'],
473
+        'login' => $row['login'],
474
+        'cnx' => (isset($prefs['cnx']) and $prefs['cnx'] === 'perma') ? '1' : '0',
475
+        'logo' => recuperer_fond('formulaires/inc-logo_auteur', $row),
476
+    ];
477
+
478
+    // desactiver le hash md5 si pas auteur spip ?
479
+    if ($row['source'] !== 'spip') {
480
+        $row['alea_actuel'] = '';
481
+        $row['alea_futur'] = '';
482
+    }
483
+    verifier_visiteur();
484
+
485
+    return auth_administrer('informer_login', [$row['source'], $infos, $row, $serveur], $infos);
486 486
 }
487 487
 
488 488
 
@@ -496,21 +496,21 @@  discard block
 block discarded – undo
496 496
  * @return mixed
497 497
  */
498 498
 function auth_identifier_login($login, $password, $serveur = '') {
499
-	$erreur = '';
500
-	foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
501
-		if ($auth = charger_fonction($methode, 'auth', true)) {
502
-			$auteur = $auth($login, $password, $serveur);
503
-			if (is_array($auteur) and count($auteur)) {
504
-				spip_log("connexion de $login par methode $methode");
505
-				$auteur['auth'] = $methode;
506
-				return $auteur;
507
-			} elseif (is_string($auteur)) {
508
-				$erreur .= "$auteur ";
509
-			}
510
-		}
511
-	}
512
-
513
-	return $erreur;
499
+    $erreur = '';
500
+    foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
501
+        if ($auth = charger_fonction($methode, 'auth', true)) {
502
+            $auteur = $auth($login, $password, $serveur);
503
+            if (is_array($auteur) and count($auteur)) {
504
+                spip_log("connexion de $login par methode $methode");
505
+                $auteur['auth'] = $methode;
506
+                return $auteur;
507
+            } elseif (is_string($auteur)) {
508
+                $erreur .= "$auteur ";
509
+            }
510
+        }
511
+    }
512
+
513
+    return $erreur;
514 514
 }
515 515
 
516 516
 /**
@@ -524,8 +524,8 @@  discard block
 block discarded – undo
524 524
  * @return string
525 525
  */
526 526
 function auth_url_retour_login($auth_methode, $login, $redirect = '', $serveur = '') {
527
-	$securiser_action = charger_fonction('securiser_action', 'inc');
528
-	return $securiser_action('auth', "$auth_methode/$login", $redirect, true);
527
+    $securiser_action = charger_fonction('securiser_action', 'inc');
528
+    return $securiser_action('auth', "$auth_methode/$login", $redirect, true);
529 529
 }
530 530
 
531 531
 /**
@@ -539,9 +539,9 @@  discard block
 block discarded – undo
539 539
  * @return mixed
540 540
  */
541 541
 function auth_terminer_identifier_login($auth_methode, $login, $serveur = '') {
542
-	$args = func_get_args();
543
-	$auteur = auth_administrer('terminer_identifier_login', $args);
544
-	return $auteur;
542
+    $args = func_get_args();
543
+    $auteur = auth_administrer('terminer_identifier_login', $args);
544
+    return $auteur;
545 545
 }
546 546
 
547 547
 /**
@@ -551,29 +551,29 @@  discard block
 block discarded – undo
551 551
  * @return bool
552 552
  */
553 553
 function auth_loger($auteur) {
554
-	if (!is_array($auteur) or !count($auteur)) {
555
-		return false;
556
-	}
557
-
558
-	// initialiser et poser le cookie de session
559
-	unset($_COOKIE['spip_session']);
560
-	if (auth_init_droits($auteur) === false) {
561
-		return false;
562
-	}
563
-
564
-	// initialiser les prefs
565
-	$p = $GLOBALS['visiteur_session']['prefs'];
566
-	$p['cnx'] = (isset($auteur['cookie']) and $auteur['cookie'] == 'oui') ? 'perma' : '';
567
-
568
-	sql_updateq(
569
-		'spip_auteurs',
570
-		['prefs' => serialize($p)],
571
-		'id_auteur=' . intval($auteur['id_auteur'])
572
-	);
573
-
574
-	//  bloquer ici le visiteur qui tente d'abuser de ses droits
575
-	verifier_visiteur();
576
-	return true;
554
+    if (!is_array($auteur) or !count($auteur)) {
555
+        return false;
556
+    }
557
+
558
+    // initialiser et poser le cookie de session
559
+    unset($_COOKIE['spip_session']);
560
+    if (auth_init_droits($auteur) === false) {
561
+        return false;
562
+    }
563
+
564
+    // initialiser les prefs
565
+    $p = $GLOBALS['visiteur_session']['prefs'];
566
+    $p['cnx'] = (isset($auteur['cookie']) and $auteur['cookie'] == 'oui') ? 'perma' : '';
567
+
568
+    sql_updateq(
569
+        'spip_auteurs',
570
+        ['prefs' => serialize($p)],
571
+        'id_auteur=' . intval($auteur['id_auteur'])
572
+    );
573
+
574
+    //  bloquer ici le visiteur qui tente d'abuser de ses droits
575
+    verifier_visiteur();
576
+    return true;
577 577
 }
578 578
 
579 579
 /**
@@ -583,8 +583,8 @@  discard block
 block discarded – undo
583 583
  * return void
584 584
  **/
585 585
 function auth_deloger() {
586
-	$logout = charger_fonction('logout', 'action');
587
-	$logout();
586
+    $logout = charger_fonction('logout', 'action');
587
+    $logout();
588 588
 }
589 589
 
590 590
 /**
@@ -598,8 +598,8 @@  discard block
 block discarded – undo
598 598
  * @return bool
599 599
  */
600 600
 function auth_autoriser_modifier_login($auth_methode, $serveur = '') {
601
-	$args = func_get_args();
602
-	return auth_administrer('autoriser_modifier_login', $args);
601
+    $args = func_get_args();
602
+    return auth_administrer('autoriser_modifier_login', $args);
603 603
 }
604 604
 
605 605
 /**
@@ -614,8 +614,8 @@  discard block
 block discarded – undo
614 614
  *  message d'erreur ou chaine vide si pas d'erreur
615 615
  */
616 616
 function auth_verifier_login($auth_methode, $new_login, $id_auteur = 0, $serveur = '') {
617
-	$args = func_get_args();
618
-	return auth_administrer('verifier_login', $args, '');
617
+    $args = func_get_args();
618
+    return auth_administrer('verifier_login', $args, '');
619 619
 }
620 620
 
621 621
 /**
@@ -628,8 +628,8 @@  discard block
 block discarded – undo
628 628
  * @return bool
629 629
  */
630 630
 function auth_modifier_login($auth_methode, $new_login, $id_auteur, $serveur = '') {
631
-	$args = func_get_args();
632
-	return auth_administrer('modifier_login', $args);
631
+    $args = func_get_args();
632
+    return auth_administrer('modifier_login', $args);
633 633
 }
634 634
 
635 635
 /**
@@ -644,8 +644,8 @@  discard block
 block discarded – undo
644 644
  *  succès ou échec
645 645
  */
646 646
 function auth_autoriser_modifier_pass($auth_methode, $serveur = '') {
647
-	$args = func_get_args();
648
-	return auth_administrer('autoriser_modifier_pass', $args);
647
+    $args = func_get_args();
648
+    return auth_administrer('autoriser_modifier_pass', $args);
649 649
 }
650 650
 
651 651
 /**
@@ -661,8 +661,8 @@  discard block
 block discarded – undo
661 661
  *  message d'erreur ou chaine vide si pas d'erreur
662 662
  */
663 663
 function auth_verifier_pass($auth_methode, $login, $new_pass, $id_auteur = 0, $serveur = '') {
664
-	$args = func_get_args();
665
-	return auth_administrer('verifier_pass', $args, '');
664
+    $args = func_get_args();
665
+    return auth_administrer('verifier_pass', $args, '');
666 666
 }
667 667
 
668 668
 /**
@@ -678,8 +678,8 @@  discard block
 block discarded – undo
678 678
  *  succes ou echec
679 679
  */
680 680
 function auth_modifier_pass($auth_methode, $login, $new_pass, $id_auteur, $serveur = '') {
681
-	$args = func_get_args();
682
-	return auth_administrer('modifier_pass', $args);
681
+    $args = func_get_args();
682
+    return auth_administrer('modifier_pass', $args);
683 683
 }
684 684
 
685 685
 /**
@@ -695,24 +695,24 @@  discard block
 block discarded – undo
695 695
  * @return void
696 696
  */
697 697
 function auth_synchroniser_distant(
698
-	$auth_methode = true,
699
-	$id_auteur = 0,
700
-	$champs = [],
701
-	$options = [],
702
-	$serveur = ''
698
+    $auth_methode = true,
699
+    $id_auteur = 0,
700
+    $champs = [],
701
+    $options = [],
702
+    $serveur = ''
703 703
 ) {
704
-	$args = func_get_args();
705
-	if ($auth_methode === true or (isset($options['all']) and $options['all'] == true)) {
706
-		$options['all'] = true; // ajouter une option all=>true pour chaque auth
707
-		$args = [true, $id_auteur, $champs, $options, $serveur];
708
-		foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
709
-			array_shift($args);
710
-			array_unshift($args, $methode);
711
-			auth_administrer('synchroniser_distant', $args);
712
-		}
713
-	} else {
714
-		auth_administrer('synchroniser_distant', $args);
715
-	}
704
+    $args = func_get_args();
705
+    if ($auth_methode === true or (isset($options['all']) and $options['all'] == true)) {
706
+        $options['all'] = true; // ajouter une option all=>true pour chaque auth
707
+        $args = [true, $id_auteur, $champs, $options, $serveur];
708
+        foreach ($GLOBALS['liste_des_authentifications'] as $methode) {
709
+            array_shift($args);
710
+            array_unshift($args, $methode);
711
+            auth_administrer('synchroniser_distant', $args);
712
+        }
713
+    } else {
714
+        auth_administrer('synchroniser_distant', $args);
715
+    }
716 716
 }
717 717
 
718 718
 
@@ -725,44 +725,44 @@  discard block
 block discarded – undo
725 725
  * @return array|bool
726 726
  */
727 727
 function lire_php_auth($login, $pw, $serveur = '') {
728
-	if (
729
-		!$login
730
-		or !$login = auth_retrouver_login($login, $serveur)
731
-	) {
732
-		return false;
733
-	}
734
-
735
-	$row = sql_fetsel('*', 'spip_auteurs', 'login=' . sql_quote($login, $serveur, 'text'), '', '', '', '', $serveur);
736
-
737
-	if (!$row) {
738
-		if (
739
-			spip_connect_ldap($serveur)
740
-			and $auth_ldap = charger_fonction('ldap', 'auth', true)
741
-		) {
742
-			return $auth_ldap($login, $pw, $serveur, true);
743
-		}
744
-
745
-		return false;
746
-	}
747
-	// su pas de source definie
748
-	// ou auth/xxx introuvable, utiliser 'spip'
749
-	if (
750
-		!$auth_methode = $row['source']
751
-		or !$auth = charger_fonction($auth_methode, 'auth', true)
752
-	) {
753
-		$auth = charger_fonction('spip', 'auth', true);
754
-	}
755
-
756
-	$auteur = '';
757
-	if ($auth) {
758
-		$auteur = $auth($login, $pw, $serveur, true);
759
-	}
760
-	// verifier que ce n'est pas un message d'erreur
761
-	if (is_array($auteur) and count($auteur)) {
762
-		return $auteur;
763
-	}
764
-
765
-	return false;
728
+    if (
729
+        !$login
730
+        or !$login = auth_retrouver_login($login, $serveur)
731
+    ) {
732
+        return false;
733
+    }
734
+
735
+    $row = sql_fetsel('*', 'spip_auteurs', 'login=' . sql_quote($login, $serveur, 'text'), '', '', '', '', $serveur);
736
+
737
+    if (!$row) {
738
+        if (
739
+            spip_connect_ldap($serveur)
740
+            and $auth_ldap = charger_fonction('ldap', 'auth', true)
741
+        ) {
742
+            return $auth_ldap($login, $pw, $serveur, true);
743
+        }
744
+
745
+        return false;
746
+    }
747
+    // su pas de source definie
748
+    // ou auth/xxx introuvable, utiliser 'spip'
749
+    if (
750
+        !$auth_methode = $row['source']
751
+        or !$auth = charger_fonction($auth_methode, 'auth', true)
752
+    ) {
753
+        $auth = charger_fonction('spip', 'auth', true);
754
+    }
755
+
756
+    $auteur = '';
757
+    if ($auth) {
758
+        $auteur = $auth($login, $pw, $serveur, true);
759
+    }
760
+    // verifier que ce n'est pas un message d'erreur
761
+    if (is_array($auteur) and count($auteur)) {
762
+        return $auteur;
763
+    }
764
+
765
+    return false;
766 766
 }
767 767
 
768 768
 /**
@@ -778,21 +778,21 @@  discard block
 block discarded – undo
778 778
  * @param string $lien
779 779
  */
780 780
 function ask_php_auth($pb, $raison, $retour = '', $url = '', $re = '', $lien = '') {
781
-	@Header('WWW-Authenticate: Basic realm="espace prive"');
782
-	@Header('HTTP/1.0 401 Unauthorized');
783
-	$corps = '';
784
-	$public = generer_url_public();
785
-	$ecrire = generer_url_ecrire();
786
-	$retour = $retour ?: _T('icone_retour');
787
-	$corps .= "<p>$raison</p>[<a href='$public'>$retour</a>] ";
788
-	if ($url) {
789
-		$corps .= "[<a href='" . generer_url_action('cookie', "essai_auth_http=oui&$url") . "'>$re</a>]";
790
-	}
791
-
792
-	if ($lien) {
793
-		$corps .= " [<a href='$ecrire'>" . _T('login_espace_prive') . '</a>]';
794
-	}
795
-	include_spip('inc/minipres');
796
-	echo minipres($pb, $corps);
797
-	exit;
781
+    @Header('WWW-Authenticate: Basic realm="espace prive"');
782
+    @Header('HTTP/1.0 401 Unauthorized');
783
+    $corps = '';
784
+    $public = generer_url_public();
785
+    $ecrire = generer_url_ecrire();
786
+    $retour = $retour ?: _T('icone_retour');
787
+    $corps .= "<p>$raison</p>[<a href='$public'>$retour</a>] ";
788
+    if ($url) {
789
+        $corps .= "[<a href='" . generer_url_action('cookie', "essai_auth_http=oui&$url") . "'>$re</a>]";
790
+    }
791
+
792
+    if ($lien) {
793
+        $corps .= " [<a href='$ecrire'>" . _T('login_espace_prive') . '</a>]';
794
+    }
795
+    include_spip('inc/minipres');
796
+    echo minipres($pb, $corps);
797
+    exit;
798 798
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_images_lib_mini.php 1 patch
Indentation   +1351 added lines, -1351 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  */
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 include_spip('inc/filtres'); // par precaution
24 24
 include_spip('inc/filtres_images_mini'); // par precaution
@@ -38,21 +38,21 @@  discard block
 block discarded – undo
38 38
  *     Le code de la couleur en hexadécimal.
39 39
  */
40 40
 function _couleur_dec_to_hex($red, $green, $blue) {
41
-	$red = dechex($red);
42
-	$green = dechex($green);
43
-	$blue = dechex($blue);
44
-
45
-	if (strlen($red) == 1) {
46
-		$red = '0' . $red;
47
-	}
48
-	if (strlen($green) == 1) {
49
-		$green = '0' . $green;
50
-	}
51
-	if (strlen($blue) == 1) {
52
-		$blue = '0' . $blue;
53
-	}
54
-
55
-	return "$red$green$blue";
41
+    $red = dechex($red);
42
+    $green = dechex($green);
43
+    $blue = dechex($blue);
44
+
45
+    if (strlen($red) == 1) {
46
+        $red = '0' . $red;
47
+    }
48
+    if (strlen($green) == 1) {
49
+        $green = '0' . $green;
50
+    }
51
+    if (strlen($blue) == 1) {
52
+        $blue = '0' . $blue;
53
+    }
54
+
55
+    return "$red$green$blue";
56 56
 }
57 57
 
58 58
 /**
@@ -64,17 +64,17 @@  discard block
 block discarded – undo
64 64
  *     Un tableau des 3 éléments : rouge, vert, bleu.
65 65
  */
66 66
 function _couleur_hex_to_dec($couleur) {
67
-	$couleur = couleur_html_to_hex($couleur);
68
-	$couleur = ltrim($couleur, '#');
69
-	if (strlen($couleur) === 3) {
70
-		$couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
71
-	}
72
-	$retour = [];
73
-	$retour['red'] = hexdec(substr($couleur, 0, 2));
74
-	$retour['green'] = hexdec(substr($couleur, 2, 2));
75
-	$retour['blue'] = hexdec(substr($couleur, 4, 2));
76
-
77
-	return $retour;
67
+    $couleur = couleur_html_to_hex($couleur);
68
+    $couleur = ltrim($couleur, '#');
69
+    if (strlen($couleur) === 3) {
70
+        $couleur = $couleur[0] . $couleur[0] . $couleur[1] . $couleur[1] . $couleur[2] . $couleur[2];
71
+    }
72
+    $retour = [];
73
+    $retour['red'] = hexdec(substr($couleur, 0, 2));
74
+    $retour['green'] = hexdec(substr($couleur, 2, 2));
75
+    $retour['blue'] = hexdec(substr($couleur, 4, 2));
76
+
77
+    return $retour;
78 78
 }
79 79
 
80 80
 
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
  *     Le code de la couleur en hexadécimal.
92 92
  */
93 93
 function _couleur_hsl_to_hex($hue, $saturation, $lightness) {
94
-	$rgb = _couleur_hsl_to_rgb($hue, $saturation, $lightness);
95
-	return _couleur_dec_to_hex($rgb['r'], $rgb['g'], $rgb['b']);
94
+    $rgb = _couleur_hsl_to_rgb($hue, $saturation, $lightness);
95
+    return _couleur_dec_to_hex($rgb['r'], $rgb['g'], $rgb['b']);
96 96
 }
97 97
 
98 98
 /**
@@ -104,8 +104,8 @@  discard block
 block discarded – undo
104 104
  *     Un tableau des 3 éléments : teinte, saturation, luminosité.
105 105
  */
106 106
 function _couleur_hex_to_hsl($couleur) {
107
-	$rgb = _couleur_hex_to_dec($couleur);
108
-	return _couleur_rgb_to_hsl($rgb['red'], $rgb['green'], $rgb['blue']);
107
+    $rgb = _couleur_hex_to_dec($couleur);
108
+    return _couleur_rgb_to_hsl($rgb['red'], $rgb['green'], $rgb['blue']);
109 109
 }
110 110
 
111 111
 /**
@@ -120,59 +120,59 @@  discard block
 block discarded – undo
120 120
  * @return array
121 121
  */
122 122
 function _couleur_rgb_to_hsl($R, $G, $B) {
123
-	$H = null;
124
-	$var_R = ($R / 255); // Where RGB values = 0 ÷ 255
125
-	$var_G = ($G / 255);
126
-	$var_B = ($B / 255);
127
-
128
-	$var_Min = min($var_R, $var_G, $var_B);   //Min. value of RGB
129
-	$var_Max = max($var_R, $var_G, $var_B);   //Max. value of RGB
130
-	$del_Max = $var_Max - $var_Min;           //Delta RGB value
131
-
132
-	$L = ($var_Max + $var_Min) / 2;
133
-
134
-	if ($del_Max == 0) {
135
-		//This is a gray, no chroma...
136
-		$H = 0; //HSL results = 0 ÷ 1
137
-		$S = 0;
138
-	} else {
139
-		// Chromatic data...
140
-		if ($L < 0.5) {
141
-			$S = $del_Max / ($var_Max + $var_Min);
142
-		} else {
143
-			$S = $del_Max / (2 - $var_Max - $var_Min);
144
-		}
145
-
146
-		$del_R = ((($var_Max - $var_R) / 6) + ($del_Max / 2)) / $del_Max;
147
-		$del_G = ((($var_Max - $var_G) / 6) + ($del_Max / 2)) / $del_Max;
148
-		$del_B = ((($var_Max - $var_B) / 6) + ($del_Max / 2)) / $del_Max;
149
-
150
-		if ($var_R == $var_Max) {
151
-			$H = $del_B - $del_G;
152
-		} else {
153
-			if ($var_G == $var_Max) {
154
-				$H = (1 / 3) + $del_R - $del_B;
155
-			} else {
156
-				if ($var_B == $var_Max) {
157
-					$H = (2 / 3) + $del_G - $del_R;
158
-				}
159
-			}
160
-		}
161
-
162
-		if ($H < 0) {
163
-			$H += 1;
164
-		}
165
-		if ($H > 1) {
166
-			$H -= 1;
167
-		}
168
-	}
169
-
170
-	$ret = [];
171
-	$ret['h'] = $H;
172
-	$ret['s'] = $S;
173
-	$ret['l'] = $L;
174
-
175
-	return $ret;
123
+    $H = null;
124
+    $var_R = ($R / 255); // Where RGB values = 0 ÷ 255
125
+    $var_G = ($G / 255);
126
+    $var_B = ($B / 255);
127
+
128
+    $var_Min = min($var_R, $var_G, $var_B);   //Min. value of RGB
129
+    $var_Max = max($var_R, $var_G, $var_B);   //Max. value of RGB
130
+    $del_Max = $var_Max - $var_Min;           //Delta RGB value
131
+
132
+    $L = ($var_Max + $var_Min) / 2;
133
+
134
+    if ($del_Max == 0) {
135
+        //This is a gray, no chroma...
136
+        $H = 0; //HSL results = 0 ÷ 1
137
+        $S = 0;
138
+    } else {
139
+        // Chromatic data...
140
+        if ($L < 0.5) {
141
+            $S = $del_Max / ($var_Max + $var_Min);
142
+        } else {
143
+            $S = $del_Max / (2 - $var_Max - $var_Min);
144
+        }
145
+
146
+        $del_R = ((($var_Max - $var_R) / 6) + ($del_Max / 2)) / $del_Max;
147
+        $del_G = ((($var_Max - $var_G) / 6) + ($del_Max / 2)) / $del_Max;
148
+        $del_B = ((($var_Max - $var_B) / 6) + ($del_Max / 2)) / $del_Max;
149
+
150
+        if ($var_R == $var_Max) {
151
+            $H = $del_B - $del_G;
152
+        } else {
153
+            if ($var_G == $var_Max) {
154
+                $H = (1 / 3) + $del_R - $del_B;
155
+            } else {
156
+                if ($var_B == $var_Max) {
157
+                    $H = (2 / 3) + $del_G - $del_R;
158
+                }
159
+            }
160
+        }
161
+
162
+        if ($H < 0) {
163
+            $H += 1;
164
+        }
165
+        if ($H > 1) {
166
+            $H -= 1;
167
+        }
168
+    }
169
+
170
+    $ret = [];
171
+    $ret['h'] = $H;
172
+    $ret['s'] = $S;
173
+    $ret['l'] = $L;
174
+
175
+    return $ret;
176 176
 }
177 177
 
178 178
 
@@ -188,52 +188,52 @@  discard block
 block discarded – undo
188 188
  * @return array
189 189
  */
190 190
 function _couleur_hsl_to_rgb($H, $S, $L) {
191
-	// helper
192
-	$hue_2_rgb = function ($v1, $v2, $vH) {
193
-		if ($vH < 0) {
194
-			$vH += 1;
195
-		}
196
-		if ($vH > 1) {
197
-			$vH -= 1;
198
-		}
199
-		if ((6 * $vH) < 1) {
200
-			return ($v1 + ($v2 - $v1) * 6 * $vH);
201
-		}
202
-		if ((2 * $vH) < 1) {
203
-			return ($v2);
204
-		}
205
-		if ((3 * $vH) < 2) {
206
-			return ($v1 + ($v2 - $v1) * ((2 / 3) - $vH) * 6);
207
-		}
208
-
209
-		return ($v1);
210
-	};
211
-
212
-	if ($S == 0) {
213
-		// HSV values = 0 -> 1
214
-		$R = $L * 255;
215
-		$G = $L * 255;
216
-		$B = $L * 255;
217
-	} else {
218
-		if ($L < 0.5) {
219
-			$var_2 = $L * (1 + $S);
220
-		} else {
221
-			$var_2 = ($L + $S) - ($S * $L);
222
-		}
223
-
224
-		$var_1 = 2 * $L - $var_2;
225
-
226
-		$R = 255 * $hue_2_rgb($var_1, $var_2, $H + (1 / 3));
227
-		$G = 255 * $hue_2_rgb($var_1, $var_2, $H);
228
-		$B = 255 * $hue_2_rgb($var_1, $var_2, $H - (1 / 3));
229
-	}
230
-
231
-	$ret = [];
232
-	$ret['r'] = floor($R);
233
-	$ret['g'] = floor($G);
234
-	$ret['b'] = floor($B);
235
-
236
-	return $ret;
191
+    // helper
192
+    $hue_2_rgb = function ($v1, $v2, $vH) {
193
+        if ($vH < 0) {
194
+            $vH += 1;
195
+        }
196
+        if ($vH > 1) {
197
+            $vH -= 1;
198
+        }
199
+        if ((6 * $vH) < 1) {
200
+            return ($v1 + ($v2 - $v1) * 6 * $vH);
201
+        }
202
+        if ((2 * $vH) < 1) {
203
+            return ($v2);
204
+        }
205
+        if ((3 * $vH) < 2) {
206
+            return ($v1 + ($v2 - $v1) * ((2 / 3) - $vH) * 6);
207
+        }
208
+
209
+        return ($v1);
210
+    };
211
+
212
+    if ($S == 0) {
213
+        // HSV values = 0 -> 1
214
+        $R = $L * 255;
215
+        $G = $L * 255;
216
+        $B = $L * 255;
217
+    } else {
218
+        if ($L < 0.5) {
219
+            $var_2 = $L * (1 + $S);
220
+        } else {
221
+            $var_2 = ($L + $S) - ($S * $L);
222
+        }
223
+
224
+        $var_1 = 2 * $L - $var_2;
225
+
226
+        $R = 255 * $hue_2_rgb($var_1, $var_2, $H + (1 / 3));
227
+        $G = 255 * $hue_2_rgb($var_1, $var_2, $H);
228
+        $B = 255 * $hue_2_rgb($var_1, $var_2, $H - (1 / 3));
229
+    }
230
+
231
+    $ret = [];
232
+    $ret['r'] = floor($R);
233
+    $ret['g'] = floor($G);
234
+    $ret['b'] = floor($B);
235
+
236
+    return $ret;
237 237
 }
238 238
 
239 239
 /**
@@ -250,11 +250,11 @@  discard block
 block discarded – undo
250 250
  *     true si il faut supprimer le fichier temporaire ; false sinon.
251 251
  */
252 252
 function statut_effacer_images_temporaires($stat) {
253
-	static $statut = false; // par defaut on grave toute les images
254
-	if ($stat === 'get') {
255
-		return $statut;
256
-	}
257
-	$statut = $stat ? true : false;
253
+    static $statut = false; // par defaut on grave toute les images
254
+    if ($stat === 'get') {
255
+        return $statut;
256
+    }
257
+    $statut = $stat ? true : false;
258 258
 }
259 259
 
260 260
 
@@ -307,243 +307,243 @@  discard block
 block discarded – undo
307 307
  *     - array : tableau décrivant de l'image
308 308
  */
309 309
 function _image_valeurs_trans($img, $effet, $forcer_format = false, $fonction_creation = null, $find_in_path = false, $support_svg = false) {
310
-	$ret = [];
311
-	$f = null;
312
-	static $images_recalcul = [];
313
-	if (strlen($img) == 0) {
314
-		return false;
315
-	}
316
-
317
-	$source = trim(extraire_attribut($img, 'src') ?? '');
318
-	if (strlen($source) < 1) {
319
-		$source = $img;
320
-		$img = "<img src='$source' />";
321
-	} elseif (
322
-		preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
323
-		and $extension = _image_trouver_extension_depuis_mime('image/' . $regs[1])
324
-		and in_array($extension, _image_extensions_acceptees_en_entree())
325
-	) {
326
-		# gerer img src="data:....base64"
327
-		$local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
328
-		if (!file_exists($local)) {
329
-			ecrire_fichier($local, base64_decode($regs[2]));
330
-		}
331
-		if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
332
-			$sanitizer($local);
333
-		}
334
-		$source = $local;
335
-		$img = inserer_attribut($img, 'src', $source);
336
-		# eviter les mauvaises surprises lors de conversions de format
337
-		$img = inserer_attribut($img, 'width', '');
338
-		$img = inserer_attribut($img, 'height', '');
339
-	}
340
-
341
-	// les protocoles web prennent au moins 3 lettres
342
-	if (tester_url_absolue($source)) {
343
-		include_spip('inc/distant');
344
-		$fichier = _DIR_RACINE . copie_locale($source);
345
-		if (!$fichier) {
346
-			return '';
347
-		}
348
-		if (
349
-			$extension = _image_trouver_extension($fichier)
350
-			and $sanitizer = charger_fonction($extension, 'sanitizer', true)
351
-		) {
352
-			$sanitizer($fichier);
353
-		}
354
-	} else {
355
-		// enlever le timestamp eventuel
356
-		if (strpos($source, '?') !== false) {
357
-			$source = preg_replace(',[?][0-9]+$,', '', $source);
358
-		}
359
-		if (
360
-			strpos($source, '?') !== false
361
-			and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
362
-			and file_exists($f = preg_replace(',[?].*$,', '', $source))
363
-		) {
364
-			$source = $f;
365
-		}
366
-		$fichier = $source;
367
-	}
368
-
369
-	$terminaison_dest = '';
370
-	if ($terminaison = _image_trouver_extension($fichier)) {
371
-		$terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
372
-	}
373
-
374
-	if (
375
-		$forcer_format !== false
376
-		// 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
377
-		and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format, _image_extensions_acceptees_en_sortie()))
378
-	) {
379
-		$terminaison_dest = $forcer_format;
380
-	}
381
-
382
-	if (!$terminaison_dest) {
383
-		return false;
384
-	}
385
-
386
-	$nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
387
-	$fichier_dest = $nom_fichier;
388
-	if (
389
-		($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
390
-		or @file_exists($f = $fichier)
391
-	) {
392
-		// on passe la balise img a taille image qui exraira les attributs si possible
393
-		// au lieu de faire un acces disque sur le fichier
394
-		[$ret['hauteur'], $ret['largeur']] = taille_image($find_in_path ? $f : $img);
395
-		$date_src = @filemtime($f);
396
-	} elseif (
397
-		@file_exists($f = "$fichier.src")
398
-		and lire_fichier($f, $valeurs)
399
-		and $valeurs = unserialize($valeurs)
400
-		and isset($valeurs['hauteur_dest'])
401
-		and isset($valeurs['largeur_dest'])
402
-	) {
403
-		$ret['hauteur'] = $valeurs['hauteur_dest'];
404
-		$ret['largeur'] = $valeurs['largeur_dest'];
405
-		$date_src = $valeurs['date'];
406
-	} // pas de fichier source par la
407
-	else {
408
-		return false;
409
-	}
410
-
411
-	// pas de taille mesurable
412
-	if (!($ret['hauteur'] or $ret['largeur'])) {
413
-		return false;
414
-	}
415
-
416
-	// les images calculees dependent du chemin du fichier source
417
-	// 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
418
-	// ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
419
-	// qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
420
-	// la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
421
-	// alors que ca concerne peu de site au final
422
-	// la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
423
-	$identifiant = $fichier;
424
-
425
-	// cas general :
426
-	// on a un dossier cache commun et un nom de fichier qui varie avec l'effet
427
-	// cas particulier de reduire :
428
-	// un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
429
-	$cache = 'cache-gd2';
430
-	if (substr($effet, 0, 7) == 'reduire') {
431
-		[, $maxWidth, $maxHeight] = explode('-', $effet);
432
-		[$destWidth, $destHeight] = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
433
-		$ret['largeur_dest'] = $destWidth;
434
-		$ret['hauteur_dest'] = $destHeight;
435
-		$effet = "L{$destWidth}xH$destHeight";
436
-		$cache = 'cache-vignettes';
437
-		$fichier_dest = basename($fichier_dest);
438
-		if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
439
-			// on garde la terminaison initiale car image simplement copiee
440
-			// et on postfixe son nom avec un md5 du path
441
-			$terminaison_dest = $terminaison;
442
-			$fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
443
-		} else {
444
-			$fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
445
-		}
446
-		$cache = sous_repertoire(_DIR_VAR, $cache);
447
-		$cache = sous_repertoire($cache, $effet);
448
-	} else {
449
-		$fichier_dest = md5("$identifiant-$effet");
450
-		$cache = sous_repertoire(_DIR_VAR, $cache);
451
-		$cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
452
-		$fichier_dest = substr($fichier_dest, 2);
453
-	}
454
-
455
-	$fichier_dest = $cache . $fichier_dest . '.' . $terminaison_dest;
456
-
457
-	$GLOBALS['images_calculees'][] = $fichier_dest;
458
-
459
-	$creer = true;
460
-	// si recalcul des images demande, recalculer chaque image une fois
461
-	if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
462
-		$images_recalcul[$fichier_dest] = true;
463
-	} else {
464
-		if (@file_exists($f = $fichier_dest)) {
465
-			if (filemtime($f) >= $date_src) {
466
-				$creer = false;
467
-			}
468
-		} else {
469
-			if (
470
-				@file_exists($f = "$fichier_dest.src")
471
-				and lire_fichier($f, $valeurs)
472
-				and $valeurs = unserialize($valeurs)
473
-				and $valeurs['date'] >= $date_src
474
-			) {
475
-				$creer = false;
476
-			}
477
-		}
478
-	}
479
-	if ($creer) {
480
-		if (!@file_exists($fichier)) {
481
-			if (!@file_exists("$fichier.src")) {
482
-				spip_log("Image absente : $fichier");
483
-
484
-				return false;
485
-			}
486
-			# on reconstruit l'image source absente a partir de la chaine des .src
487
-			reconstruire_image_intermediaire($fichier);
488
-		}
489
-	}
490
-
491
-	if ($creer) {
492
-		spip_log(
493
-			'filtre image ' . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
494
-			'images' . _LOG_DEBUG
495
-		);
496
-	}
497
-
498
-	$term_fonction = _image_trouver_extension_pertinente($fichier);
499
-	$ret['fonction_imagecreatefrom'] = '_imagecreatefrom' . $term_fonction;
500
-	$ret['fichier'] = $fichier;
501
-	$ret['fonction_image'] = '_image_image' . $terminaison_dest;
502
-	$ret['fichier_dest'] = $fichier_dest;
503
-	$ret['format_source'] = _image_extension_normalisee($terminaison);
504
-	$ret['format_dest'] = $terminaison_dest;
505
-	$ret['date_src'] = $date_src;
506
-	$ret['creer'] = $creer;
507
-	$ret['class'] = extraire_attribut($img, 'class');
508
-	$ret['alt'] = extraire_attribut($img, 'alt');
509
-	$ret['style'] = extraire_attribut($img, 'style');
510
-	$ret['tag'] = $img;
511
-	if ($fonction_creation) {
512
-		$ret['reconstruction'] = $fonction_creation;
513
-		# ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement
514
-		# cas de image_reduire qui finalement ne reduit pas l'image source
515
-		# ca evite d'essayer de le creer au prochain hit si il n'est pas la
516
-		#ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
517
-	}
518
-
519
-	$ret = pipeline('image_preparer_filtre', [
520
-			'args' => [
521
-				'img' => $img,
522
-				'effet' => $effet,
523
-				'forcer_format' => $forcer_format,
524
-				'fonction_creation' => $fonction_creation,
525
-				'find_in_path' => $find_in_path,
526
-			],
527
-			'data' => $ret
528
-		]);
529
-
530
-	// une globale pour le debug en cas de crash memoire
531
-	$GLOBALS['derniere_image_calculee'] = $ret;
532
-
533
-	// traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
534
-	if ($term_fonction === 'svg') {
535
-		if ($creer and !$support_svg) {
536
-			process_image_svg_identite($ret);
537
-			$ret['creer'] = false;
538
-		}
539
-	}
540
-	else {
541
-		if (!function_exists($ret['fonction_imagecreatefrom'])) {
542
-			return false;
543
-		}
544
-	}
545
-
546
-	return $ret;
310
+    $ret = [];
311
+    $f = null;
312
+    static $images_recalcul = [];
313
+    if (strlen($img) == 0) {
314
+        return false;
315
+    }
316
+
317
+    $source = trim(extraire_attribut($img, 'src') ?? '');
318
+    if (strlen($source) < 1) {
319
+        $source = $img;
320
+        $img = "<img src='$source' />";
321
+    } elseif (
322
+        preg_match('@^data:image/([^;]*);base64,(.*)$@isS', $source, $regs)
323
+        and $extension = _image_trouver_extension_depuis_mime('image/' . $regs[1])
324
+        and in_array($extension, _image_extensions_acceptees_en_entree())
325
+    ) {
326
+        # gerer img src="data:....base64"
327
+        $local = sous_repertoire(_DIR_VAR, 'image-data') . md5($regs[2]) . '.' . _image_extension_normalisee($extension);
328
+        if (!file_exists($local)) {
329
+            ecrire_fichier($local, base64_decode($regs[2]));
330
+        }
331
+        if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
332
+            $sanitizer($local);
333
+        }
334
+        $source = $local;
335
+        $img = inserer_attribut($img, 'src', $source);
336
+        # eviter les mauvaises surprises lors de conversions de format
337
+        $img = inserer_attribut($img, 'width', '');
338
+        $img = inserer_attribut($img, 'height', '');
339
+    }
340
+
341
+    // les protocoles web prennent au moins 3 lettres
342
+    if (tester_url_absolue($source)) {
343
+        include_spip('inc/distant');
344
+        $fichier = _DIR_RACINE . copie_locale($source);
345
+        if (!$fichier) {
346
+            return '';
347
+        }
348
+        if (
349
+            $extension = _image_trouver_extension($fichier)
350
+            and $sanitizer = charger_fonction($extension, 'sanitizer', true)
351
+        ) {
352
+            $sanitizer($fichier);
353
+        }
354
+    } else {
355
+        // enlever le timestamp eventuel
356
+        if (strpos($source, '?') !== false) {
357
+            $source = preg_replace(',[?][0-9]+$,', '', $source);
358
+        }
359
+        if (
360
+            strpos($source, '?') !== false
361
+            and strncmp($source, _DIR_IMG, strlen(_DIR_IMG)) == 0
362
+            and file_exists($f = preg_replace(',[?].*$,', '', $source))
363
+        ) {
364
+            $source = $f;
365
+        }
366
+        $fichier = $source;
367
+    }
368
+
369
+    $terminaison_dest = '';
370
+    if ($terminaison = _image_trouver_extension($fichier)) {
371
+        $terminaison_dest = ($terminaison == 'gif') ? 'png' : $terminaison;
372
+    }
373
+
374
+    if (
375
+        $forcer_format !== false
376
+        // 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
377
+        and ($terminaison_dest !== 'svg' or $support_svg or !in_array($forcer_format, _image_extensions_acceptees_en_sortie()))
378
+    ) {
379
+        $terminaison_dest = $forcer_format;
380
+    }
381
+
382
+    if (!$terminaison_dest) {
383
+        return false;
384
+    }
385
+
386
+    $nom_fichier = substr($fichier, 0, strlen($fichier) - (strlen($terminaison) + 1));
387
+    $fichier_dest = $nom_fichier;
388
+    if (
389
+        ($find_in_path and $f = find_in_path($fichier) and $fichier = $f)
390
+        or @file_exists($f = $fichier)
391
+    ) {
392
+        // on passe la balise img a taille image qui exraira les attributs si possible
393
+        // au lieu de faire un acces disque sur le fichier
394
+        [$ret['hauteur'], $ret['largeur']] = taille_image($find_in_path ? $f : $img);
395
+        $date_src = @filemtime($f);
396
+    } elseif (
397
+        @file_exists($f = "$fichier.src")
398
+        and lire_fichier($f, $valeurs)
399
+        and $valeurs = unserialize($valeurs)
400
+        and isset($valeurs['hauteur_dest'])
401
+        and isset($valeurs['largeur_dest'])
402
+    ) {
403
+        $ret['hauteur'] = $valeurs['hauteur_dest'];
404
+        $ret['largeur'] = $valeurs['largeur_dest'];
405
+        $date_src = $valeurs['date'];
406
+    } // pas de fichier source par la
407
+    else {
408
+        return false;
409
+    }
410
+
411
+    // pas de taille mesurable
412
+    if (!($ret['hauteur'] or $ret['largeur'])) {
413
+        return false;
414
+    }
415
+
416
+    // les images calculees dependent du chemin du fichier source
417
+    // 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
418
+    // ce n'est pas totalement optimal en terme de stockage, mais chaque image est associee a un fichier .src
419
+    // qui contient la methode de reconstrucion (le filtre + les arguments d'appel) et les arguments different entre prive et public
420
+    // la mise en commun du fichier image cree donc un bug et des problemes qui necessiteraient beaucoup de complexite de code
421
+    // alors que ca concerne peu de site au final
422
+    // la release de r23632+r23633+r23634 a provoque peu de remontee de bug attestant du peu de sites impactes
423
+    $identifiant = $fichier;
424
+
425
+    // cas general :
426
+    // on a un dossier cache commun et un nom de fichier qui varie avec l'effet
427
+    // cas particulier de reduire :
428
+    // un cache par dimension, et le nom de fichier est conserve, suffixe par la dimension aussi
429
+    $cache = 'cache-gd2';
430
+    if (substr($effet, 0, 7) == 'reduire') {
431
+        [, $maxWidth, $maxHeight] = explode('-', $effet);
432
+        [$destWidth, $destHeight] = _image_ratio($ret['largeur'], $ret['hauteur'], $maxWidth, $maxHeight);
433
+        $ret['largeur_dest'] = $destWidth;
434
+        $ret['hauteur_dest'] = $destHeight;
435
+        $effet = "L{$destWidth}xH$destHeight";
436
+        $cache = 'cache-vignettes';
437
+        $fichier_dest = basename($fichier_dest);
438
+        if (($ret['largeur'] <= $maxWidth) && ($ret['hauteur'] <= $maxHeight)) {
439
+            // on garde la terminaison initiale car image simplement copiee
440
+            // et on postfixe son nom avec un md5 du path
441
+            $terminaison_dest = $terminaison;
442
+            $fichier_dest .= '-' . substr(md5("$identifiant"), 0, 5);
443
+        } else {
444
+            $fichier_dest .= '-' . substr(md5("$identifiant-$effet"), 0, 5);
445
+        }
446
+        $cache = sous_repertoire(_DIR_VAR, $cache);
447
+        $cache = sous_repertoire($cache, $effet);
448
+    } else {
449
+        $fichier_dest = md5("$identifiant-$effet");
450
+        $cache = sous_repertoire(_DIR_VAR, $cache);
451
+        $cache = sous_repertoire($cache, substr($fichier_dest, 0, 2));
452
+        $fichier_dest = substr($fichier_dest, 2);
453
+    }
454
+
455
+    $fichier_dest = $cache . $fichier_dest . '.' . $terminaison_dest;
456
+
457
+    $GLOBALS['images_calculees'][] = $fichier_dest;
458
+
459
+    $creer = true;
460
+    // si recalcul des images demande, recalculer chaque image une fois
461
+    if (defined('_VAR_IMAGES') and _VAR_IMAGES and !isset($images_recalcul[$fichier_dest])) {
462
+        $images_recalcul[$fichier_dest] = true;
463
+    } else {
464
+        if (@file_exists($f = $fichier_dest)) {
465
+            if (filemtime($f) >= $date_src) {
466
+                $creer = false;
467
+            }
468
+        } else {
469
+            if (
470
+                @file_exists($f = "$fichier_dest.src")
471
+                and lire_fichier($f, $valeurs)
472
+                and $valeurs = unserialize($valeurs)
473
+                and $valeurs['date'] >= $date_src
474
+            ) {
475
+                $creer = false;
476
+            }
477
+        }
478
+    }
479
+    if ($creer) {
480
+        if (!@file_exists($fichier)) {
481
+            if (!@file_exists("$fichier.src")) {
482
+                spip_log("Image absente : $fichier");
483
+
484
+                return false;
485
+            }
486
+            # on reconstruit l'image source absente a partir de la chaine des .src
487
+            reconstruire_image_intermediaire($fichier);
488
+        }
489
+    }
490
+
491
+    if ($creer) {
492
+        spip_log(
493
+            'filtre image ' . ($fonction_creation ? reset($fonction_creation) : '') . "[$effet] sur $fichier",
494
+            'images' . _LOG_DEBUG
495
+        );
496
+    }
497
+
498
+    $term_fonction = _image_trouver_extension_pertinente($fichier);
499
+    $ret['fonction_imagecreatefrom'] = '_imagecreatefrom' . $term_fonction;
500
+    $ret['fichier'] = $fichier;
501
+    $ret['fonction_image'] = '_image_image' . $terminaison_dest;
502
+    $ret['fichier_dest'] = $fichier_dest;
503
+    $ret['format_source'] = _image_extension_normalisee($terminaison);
504
+    $ret['format_dest'] = $terminaison_dest;
505
+    $ret['date_src'] = $date_src;
506
+    $ret['creer'] = $creer;
507
+    $ret['class'] = extraire_attribut($img, 'class');
508
+    $ret['alt'] = extraire_attribut($img, 'alt');
509
+    $ret['style'] = extraire_attribut($img, 'style');
510
+    $ret['tag'] = $img;
511
+    if ($fonction_creation) {
512
+        $ret['reconstruction'] = $fonction_creation;
513
+        # ecrire ici comment creer le fichier, car il est pas sur qu'on l'ecrira reelement
514
+        # cas de image_reduire qui finalement ne reduit pas l'image source
515
+        # ca evite d'essayer de le creer au prochain hit si il n'est pas la
516
+        #ecrire_fichier($ret['fichier_dest'].'.src',serialize($ret),true);
517
+    }
518
+
519
+    $ret = pipeline('image_preparer_filtre', [
520
+            'args' => [
521
+                'img' => $img,
522
+                'effet' => $effet,
523
+                'forcer_format' => $forcer_format,
524
+                'fonction_creation' => $fonction_creation,
525
+                'find_in_path' => $find_in_path,
526
+            ],
527
+            'data' => $ret
528
+        ]);
529
+
530
+    // une globale pour le debug en cas de crash memoire
531
+    $GLOBALS['derniere_image_calculee'] = $ret;
532
+
533
+    // traiter le cas particulier des SVG : si le filtre n'a pas annonce explicitement qu'il savait faire, on delegue
534
+    if ($term_fonction === 'svg') {
535
+        if ($creer and !$support_svg) {
536
+            process_image_svg_identite($ret);
537
+            $ret['creer'] = false;
538
+        }
539
+    }
540
+    else {
541
+        if (!function_exists($ret['fonction_imagecreatefrom'])) {
542
+            return false;
543
+        }
544
+    }
545
+
546
+    return $ret;
547 547
 }
548 548
 
549 549
 
@@ -552,53 +552,53 @@  discard block
 block discarded – undo
552 552
  * @return array
553 553
  */
554 554
 function _image_extensions_acceptees_en_entree() {
555
-	static $extensions = null;
556
-	if (empty($extensions)) {
557
-		$extensions = ['png', 'gif', 'jpg', 'jpeg'];
558
-		if (!empty($GLOBALS['meta']['gd_formats'])) {
559
-			// action=tester renseigne gd_formats et detecte le support de webp
560
-			$extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
561
-			$extensions = array_map('trim', $extensions);
562
-			$extensions = array_filter($extensions);
563
-			$extensions = array_unique($extensions);
564
-			if (in_array('jpg', $extensions)) { $extensions[] = 'jpeg';
565
-			}
566
-		}
567
-		$extensions[] = 'svg'; // on le supporte toujours avec des fonctions specifiques
568
-	}
569
-
570
-	return $extensions;
555
+    static $extensions = null;
556
+    if (empty($extensions)) {
557
+        $extensions = ['png', 'gif', 'jpg', 'jpeg'];
558
+        if (!empty($GLOBALS['meta']['gd_formats'])) {
559
+            // action=tester renseigne gd_formats et detecte le support de webp
560
+            $extensions = array_merge(explode(',', $GLOBALS['meta']['gd_formats']));
561
+            $extensions = array_map('trim', $extensions);
562
+            $extensions = array_filter($extensions);
563
+            $extensions = array_unique($extensions);
564
+            if (in_array('jpg', $extensions)) { $extensions[] = 'jpeg';
565
+            }
566
+        }
567
+        $extensions[] = 'svg'; // on le supporte toujours avec des fonctions specifiques
568
+    }
569
+
570
+    return $extensions;
571 571
 }
572 572
 
573 573
 /**
574 574
  * @return array|string[]|null
575 575
  */
576 576
 function _image_extensions_acceptees_en_sortie() {
577
-	static $extensions = null;
578
-	if (empty($extensions)) {
579
-		$extensions = _image_extensions_acceptees_en_entree();
580
-		$extensions = array_diff($extensions, ['jpeg']);
581
-		if (in_array('gif', $extensions) and !function_exists('imagegif')) {
582
-			$extensions = array_diff($extensions, ['gif']);
583
-		}
584
-		if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
585
-			$extensions = array_diff($extensions, ['webp']);
586
-		}
587
-	}
588
-
589
-	return $extensions;
577
+    static $extensions = null;
578
+    if (empty($extensions)) {
579
+        $extensions = _image_extensions_acceptees_en_entree();
580
+        $extensions = array_diff($extensions, ['jpeg']);
581
+        if (in_array('gif', $extensions) and !function_exists('imagegif')) {
582
+            $extensions = array_diff($extensions, ['gif']);
583
+        }
584
+        if (in_array('webp', $extensions) and !function_exists('imagewebp')) {
585
+            $extensions = array_diff($extensions, ['webp']);
586
+        }
587
+    }
588
+
589
+    return $extensions;
590 590
 }
591 591
 
592 592
 function _image_extension_normalisee($extension) {
593
-	$extension = strtolower($extension);
594
-	if ($extension === 'jpeg') {
595
-		$extension = 'jpg';
596
-	}
597
-	return $extension;
593
+    $extension = strtolower($extension);
594
+    if ($extension === 'jpeg') {
595
+        $extension = 'jpg';
596
+    }
597
+    return $extension;
598 598
 }
599 599
 
600 600
 function _image_extensions_conservent_transparence() {
601
-	return ['png', 'webp'];
601
+    return ['png', 'webp'];
602 602
 }
603 603
 
604 604
 
@@ -608,12 +608,12 @@  discard block
 block discarded – undo
608 608
  * @return string
609 609
  */
610 610
 function _image_trouver_extension($path) {
611
-	$preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
612
-	if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
613
-		$terminaison = strtolower($regs[1]);
614
-		return $terminaison;
615
-	}
616
-	return '';
611
+    $preg_extensions = implode('|', _image_extensions_acceptees_en_entree());
612
+    if (preg_match(",\.($preg_extensions)($|[?]),i", $path, $regs)) {
613
+        $terminaison = strtolower($regs[1]);
614
+        return $terminaison;
615
+    }
616
+    return '';
617 617
 }
618 618
 
619 619
 /**
@@ -624,33 +624,33 @@  discard block
 block discarded – undo
624 624
  * @return string Extension, dans le format attendu par les fonctions 'gd' ('jpeg' pour les .jpg par exemple)
625 625
  */
626 626
 function _image_trouver_extension_pertinente($path) {
627
-	$path = supprimer_timestamp($path);
628
-	$terminaison = _image_trouver_extension($path);
629
-	if ($terminaison == 'jpg') {
630
-		$terminaison = 'jpeg';
631
-	}
632
-
633
-	if (!file_exists($path)) {
634
-		return $terminaison;
635
-	}
636
-
637
-	if (!$info = @spip_getimagesize($path)) {
638
-		return $terminaison;
639
-	}
640
-
641
-	if (isset($info['mime'])) {
642
-		$mime = $info['mime'];
643
-	}
644
-	else {
645
-		$mime = image_type_to_mime_type($info[2]);
646
-	}
647
-
648
-	$_terminaison = _image_trouver_extension_depuis_mime($mime);
649
-	if ($_terminaison and $_terminaison !== $terminaison) {
650
-		spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", 'images.' . _LOG_INFO_IMPORTANTE);
651
-		$terminaison = $_terminaison;
652
-	}
653
-	return $terminaison;
627
+    $path = supprimer_timestamp($path);
628
+    $terminaison = _image_trouver_extension($path);
629
+    if ($terminaison == 'jpg') {
630
+        $terminaison = 'jpeg';
631
+    }
632
+
633
+    if (!file_exists($path)) {
634
+        return $terminaison;
635
+    }
636
+
637
+    if (!$info = @spip_getimagesize($path)) {
638
+        return $terminaison;
639
+    }
640
+
641
+    if (isset($info['mime'])) {
642
+        $mime = $info['mime'];
643
+    }
644
+    else {
645
+        $mime = image_type_to_mime_type($info[2]);
646
+    }
647
+
648
+    $_terminaison = _image_trouver_extension_depuis_mime($mime);
649
+    if ($_terminaison and $_terminaison !== $terminaison) {
650
+        spip_log("Mauvaise extension du fichier : $path . Son type mime est : $mime", 'images.' . _LOG_INFO_IMPORTANTE);
651
+        $terminaison = $_terminaison;
652
+    }
653
+    return $terminaison;
654 654
 }
655 655
 
656 656
 /**
@@ -658,36 +658,36 @@  discard block
 block discarded – undo
658 658
  * @return string
659 659
  */
660 660
 function _image_trouver_extension_depuis_mime($mime) {
661
-	switch (strtolower($mime)) {
662
-		case 'image/png':
663
-		case 'image/x-png':
664
-			$terminaison = 'png';
665
-			break;
666
-
667
-		case 'image/jpg':
668
-		case 'image/jpeg':
669
-		case 'image/pjpeg':
670
-			$terminaison = 'jpeg';
671
-			break;
672
-
673
-		case 'image/gif':
674
-			$terminaison = 'gif';
675
-			break;
676
-
677
-		case 'image/webp':
678
-		case 'image/x-webp':
679
-			$terminaison = 'webp';
680
-			break;
681
-
682
-		case 'image/svg+xml':
683
-			$terminaison = 'svg';
684
-			break;
685
-
686
-		default:
687
-			$terminaison = '';
688
-	}
689
-
690
-	return $terminaison;
661
+    switch (strtolower($mime)) {
662
+        case 'image/png':
663
+        case 'image/x-png':
664
+            $terminaison = 'png';
665
+            break;
666
+
667
+        case 'image/jpg':
668
+        case 'image/jpeg':
669
+        case 'image/pjpeg':
670
+            $terminaison = 'jpeg';
671
+            break;
672
+
673
+        case 'image/gif':
674
+            $terminaison = 'gif';
675
+            break;
676
+
677
+        case 'image/webp':
678
+        case 'image/x-webp':
679
+            $terminaison = 'webp';
680
+            break;
681
+
682
+        case 'image/svg+xml':
683
+            $terminaison = 'svg';
684
+            break;
685
+
686
+        default:
687
+            $terminaison = '';
688
+    }
689
+
690
+    return $terminaison;
691 691
 }
692 692
 
693 693
 
@@ -707,18 +707,18 @@  discard block
 block discarded – undo
707 707
  *     Une ressource de type Image GD.
708 708
  */
709 709
 function _imagecreatefrom_func(string $func, string $filename) {
710
-	if (!function_exists($func)) {
711
-		spip_log("GD indisponible : $func inexistante. Traitement $filename impossible.", _LOG_CRITIQUE);
712
-		erreur_squelette("GD indisponible : $func inexistante. Traitement $filename impossible.");
713
-		return null;
714
-	}
715
-	$img = @$func($filename);
716
-	if (!$img) {
717
-		spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
718
-		erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
719
-		$img = imagecreate(10, 10);
720
-	}
721
-	return $img;
710
+    if (!function_exists($func)) {
711
+        spip_log("GD indisponible : $func inexistante. Traitement $filename impossible.", _LOG_CRITIQUE);
712
+        erreur_squelette("GD indisponible : $func inexistante. Traitement $filename impossible.");
713
+        return null;
714
+    }
715
+    $img = @$func($filename);
716
+    if (!$img) {
717
+        spip_log("Erreur lecture imagecreatefromjpeg $filename", _LOG_CRITIQUE);
718
+        erreur_squelette("Erreur lecture imagecreatefromjpeg $filename");
719
+        $img = imagecreate(10, 10);
720
+    }
721
+    return $img;
722 722
 }
723 723
 
724 724
 /**
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
  *     Une ressource de type Image GD.
735 735
  */
736 736
 function _imagecreatefromjpeg($filename) {
737
-	return _imagecreatefrom_func('imagecreatefromjpeg', $filename);
737
+    return _imagecreatefrom_func('imagecreatefromjpeg', $filename);
738 738
 }
739 739
 
740 740
 /**
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
  *     Une ressource de type Image GD.
751 751
  */
752 752
 function _imagecreatefrompng($filename) {
753
-	return _imagecreatefrom_func('imagecreatefrompng', $filename);
753
+    return _imagecreatefrom_func('imagecreatefrompng', $filename);
754 754
 }
755 755
 
756 756
 /**
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
  *     Une ressource de type Image GD.
767 767
  */
768 768
 function _imagecreatefromgif($filename) {
769
-	return _imagecreatefrom_func('imagecreatefromgif', $filename);
769
+    return _imagecreatefrom_func('imagecreatefromgif', $filename);
770 770
 }
771 771
 
772 772
 
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
  *     Une ressource de type Image GD.
784 784
  */
785 785
 function _imagecreatefromwebp($filename) {
786
-	return _imagecreatefrom_func('imagecreatefromwebp', $filename);
786
+    return _imagecreatefrom_func('imagecreatefromwebp', $filename);
787 787
 }
788 788
 
789 789
 /**
@@ -801,24 +801,24 @@  discard block
 block discarded – undo
801 801
  *     - true si une image est bien retournée.
802 802
  */
803 803
 function _image_imagepng($img, $fichier) {
804
-	if (!function_exists('imagepng')) {
805
-		return false;
806
-	}
807
-	$tmp = $fichier . '.tmp';
808
-	$ret = imagepng($img, $tmp);
809
-	if (file_exists($tmp)) {
810
-		$taille_test = getimagesize($tmp);
811
-		if ($taille_test[0] < 1) {
812
-			return false;
813
-		}
814
-
815
-		spip_unlink($fichier); // le fichier peut deja exister
816
-		@rename($tmp, $fichier);
817
-
818
-		return $ret;
819
-	}
820
-
821
-	return false;
804
+    if (!function_exists('imagepng')) {
805
+        return false;
806
+    }
807
+    $tmp = $fichier . '.tmp';
808
+    $ret = imagepng($img, $tmp);
809
+    if (file_exists($tmp)) {
810
+        $taille_test = getimagesize($tmp);
811
+        if ($taille_test[0] < 1) {
812
+            return false;
813
+        }
814
+
815
+        spip_unlink($fichier); // le fichier peut deja exister
816
+        @rename($tmp, $fichier);
817
+
818
+        return $ret;
819
+    }
820
+
821
+    return false;
822 822
 }
823 823
 
824 824
 /**
@@ -836,24 +836,24 @@  discard block
 block discarded – undo
836 836
  *     - true si une image est bien retournée.
837 837
  */
838 838
 function _image_imagegif($img, $fichier) {
839
-	if (!function_exists('imagegif')) {
840
-		return false;
841
-	}
842
-	$tmp = $fichier . '.tmp';
843
-	$ret = imagegif($img, $tmp);
844
-	if (file_exists($tmp)) {
845
-		$taille_test = getimagesize($tmp);
846
-		if ($taille_test[0] < 1) {
847
-			return false;
848
-		}
849
-
850
-		spip_unlink($fichier); // le fichier peut deja exister
851
-		@rename($tmp, $fichier);
852
-
853
-		return $ret;
854
-	}
855
-
856
-	return false;
839
+    if (!function_exists('imagegif')) {
840
+        return false;
841
+    }
842
+    $tmp = $fichier . '.tmp';
843
+    $ret = imagegif($img, $tmp);
844
+    if (file_exists($tmp)) {
845
+        $taille_test = getimagesize($tmp);
846
+        if ($taille_test[0] < 1) {
847
+            return false;
848
+        }
849
+
850
+        spip_unlink($fichier); // le fichier peut deja exister
851
+        @rename($tmp, $fichier);
852
+
853
+        return $ret;
854
+    }
855
+
856
+    return false;
857 857
 }
858 858
 
859 859
 /**
@@ -876,29 +876,29 @@  discard block
 block discarded – undo
876 876
  *     - true si une image est bien retournée.
877 877
  */
878 878
 function _image_imagejpg($img, $fichier, $qualite = _IMG_GD_QUALITE) {
879
-	if (!function_exists('imagejpeg')) {
880
-		return false;
881
-	}
882
-	$tmp = $fichier . '.tmp';
879
+    if (!function_exists('imagejpeg')) {
880
+        return false;
881
+    }
882
+    $tmp = $fichier . '.tmp';
883 883
 
884
-	// Enable interlancing
885
-	imageinterlace($img, true);
884
+    // Enable interlancing
885
+    imageinterlace($img, true);
886 886
 
887
-	$ret = imagejpeg($img, $tmp, $qualite);
887
+    $ret = imagejpeg($img, $tmp, $qualite);
888 888
 
889
-	if (file_exists($tmp)) {
890
-		$taille_test = getimagesize($tmp);
891
-		if ($taille_test[0] < 1) {
892
-			return false;
893
-		}
889
+    if (file_exists($tmp)) {
890
+        $taille_test = getimagesize($tmp);
891
+        if ($taille_test[0] < 1) {
892
+            return false;
893
+        }
894 894
 
895
-		spip_unlink($fichier); // le fichier peut deja exister
896
-		@rename($tmp, $fichier);
895
+        spip_unlink($fichier); // le fichier peut deja exister
896
+        @rename($tmp, $fichier);
897 897
 
898
-		return $ret;
899
-	}
898
+        return $ret;
899
+    }
900 900
 
901
-	return false;
901
+    return false;
902 902
 }
903 903
 
904 904
 /**
@@ -916,9 +916,9 @@  discard block
 block discarded – undo
916 916
  *     true si le fichier a bien été créé ; false sinon.
917 917
  */
918 918
 function _image_imageico($img, $fichier) {
919
-	$gd_image_array = [$img];
919
+    $gd_image_array = [$img];
920 920
 
921
-	return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
921
+    return ecrire_fichier($fichier, phpthumb_functions::GD2ICOstring($gd_image_array));
922 922
 }
923 923
 
924 924
 
@@ -937,24 +937,24 @@  discard block
 block discarded – undo
937 937
  *     - true si une image est bien retournée.
938 938
  */
939 939
 function _image_imagewebp($img, $fichier, $qualite = _IMG_GD_QUALITE) {
940
-	if (!function_exists('imagewebp')) {
941
-		return false;
942
-	}
943
-	$tmp = $fichier . '.tmp';
944
-	$ret = imagewebp($img, $tmp, $qualite);
945
-	if (file_exists($tmp)) {
946
-		$taille_test = getimagesize($tmp);
947
-		if ($taille_test[0] < 1) {
948
-			return false;
949
-		}
950
-
951
-		spip_unlink($fichier); // le fichier peut deja exister
952
-		@rename($tmp, $fichier);
953
-
954
-		return $ret;
955
-	}
956
-
957
-	return false;
940
+    if (!function_exists('imagewebp')) {
941
+        return false;
942
+    }
943
+    $tmp = $fichier . '.tmp';
944
+    $ret = imagewebp($img, $tmp, $qualite);
945
+    if (file_exists($tmp)) {
946
+        $taille_test = getimagesize($tmp);
947
+        if ($taille_test[0] < 1) {
948
+            return false;
949
+        }
950
+
951
+        spip_unlink($fichier); // le fichier peut deja exister
952
+        @rename($tmp, $fichier);
953
+
954
+        return $ret;
955
+    }
956
+
957
+    return false;
958 958
 }
959 959
 
960 960
 /**
@@ -974,35 +974,35 @@  discard block
 block discarded – undo
974 974
  */
975 975
 function _image_imagesvg($img, $fichier) {
976 976
 
977
-	$tmp = $fichier . '.tmp';
978
-	if (strpos($img, '<') === false) {
979
-		$img = supprimer_timestamp($img);
980
-		if (!file_exists($img)) {
981
-			return false;
982
-		}
983
-		@copy($img, $tmp);
984
-		if (filesize($tmp) == filesize($img)) {
985
-			spip_unlink($fichier); // le fichier peut deja exister
986
-			@rename($tmp, $fichier);
987
-			return true;
988
-		}
989
-		return false;
990
-	}
991
-
992
-	file_put_contents($tmp, $img);
993
-	if (file_exists($tmp)) {
994
-		$taille_test = spip_getimagesize($tmp);
995
-		if ($taille_test[0] < 1) {
996
-			return false;
997
-		}
998
-
999
-		spip_unlink($fichier); // le fichier peut deja exister
1000
-		@rename($tmp, $fichier);
1001
-
1002
-		return true;
1003
-	}
1004
-
1005
-	return false;
977
+    $tmp = $fichier . '.tmp';
978
+    if (strpos($img, '<') === false) {
979
+        $img = supprimer_timestamp($img);
980
+        if (!file_exists($img)) {
981
+            return false;
982
+        }
983
+        @copy($img, $tmp);
984
+        if (filesize($tmp) == filesize($img)) {
985
+            spip_unlink($fichier); // le fichier peut deja exister
986
+            @rename($tmp, $fichier);
987
+            return true;
988
+        }
989
+        return false;
990
+    }
991
+
992
+    file_put_contents($tmp, $img);
993
+    if (file_exists($tmp)) {
994
+        $taille_test = spip_getimagesize($tmp);
995
+        if ($taille_test[0] < 1) {
996
+            return false;
997
+        }
998
+
999
+        spip_unlink($fichier); // le fichier peut deja exister
1000
+        @rename($tmp, $fichier);
1001
+
1002
+        return true;
1003
+    }
1004
+
1005
+    return false;
1006 1006
 }
1007 1007
 
1008 1008
 
@@ -1030,29 +1030,29 @@  discard block
 block discarded – undo
1030 1030
  *     - false sinon.
1031 1031
  */
1032 1032
 function _image_gd_output($img, $valeurs, $qualite = _IMG_GD_QUALITE, $fonction = null) {
1033
-	if (is_null($fonction)) {
1034
-		$fonction = '_image_image' . $valeurs['format_dest'];
1035
-	}
1036
-	$ret = false;
1037
-	#un flag pour reperer les images gravees
1038
-	$lock =
1039
-		!statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
1040
-	or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'));
1041
-	if (
1042
-		function_exists($fonction)
1043
-		&& ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
1044
-		&& isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
1045
-		&& !$lock
1046
-	) {
1047
-		if (@file_exists($valeurs['fichier_dest'])) {
1048
-			// dans tous les cas mettre a jour la taille de l'image finale
1049
-			[$valeurs['hauteur_dest'], $valeurs['largeur_dest']] = taille_image($valeurs['fichier_dest']);
1050
-			$valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
1051
-			ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
1052
-		}
1053
-	}
1054
-
1055
-	return $ret;
1033
+    if (is_null($fonction)) {
1034
+        $fonction = '_image_image' . $valeurs['format_dest'];
1035
+    }
1036
+    $ret = false;
1037
+    #un flag pour reperer les images gravees
1038
+    $lock =
1039
+        !statut_effacer_images_temporaires('get') // si la fonction n'a pas ete activee, on grave tout
1040
+    or (@file_exists($valeurs['fichier_dest']) and !@file_exists($valeurs['fichier_dest'] . '.src'));
1041
+    if (
1042
+        function_exists($fonction)
1043
+        && ($ret = $fonction($img, $valeurs['fichier_dest'], $qualite)) # on a reussi a creer l'image
1044
+        && isset($valeurs['reconstruction']) # et on sait comment la resonctruire le cas echeant
1045
+        && !$lock
1046
+    ) {
1047
+        if (@file_exists($valeurs['fichier_dest'])) {
1048
+            // dans tous les cas mettre a jour la taille de l'image finale
1049
+            [$valeurs['hauteur_dest'], $valeurs['largeur_dest']] = taille_image($valeurs['fichier_dest']);
1050
+            $valeurs['date'] = @filemtime($valeurs['fichier_dest']); // pour la retrouver apres disparition
1051
+            ecrire_fichier($valeurs['fichier_dest'] . '.src', serialize($valeurs), true);
1052
+        }
1053
+    }
1054
+
1055
+    return $ret;
1056 1056
 }
1057 1057
 
1058 1058
 /**
@@ -1065,27 +1065,27 @@  discard block
 block discarded – undo
1065 1065
  *     Chemin vers le fichier manquant
1066 1066
  **/
1067 1067
 function reconstruire_image_intermediaire($fichier_manquant) {
1068
-	$reconstruire = [];
1069
-	$fichier = $fichier_manquant;
1070
-	while (
1071
-		strpos($fichier, '://') === false
1072
-		and !@file_exists($fichier)
1073
-		and lire_fichier($src = "$fichier.src", $source)
1074
-		and $valeurs = unserialize($source)
1075
-		and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1076
-	) {
1077
-		spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
1078
-		$reconstruire[] = $valeurs['reconstruction'];
1079
-	}
1080
-	while (count($reconstruire)) {
1081
-		$r = array_pop($reconstruire);
1082
-		$fonction = $r[0];
1083
-		$args = $r[1];
1084
-		call_user_func_array($fonction, $args);
1085
-	}
1086
-	// cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
1087
-	// mais l'on peut nettoyer les miettes de sa creation
1088
-	ramasse_miettes($fichier_manquant);
1068
+    $reconstruire = [];
1069
+    $fichier = $fichier_manquant;
1070
+    while (
1071
+        strpos($fichier, '://') === false
1072
+        and !@file_exists($fichier)
1073
+        and lire_fichier($src = "$fichier.src", $source)
1074
+        and $valeurs = unserialize($source)
1075
+        and ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1076
+    ) {
1077
+        spip_unlink($src); // si jamais on a un timeout pendant la reconstruction, elle se fera naturellement au hit suivant
1078
+        $reconstruire[] = $valeurs['reconstruction'];
1079
+    }
1080
+    while (count($reconstruire)) {
1081
+        $r = array_pop($reconstruire);
1082
+        $fonction = $r[0];
1083
+        $args = $r[1];
1084
+        call_user_func_array($fonction, $args);
1085
+    }
1086
+    // cette image intermediaire est commune a plusieurs series de filtre, il faut la conserver
1087
+    // mais l'on peut nettoyer les miettes de sa creation
1088
+    ramasse_miettes($fichier_manquant);
1089 1089
 }
1090 1090
 
1091 1091
 /**
@@ -1105,28 +1105,28 @@  discard block
 block discarded – undo
1105 1105
  *     Chemin du fichier d'image calculé
1106 1106
  **/
1107 1107
 function ramasse_miettes($fichier) {
1108
-	if (
1109
-		strpos($fichier, '://') !== false
1110
-		or !lire_fichier($src = "$fichier.src", $source)
1111
-		or !$valeurs = unserialize($source)
1112
-	) {
1113
-		return;
1114
-	}
1115
-	spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
1116
-	while (
1117
-		($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1118
-		and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
1119
-		and (lire_fichier(
1120
-			$src = "$fichier.src",
1121
-			$source
1122
-		)) # le fichier a une source connue (c'est donc une image calculee intermediaire)
1123
-		and ($valeurs = unserialize($source))  # et valide
1124
-	) {
1125
-		# on efface le fichier
1126
-		spip_unlink($fichier);
1127
-		# mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
1128
-		#spip_unlink($src);
1129
-	}
1108
+    if (
1109
+        strpos($fichier, '://') !== false
1110
+        or !lire_fichier($src = "$fichier.src", $source)
1111
+        or !$valeurs = unserialize($source)
1112
+    ) {
1113
+        return;
1114
+    }
1115
+    spip_unlink($src); # on supprime la reference a sa source pour marquer cette image comme non intermediaire
1116
+    while (
1117
+        ($fichier = $valeurs['fichier']) # l'origine est connue (on ne verifie pas son existence, qu'importe ...)
1118
+        and (substr($fichier, 0, strlen(_DIR_VAR)) == _DIR_VAR) # et est dans local
1119
+        and (lire_fichier(
1120
+            $src = "$fichier.src",
1121
+            $source
1122
+        )) # le fichier a une source connue (c'est donc une image calculee intermediaire)
1123
+        and ($valeurs = unserialize($source))  # et valide
1124
+    ) {
1125
+        # on efface le fichier
1126
+        spip_unlink($fichier);
1127
+        # mais laisse le .src qui permet de savoir comment reconstruire l'image si besoin
1128
+        #spip_unlink($src);
1129
+    }
1130 1130
 }
1131 1131
 
1132 1132
 
@@ -1151,71 +1151,71 @@  discard block
 block discarded – undo
1151 1151
  *     Code HTML de l'image
1152 1152
  **/
1153 1153
 function image_graver($img) {
1154
-	// appeler le filtre post_image_filtrer qui permet de faire
1155
-	// des traitements auto a la fin d'une serie de filtres
1156
-	$img = pipeline('post_image_filtrer', $img);
1157
-
1158
-	$fichier_ori = $fichier = extraire_attribut($img, 'src');
1159
-	if (($p = strpos($fichier, '?')) !== false) {
1160
-		$fichier = substr($fichier, 0, $p);
1161
-	}
1162
-	if (strlen($fichier) < 1) {
1163
-		$fichier = $img;
1164
-	}
1165
-	# si jamais le fichier final n'a pas ete calcule car suppose temporaire
1166
-	# et qu'il ne s'agit pas d'une URL
1167
-	if (strpos($fichier, '://') === false and !@file_exists($fichier)) {
1168
-		reconstruire_image_intermediaire($fichier);
1169
-	}
1170
-	ramasse_miettes($fichier);
1171
-
1172
-	// ajouter le timestamp si besoin
1173
-	if (strpos($fichier_ori, '?') === false) {
1174
-		// on utilise str_replace pour attraper le onmouseover des logo si besoin
1175
-		$img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
1176
-	}
1177
-
1178
-	return $img;
1154
+    // appeler le filtre post_image_filtrer qui permet de faire
1155
+    // des traitements auto a la fin d'une serie de filtres
1156
+    $img = pipeline('post_image_filtrer', $img);
1157
+
1158
+    $fichier_ori = $fichier = extraire_attribut($img, 'src');
1159
+    if (($p = strpos($fichier, '?')) !== false) {
1160
+        $fichier = substr($fichier, 0, $p);
1161
+    }
1162
+    if (strlen($fichier) < 1) {
1163
+        $fichier = $img;
1164
+    }
1165
+    # si jamais le fichier final n'a pas ete calcule car suppose temporaire
1166
+    # et qu'il ne s'agit pas d'une URL
1167
+    if (strpos($fichier, '://') === false and !@file_exists($fichier)) {
1168
+        reconstruire_image_intermediaire($fichier);
1169
+    }
1170
+    ramasse_miettes($fichier);
1171
+
1172
+    // ajouter le timestamp si besoin
1173
+    if (strpos($fichier_ori, '?') === false) {
1174
+        // on utilise str_replace pour attraper le onmouseover des logo si besoin
1175
+        $img = str_replace($fichier_ori, timestamp($fichier_ori), $img);
1176
+    }
1177
+
1178
+    return $img;
1179 1179
 }
1180 1180
 
1181 1181
 
1182 1182
 if (!function_exists('imagepalettetotruecolor')) {
1183
-	/**
1184
-	 * Transforme une image à palette indexée (256 couleurs max) en "vraies" couleurs RGB
1185
-	 *
1186
-	 * @note Pour compatibilité avec PHP < 5.5
1187
-	 *
1188
-	 * @link http://php.net/manual/fr/function.imagepalettetotruecolor.php
1189
-	 *
1190
-	 * @param ressource $img
1191
-	 * @return bool
1192
-	 *     - true si l'image est déjà en vrai RGB ou peut être transformée
1193
-	 *     - false si la transformation ne peut être faite.
1194
-	 **/
1195
-	function imagepalettetotruecolor(&$img) {
1196
-		if (!$img or !function_exists('imagecreatetruecolor')) {
1197
-			return false;
1198
-		} elseif (!imageistruecolor($img)) {
1199
-			$w = imagesx($img);
1200
-			$h = imagesy($img);
1201
-			$img1 = imagecreatetruecolor($w, $h);
1202
-			//Conserver la transparence si possible
1203
-			if (function_exists('ImageCopyResampled')) {
1204
-				if (function_exists('imageAntiAlias')) {
1205
-					imageAntiAlias($img1, true);
1206
-				}
1207
-				@imagealphablending($img1, false);
1208
-				@imagesavealpha($img1, true);
1209
-				@ImageCopyResampled($img1, $img, 0, 0, 0, 0, $w, $h, $w, $h);
1210
-			} else {
1211
-				imagecopy($img1, $img, 0, 0, 0, 0, $w, $h);
1212
-			}
1213
-
1214
-			$img = $img1;
1215
-		}
1216
-
1217
-		return true;
1218
-	}
1183
+    /**
1184
+     * Transforme une image à palette indexée (256 couleurs max) en "vraies" couleurs RGB
1185
+     *
1186
+     * @note Pour compatibilité avec PHP < 5.5
1187
+     *
1188
+     * @link http://php.net/manual/fr/function.imagepalettetotruecolor.php
1189
+     *
1190
+     * @param ressource $img
1191
+     * @return bool
1192
+     *     - true si l'image est déjà en vrai RGB ou peut être transformée
1193
+     *     - false si la transformation ne peut être faite.
1194
+     **/
1195
+    function imagepalettetotruecolor(&$img) {
1196
+        if (!$img or !function_exists('imagecreatetruecolor')) {
1197
+            return false;
1198
+        } elseif (!imageistruecolor($img)) {
1199
+            $w = imagesx($img);
1200
+            $h = imagesy($img);
1201
+            $img1 = imagecreatetruecolor($w, $h);
1202
+            //Conserver la transparence si possible
1203
+            if (function_exists('ImageCopyResampled')) {
1204
+                if (function_exists('imageAntiAlias')) {
1205
+                    imageAntiAlias($img1, true);
1206
+                }
1207
+                @imagealphablending($img1, false);
1208
+                @imagesavealpha($img1, true);
1209
+                @ImageCopyResampled($img1, $img, 0, 0, 0, 0, $w, $h, $w, $h);
1210
+            } else {
1211
+                imagecopy($img1, $img, 0, 0, 0, 0, $w, $h);
1212
+            }
1213
+
1214
+            $img = $img1;
1215
+        }
1216
+
1217
+        return true;
1218
+    }
1219 1219
 }
1220 1220
 
1221 1221
 /**
@@ -1242,34 +1242,34 @@  discard block
 block discarded – undo
1242 1242
  *     Code html modifié de la balise.
1243 1243
  **/
1244 1244
 function _image_tag_changer_taille($tag, $width, $height, $style = false) {
1245
-	if ($style === false) {
1246
-		$style = extraire_attribut($tag, 'style');
1247
-	}
1248
-
1249
-	// enlever le width et height du style
1250
-	if ($style) {
1251
-		$style = preg_replace(',(^|;)\s*(width|height)\s*:\s*[^;]+,ims', '', $style);
1252
-	}
1253
-	if ($style and $style[0] === ';') {
1254
-		$style = substr($style, 1);
1255
-	}
1256
-
1257
-	// mettre des attributs de width et height sur les images,
1258
-	// ca accelere le rendu du navigateur
1259
-	// ca permet aux navigateurs de reserver la bonne taille
1260
-	// quand on a desactive l'affichage des images.
1261
-	$tag = inserer_attribut($tag, 'width', round($width));
1262
-	$tag = inserer_attribut($tag, 'height', round($height));
1263
-
1264
-	// attributs deprecies. Transformer en CSS
1265
-	if ($espace = extraire_attribut($tag, 'hspace')) {
1266
-		$style = "margin:${espace}px;" . $style;
1267
-		$tag = inserer_attribut($tag, 'hspace', '');
1268
-	}
1269
-
1270
-	$tag = inserer_attribut($tag, 'style', (string) $style, true, $style ? false : true);
1271
-
1272
-	return $tag;
1245
+    if ($style === false) {
1246
+        $style = extraire_attribut($tag, 'style');
1247
+    }
1248
+
1249
+    // enlever le width et height du style
1250
+    if ($style) {
1251
+        $style = preg_replace(',(^|;)\s*(width|height)\s*:\s*[^;]+,ims', '', $style);
1252
+    }
1253
+    if ($style and $style[0] === ';') {
1254
+        $style = substr($style, 1);
1255
+    }
1256
+
1257
+    // mettre des attributs de width et height sur les images,
1258
+    // ca accelere le rendu du navigateur
1259
+    // ca permet aux navigateurs de reserver la bonne taille
1260
+    // quand on a desactive l'affichage des images.
1261
+    $tag = inserer_attribut($tag, 'width', round($width));
1262
+    $tag = inserer_attribut($tag, 'height', round($height));
1263
+
1264
+    // attributs deprecies. Transformer en CSS
1265
+    if ($espace = extraire_attribut($tag, 'hspace')) {
1266
+        $style = "margin:${espace}px;" . $style;
1267
+        $tag = inserer_attribut($tag, 'hspace', '');
1268
+    }
1269
+
1270
+    $tag = inserer_attribut($tag, 'style', (string) $style, true, $style ? false : true);
1271
+
1272
+    return $tag;
1273 1273
 }
1274 1274
 
1275 1275
 
@@ -1295,72 +1295,72 @@  discard block
 block discarded – undo
1295 1295
  *     Retourne le code HTML de l'image
1296 1296
  **/
1297 1297
 function _image_ecrire_tag($valeurs, $surcharge = []) {
1298
-	$valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1299
-
1300
-	// fermer les tags img pas bien fermes;
1301
-	$tag = str_replace('>', '/>', str_replace('/>', '>', $valeurs['tag']));
1302
-
1303
-	// le style
1304
-	$style = $valeurs['style'];
1305
-	if (isset($surcharge['style'])) {
1306
-		$style = $surcharge['style'];
1307
-		unset($surcharge['style']);
1308
-	}
1309
-
1310
-	// traiter specifiquement la largeur et la hauteur
1311
-	$width = $valeurs['largeur'];
1312
-	if (isset($surcharge['width'])) {
1313
-		$width = $surcharge['width'];
1314
-		unset($surcharge['width']);
1315
-	}
1316
-	$height = $valeurs['hauteur'];
1317
-	if (isset($surcharge['height'])) {
1318
-		$height = $surcharge['height'];
1319
-		unset($surcharge['height']);
1320
-	}
1321
-
1322
-	$tag = _image_tag_changer_taille($tag, $width, $height, $style);
1323
-	// traiter specifiquement le src qui peut etre repris dans un onmouseout
1324
-	// on remplace toute les ref a src dans le tag
1325
-	$src = extraire_attribut($tag, 'src');
1326
-	if (isset($surcharge['src'])) {
1327
-		$tag = str_replace($src, $surcharge['src'], $tag);
1328
-		// si il y a des & dans src, alors ils peuvent provenir d'un &amp
1329
-		// pas garanti comme methode, mais mieux que rien
1330
-		if (strpos($src, '&') !== false) {
1331
-			$tag = str_replace(str_replace('&', '&amp;', $src), $surcharge['src'], $tag);
1332
-		}
1333
-		$src = $surcharge['src'];
1334
-		unset($surcharge['src']);
1335
-	}
1336
-
1337
-	$class = $valeurs['class'];
1338
-	if (isset($surcharge['class'])) {
1339
-		$class = $surcharge['class'];
1340
-		unset($surcharge['class']);
1341
-	}
1342
-	if (is_scalar($class) && strlen($class)) {
1343
-		$tag = inserer_attribut($tag, 'class', $class);
1344
-	}
1345
-
1346
-	if (count($surcharge)) {
1347
-		foreach ($surcharge as $attribut => $valeur) {
1348
-			$tag = inserer_attribut($tag, $attribut, $valeur);
1349
-		}
1350
-	}
1351
-
1352
-	$tag = pipeline(
1353
-		'image_ecrire_tag_finir',
1354
-		[
1355
-			'args' => [
1356
-				'valeurs' => $valeurs,
1357
-				'surcharge' => $surcharge,
1358
-			],
1359
-			'data' => $tag
1360
-		]
1361
-	);
1362
-
1363
-	return $tag;
1298
+    $valeurs = pipeline('image_ecrire_tag_preparer', $valeurs);
1299
+
1300
+    // fermer les tags img pas bien fermes;
1301
+    $tag = str_replace('>', '/>', str_replace('/>', '>', $valeurs['tag']));
1302
+
1303
+    // le style
1304
+    $style = $valeurs['style'];
1305
+    if (isset($surcharge['style'])) {
1306
+        $style = $surcharge['style'];
1307
+        unset($surcharge['style']);
1308
+    }
1309
+
1310
+    // traiter specifiquement la largeur et la hauteur
1311
+    $width = $valeurs['largeur'];
1312
+    if (isset($surcharge['width'])) {
1313
+        $width = $surcharge['width'];
1314
+        unset($surcharge['width']);
1315
+    }
1316
+    $height = $valeurs['hauteur'];
1317
+    if (isset($surcharge['height'])) {
1318
+        $height = $surcharge['height'];
1319
+        unset($surcharge['height']);
1320
+    }
1321
+
1322
+    $tag = _image_tag_changer_taille($tag, $width, $height, $style);
1323
+    // traiter specifiquement le src qui peut etre repris dans un onmouseout
1324
+    // on remplace toute les ref a src dans le tag
1325
+    $src = extraire_attribut($tag, 'src');
1326
+    if (isset($surcharge['src'])) {
1327
+        $tag = str_replace($src, $surcharge['src'], $tag);
1328
+        // si il y a des & dans src, alors ils peuvent provenir d'un &amp
1329
+        // pas garanti comme methode, mais mieux que rien
1330
+        if (strpos($src, '&') !== false) {
1331
+            $tag = str_replace(str_replace('&', '&amp;', $src), $surcharge['src'], $tag);
1332
+        }
1333
+        $src = $surcharge['src'];
1334
+        unset($surcharge['src']);
1335
+    }
1336
+
1337
+    $class = $valeurs['class'];
1338
+    if (isset($surcharge['class'])) {
1339
+        $class = $surcharge['class'];
1340
+        unset($surcharge['class']);
1341
+    }
1342
+    if (is_scalar($class) && strlen($class)) {
1343
+        $tag = inserer_attribut($tag, 'class', $class);
1344
+    }
1345
+
1346
+    if (count($surcharge)) {
1347
+        foreach ($surcharge as $attribut => $valeur) {
1348
+            $tag = inserer_attribut($tag, $attribut, $valeur);
1349
+        }
1350
+    }
1351
+
1352
+    $tag = pipeline(
1353
+        'image_ecrire_tag_finir',
1354
+        [
1355
+            'args' => [
1356
+                'valeurs' => $valeurs,
1357
+                'surcharge' => $surcharge,
1358
+            ],
1359
+            'data' => $tag
1360
+        ]
1361
+    );
1362
+
1363
+    return $tag;
1364 1364
 }
1365 1365
 
1366 1366
 /**
@@ -1383,259 +1383,259 @@  discard block
 block discarded – undo
1383 1383
  *     Description de l'image, sinon null.
1384 1384
  **/
1385 1385
 function _image_creer_vignette($valeurs, $maxWidth, $maxHeight, $process = 'AUTO', $force = false) {
1386
-	$srcHeight = null;
1387
-	$retour = [];
1388
-	// ordre de preference des formats graphiques pour creer les vignettes
1389
-	// le premier format disponible, selon la methode demandee, est utilise
1390
-	$image = $valeurs['fichier'];
1391
-	$format = $valeurs['format_source'];
1392
-	$destdir = dirname($valeurs['fichier_dest']);
1393
-	$destfile = basename($valeurs['fichier_dest'], '.' . $valeurs['format_dest']);
1394
-
1395
-	$format_sortie = $valeurs['format_dest'];
1396
-
1397
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1398
-		$process = $GLOBALS['meta']['image_process'];
1399
-	}
1400
-
1401
-	// si le doc n'est pas une image dans un format accetpable, refuser
1402
-	if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1403
-		return;
1404
-	}
1405
-	$destination = "$destdir/$destfile";
1406
-
1407
-	// calculer la taille
1408
-	if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1409
-		if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1410
-			[$destWidth, $destHeight] = _image_ratio($srcWidth, $srcHeight, $maxWidth, $maxHeight);
1411
-		}
1412
-	} elseif ($process == 'convert' or $process == 'imagick') {
1413
-		$destWidth = $maxWidth;
1414
-		$destHeight = $maxHeight;
1415
-	} else {
1416
-		spip_log("echec $process sur $image");
1417
-
1418
-		return;
1419
-	}
1420
-
1421
-	$vignette = '';
1422
-
1423
-	// Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1424
-	if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1425
-		$vignette = $destination . '.' . $format;
1426
-		@copy($image, $vignette);
1427
-	}
1428
-
1429
-	elseif ($valeurs['format_source'] === 'svg') {
1430
-		if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)) {
1431
-			$format_sortie = 'svg';
1432
-			$vignette = $destination . '.' . $format_sortie;
1433
-			$valeurs['fichier_dest'] = $vignette;
1434
-			_image_gd_output($svg, $valeurs);
1435
-		}
1436
-	}
1437
-
1438
-	// imagemagick en ligne de commande
1439
-	elseif ($process == 'convert') {
1440
-		if (!defined('_CONVERT_COMMAND')) {
1441
-			define('_CONVERT_COMMAND', 'convert');
1442
-		} // Securite : mes_options.php peut preciser le chemin absolu
1443
-		if (!defined('_RESIZE_COMMAND')) {
1444
-			define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1445
-		}
1446
-		$vignette = $destination . '.' . $format_sortie;
1447
-		$commande = str_replace(
1448
-			['%x', '%y', '%src', '%dest'],
1449
-			[
1450
-				$destWidth,
1451
-				$destHeight,
1452
-				escapeshellcmd($image),
1453
-				escapeshellcmd($vignette)
1454
-			],
1455
-			_RESIZE_COMMAND
1456
-		);
1457
-		spip_log($commande);
1458
-		exec($commande);
1459
-		if (!@file_exists($vignette)) {
1460
-			spip_log("echec convert sur $vignette");
1461
-
1462
-			return;  // echec commande
1463
-		}
1464
-	}
1465
-
1466
-	// php5 imagemagick
1467
-	elseif ($process == 'imagick') {
1468
-		$vignette = "$destination." . $format_sortie;
1469
-
1470
-		if (!class_exists(\Imagick::class)) {
1471
-			spip_log('Classe Imagick absente !', _LOG_ERREUR);
1472
-
1473
-			return;
1474
-		}
1475
-		$imagick = new Imagick();
1476
-		$imagick->readImage($image);
1477
-		$imagick->resizeImage(
1478
-			$destWidth,
1479
-			$destHeight,
1480
-			Imagick::FILTER_LANCZOS,
1481
-			1
1482
-		);//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1483
-		$imagick->writeImage($vignette);
1484
-
1485
-		if (!@file_exists($vignette)) {
1486
-			spip_log("echec imagick sur $vignette");
1487
-
1488
-			return;
1489
-		}
1490
-	}
1491
-
1492
-	// netpbm
1493
-	elseif ($process == 'netpbm') {
1494
-		if (!defined('_PNMSCALE_COMMAND')) {
1495
-			define('_PNMSCALE_COMMAND', 'pnmscale');
1496
-		} // Securite : mes_options.php peut preciser le chemin absolu
1497
-		if (_PNMSCALE_COMMAND == '') {
1498
-			return;
1499
-		}
1500
-		$vignette = $destination . '.' . $format_sortie;
1501
-		$pnmtojpeg_command = str_replace('pnmscale', 'pnmtojpeg', _PNMSCALE_COMMAND);
1502
-		if ($format == 'jpg') {
1503
-			$jpegtopnm_command = str_replace('pnmscale', 'jpegtopnm', _PNMSCALE_COMMAND);
1504
-			exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1505
-			if (!($s = @filesize($vignette))) {
1506
-				spip_unlink($vignette);
1507
-			}
1508
-			if (!@file_exists($vignette)) {
1509
-				spip_log("echec netpbm-jpg sur $vignette");
1510
-
1511
-				return;
1512
-			}
1513
-		} else {
1514
-			if ($format == 'gif') {
1515
-				$giftopnm_command = str_replace('pnmscale', 'giftopnm', _PNMSCALE_COMMAND);
1516
-				exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1517
-				if (!($s = @filesize($vignette))) {
1518
-					spip_unlink($vignette);
1519
-				}
1520
-				if (!@file_exists($vignette)) {
1521
-					spip_log("echec netpbm-gif sur $vignette");
1522
-
1523
-					return;
1524
-				}
1525
-			} else {
1526
-				if ($format == 'png') {
1527
-					$pngtopnm_command = str_replace('pnmscale', 'pngtopnm', _PNMSCALE_COMMAND);
1528
-					exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1529
-					if (!($s = @filesize($vignette))) {
1530
-						spip_unlink($vignette);
1531
-					}
1532
-					if (!@file_exists($vignette)) {
1533
-						spip_log("echec netpbm-png sur $vignette");
1534
-
1535
-						return;
1536
-					}
1537
-				}
1538
-			}
1539
-		}
1540
-	}
1541
-
1542
-	// gd ou gd2
1543
-	elseif ($process == 'gd1' or $process == 'gd2') {
1544
-		if (!function_exists('gd_info')) {
1545
-			spip_log('Librairie GD absente !', _LOG_ERREUR);
1546
-
1547
-			return;
1548
-		}
1549
-		if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1550
-			spip_log('vignette gd1/gd2 impossible : ' . $srcWidth * $srcHeight . 'pixels');
1551
-
1552
-			return;
1553
-		}
1554
-		$destFormat = $format_sortie;
1555
-		if (!$destFormat) {
1556
-			spip_log("pas de format pour $image");
1557
-
1558
-			return;
1559
-		}
1560
-
1561
-		$fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1562
-		if (!function_exists($fonction_imagecreatefrom)) {
1563
-			return '';
1564
-		}
1565
-		$srcImage = @$fonction_imagecreatefrom($image);
1566
-		if (!$srcImage) {
1567
-			spip_log('echec gd1/gd2');
1568
-
1569
-			return;
1570
-		}
1571
-
1572
-		// Initialisation de l'image destination
1573
-		$destImage = null;
1574
-		if ($process == 'gd2' and $destFormat != 'gif') {
1575
-			$destImage = ImageCreateTrueColor($destWidth, $destHeight);
1576
-		}
1577
-		if (!$destImage) {
1578
-			$destImage = ImageCreate($destWidth, $destHeight);
1579
-		}
1580
-
1581
-		// Recopie de l'image d'origine avec adaptation de la taille
1582
-		$ok = false;
1583
-		if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1584
-			if ($format == 'gif') {
1585
-				// Si un GIF est transparent,
1586
-				// fabriquer un PNG transparent
1587
-				$transp = imagecolortransparent($srcImage);
1588
-				if ($transp > 0) {
1589
-					$destFormat = 'png';
1590
-				}
1591
-			}
1592
-			if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1593
-				// Conserver la transparence
1594
-				if (function_exists('imageAntiAlias')) {
1595
-					imageAntiAlias($destImage, true);
1596
-				}
1597
-				@imagealphablending($destImage, false);
1598
-				@imagesavealpha($destImage, true);
1599
-			}
1600
-			$ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1601
-		}
1602
-		if (!$ok) {
1603
-			$ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1604
-		}
1605
-
1606
-		// Sauvegarde de l'image destination
1607
-		$valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1608
-		$valeurs['format_dest'] = $format = $destFormat;
1609
-		_image_gd_output($destImage, $valeurs);
1610
-
1611
-		if ($srcImage) {
1612
-			ImageDestroy($srcImage);
1613
-		}
1614
-		ImageDestroy($destImage);
1615
-	}
1616
-
1617
-	if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1618
-		$size = [$destWidth, $destHeight];
1619
-	}
1620
-
1621
-	// Gaffe: en safe mode, pas d'acces a la vignette,
1622
-	// donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1623
-	if ($size[0] < 1) {
1624
-		$size[0] = $destWidth;
1625
-	}
1626
-	if ($size[1] < 1) {
1627
-		$size[1] = $destHeight;
1628
-	}
1629
-
1630
-	$retour['width'] = $largeur = $size[0];
1631
-	$retour['height'] = $hauteur = $size[1];
1632
-
1633
-	$retour['fichier'] = $vignette;
1634
-	$retour['format'] = $format;
1635
-	$retour['date'] = @filemtime($vignette);
1636
-
1637
-	// renvoyer l'image
1638
-	return $retour;
1386
+    $srcHeight = null;
1387
+    $retour = [];
1388
+    // ordre de preference des formats graphiques pour creer les vignettes
1389
+    // le premier format disponible, selon la methode demandee, est utilise
1390
+    $image = $valeurs['fichier'];
1391
+    $format = $valeurs['format_source'];
1392
+    $destdir = dirname($valeurs['fichier_dest']);
1393
+    $destfile = basename($valeurs['fichier_dest'], '.' . $valeurs['format_dest']);
1394
+
1395
+    $format_sortie = $valeurs['format_dest'];
1396
+
1397
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1398
+        $process = $GLOBALS['meta']['image_process'];
1399
+    }
1400
+
1401
+    // si le doc n'est pas une image dans un format accetpable, refuser
1402
+    if (!$force and !in_array($format, formats_image_acceptables(in_array($process, ['gd1', 'gd2'])))) {
1403
+        return;
1404
+    }
1405
+    $destination = "$destdir/$destfile";
1406
+
1407
+    // calculer la taille
1408
+    if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) {
1409
+        if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) {
1410
+            [$destWidth, $destHeight] = _image_ratio($srcWidth, $srcHeight, $maxWidth, $maxHeight);
1411
+        }
1412
+    } elseif ($process == 'convert' or $process == 'imagick') {
1413
+        $destWidth = $maxWidth;
1414
+        $destHeight = $maxHeight;
1415
+    } else {
1416
+        spip_log("echec $process sur $image");
1417
+
1418
+        return;
1419
+    }
1420
+
1421
+    $vignette = '';
1422
+
1423
+    // Si l'image est de la taille demandee (ou plus petite), simplement la retourner
1424
+    if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1425
+        $vignette = $destination . '.' . $format;
1426
+        @copy($image, $vignette);
1427
+    }
1428
+
1429
+    elseif ($valeurs['format_source'] === 'svg') {
1430
+        if ($svg = svg_redimensionner($valeurs['fichier'], $destWidth, $destHeight)) {
1431
+            $format_sortie = 'svg';
1432
+            $vignette = $destination . '.' . $format_sortie;
1433
+            $valeurs['fichier_dest'] = $vignette;
1434
+            _image_gd_output($svg, $valeurs);
1435
+        }
1436
+    }
1437
+
1438
+    // imagemagick en ligne de commande
1439
+    elseif ($process == 'convert') {
1440
+        if (!defined('_CONVERT_COMMAND')) {
1441
+            define('_CONVERT_COMMAND', 'convert');
1442
+        } // Securite : mes_options.php peut preciser le chemin absolu
1443
+        if (!defined('_RESIZE_COMMAND')) {
1444
+            define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest');
1445
+        }
1446
+        $vignette = $destination . '.' . $format_sortie;
1447
+        $commande = str_replace(
1448
+            ['%x', '%y', '%src', '%dest'],
1449
+            [
1450
+                $destWidth,
1451
+                $destHeight,
1452
+                escapeshellcmd($image),
1453
+                escapeshellcmd($vignette)
1454
+            ],
1455
+            _RESIZE_COMMAND
1456
+        );
1457
+        spip_log($commande);
1458
+        exec($commande);
1459
+        if (!@file_exists($vignette)) {
1460
+            spip_log("echec convert sur $vignette");
1461
+
1462
+            return;  // echec commande
1463
+        }
1464
+    }
1465
+
1466
+    // php5 imagemagick
1467
+    elseif ($process == 'imagick') {
1468
+        $vignette = "$destination." . $format_sortie;
1469
+
1470
+        if (!class_exists(\Imagick::class)) {
1471
+            spip_log('Classe Imagick absente !', _LOG_ERREUR);
1472
+
1473
+            return;
1474
+        }
1475
+        $imagick = new Imagick();
1476
+        $imagick->readImage($image);
1477
+        $imagick->resizeImage(
1478
+            $destWidth,
1479
+            $destHeight,
1480
+            Imagick::FILTER_LANCZOS,
1481
+            1
1482
+        );//, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100);
1483
+        $imagick->writeImage($vignette);
1484
+
1485
+        if (!@file_exists($vignette)) {
1486
+            spip_log("echec imagick sur $vignette");
1487
+
1488
+            return;
1489
+        }
1490
+    }
1491
+
1492
+    // netpbm
1493
+    elseif ($process == 'netpbm') {
1494
+        if (!defined('_PNMSCALE_COMMAND')) {
1495
+            define('_PNMSCALE_COMMAND', 'pnmscale');
1496
+        } // Securite : mes_options.php peut preciser le chemin absolu
1497
+        if (_PNMSCALE_COMMAND == '') {
1498
+            return;
1499
+        }
1500
+        $vignette = $destination . '.' . $format_sortie;
1501
+        $pnmtojpeg_command = str_replace('pnmscale', 'pnmtojpeg', _PNMSCALE_COMMAND);
1502
+        if ($format == 'jpg') {
1503
+            $jpegtopnm_command = str_replace('pnmscale', 'jpegtopnm', _PNMSCALE_COMMAND);
1504
+            exec("$jpegtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1505
+            if (!($s = @filesize($vignette))) {
1506
+                spip_unlink($vignette);
1507
+            }
1508
+            if (!@file_exists($vignette)) {
1509
+                spip_log("echec netpbm-jpg sur $vignette");
1510
+
1511
+                return;
1512
+            }
1513
+        } else {
1514
+            if ($format == 'gif') {
1515
+                $giftopnm_command = str_replace('pnmscale', 'giftopnm', _PNMSCALE_COMMAND);
1516
+                exec("$giftopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1517
+                if (!($s = @filesize($vignette))) {
1518
+                    spip_unlink($vignette);
1519
+                }
1520
+                if (!@file_exists($vignette)) {
1521
+                    spip_log("echec netpbm-gif sur $vignette");
1522
+
1523
+                    return;
1524
+                }
1525
+            } else {
1526
+                if ($format == 'png') {
1527
+                    $pngtopnm_command = str_replace('pnmscale', 'pngtopnm', _PNMSCALE_COMMAND);
1528
+                    exec("$pngtopnm_command $image | " . _PNMSCALE_COMMAND . " -width $destWidth | $pnmtojpeg_command > $vignette");
1529
+                    if (!($s = @filesize($vignette))) {
1530
+                        spip_unlink($vignette);
1531
+                    }
1532
+                    if (!@file_exists($vignette)) {
1533
+                        spip_log("echec netpbm-png sur $vignette");
1534
+
1535
+                        return;
1536
+                    }
1537
+                }
1538
+            }
1539
+        }
1540
+    }
1541
+
1542
+    // gd ou gd2
1543
+    elseif ($process == 'gd1' or $process == 'gd2') {
1544
+        if (!function_exists('gd_info')) {
1545
+            spip_log('Librairie GD absente !', _LOG_ERREUR);
1546
+
1547
+            return;
1548
+        }
1549
+        if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) {
1550
+            spip_log('vignette gd1/gd2 impossible : ' . $srcWidth * $srcHeight . 'pixels');
1551
+
1552
+            return;
1553
+        }
1554
+        $destFormat = $format_sortie;
1555
+        if (!$destFormat) {
1556
+            spip_log("pas de format pour $image");
1557
+
1558
+            return;
1559
+        }
1560
+
1561
+        $fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom'];
1562
+        if (!function_exists($fonction_imagecreatefrom)) {
1563
+            return '';
1564
+        }
1565
+        $srcImage = @$fonction_imagecreatefrom($image);
1566
+        if (!$srcImage) {
1567
+            spip_log('echec gd1/gd2');
1568
+
1569
+            return;
1570
+        }
1571
+
1572
+        // Initialisation de l'image destination
1573
+        $destImage = null;
1574
+        if ($process == 'gd2' and $destFormat != 'gif') {
1575
+            $destImage = ImageCreateTrueColor($destWidth, $destHeight);
1576
+        }
1577
+        if (!$destImage) {
1578
+            $destImage = ImageCreate($destWidth, $destHeight);
1579
+        }
1580
+
1581
+        // Recopie de l'image d'origine avec adaptation de la taille
1582
+        $ok = false;
1583
+        if (($process == 'gd2') and function_exists('ImageCopyResampled')) {
1584
+            if ($format == 'gif') {
1585
+                // Si un GIF est transparent,
1586
+                // fabriquer un PNG transparent
1587
+                $transp = imagecolortransparent($srcImage);
1588
+                if ($transp > 0) {
1589
+                    $destFormat = 'png';
1590
+                }
1591
+            }
1592
+            if (in_array($destFormat, _image_extensions_conservent_transparence())) {
1593
+                // Conserver la transparence
1594
+                if (function_exists('imageAntiAlias')) {
1595
+                    imageAntiAlias($destImage, true);
1596
+                }
1597
+                @imagealphablending($destImage, false);
1598
+                @imagesavealpha($destImage, true);
1599
+            }
1600
+            $ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1601
+        }
1602
+        if (!$ok) {
1603
+            $ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
1604
+        }
1605
+
1606
+        // Sauvegarde de l'image destination
1607
+        $valeurs['fichier_dest'] = $vignette = "$destination.$destFormat";
1608
+        $valeurs['format_dest'] = $format = $destFormat;
1609
+        _image_gd_output($destImage, $valeurs);
1610
+
1611
+        if ($srcImage) {
1612
+            ImageDestroy($srcImage);
1613
+        }
1614
+        ImageDestroy($destImage);
1615
+    }
1616
+
1617
+    if (!$vignette or !$size = @spip_getimagesize($vignette)) {
1618
+        $size = [$destWidth, $destHeight];
1619
+    }
1620
+
1621
+    // Gaffe: en safe mode, pas d'acces a la vignette,
1622
+    // donc risque de balancer "width='0'", ce qui masque l'image sous MSIE
1623
+    if ($size[0] < 1) {
1624
+        $size[0] = $destWidth;
1625
+    }
1626
+    if ($size[1] < 1) {
1627
+        $size[1] = $destHeight;
1628
+    }
1629
+
1630
+    $retour['width'] = $largeur = $size[0];
1631
+    $retour['height'] = $hauteur = $size[1];
1632
+
1633
+    $retour['fichier'] = $vignette;
1634
+    $retour['format'] = $format;
1635
+    $retour['date'] = @filemtime($vignette);
1636
+
1637
+    // renvoyer l'image
1638
+    return $retour;
1639 1639
 }
1640 1640
 
1641 1641
 /**
@@ -1655,25 +1655,25 @@  discard block
 block discarded – undo
1655 1655
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1656 1656
  **/
1657 1657
 function _image_ratio(int $srcWidth, int $srcHeight, int $maxWidth, int $maxHeight): array {
1658
-	$ratioWidth = $srcWidth / $maxWidth;
1659
-	$ratioHeight = $srcHeight / $maxHeight;
1660
-
1661
-	if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1662
-		$destWidth = $srcWidth;
1663
-		$destHeight = $srcHeight;
1664
-	} elseif ($ratioWidth < $ratioHeight) {
1665
-		$destWidth = $srcWidth / $ratioHeight;
1666
-		$destHeight = $maxHeight;
1667
-	} else {
1668
-		$destWidth = $maxWidth;
1669
-		$destHeight = $srcHeight / $ratioWidth;
1670
-	}
1671
-
1672
-	return [
1673
-		intval(round($destWidth)),
1674
-		intval(round($destHeight)),
1675
-		max($ratioWidth, $ratioHeight)
1676
-	];
1658
+    $ratioWidth = $srcWidth / $maxWidth;
1659
+    $ratioHeight = $srcHeight / $maxHeight;
1660
+
1661
+    if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1662
+        $destWidth = $srcWidth;
1663
+        $destHeight = $srcHeight;
1664
+    } elseif ($ratioWidth < $ratioHeight) {
1665
+        $destWidth = $srcWidth / $ratioHeight;
1666
+        $destHeight = $maxHeight;
1667
+    } else {
1668
+        $destWidth = $maxWidth;
1669
+        $destHeight = $srcHeight / $ratioWidth;
1670
+    }
1671
+
1672
+    return [
1673
+        intval(round($destWidth)),
1674
+        intval(round($destHeight)),
1675
+        max($ratioWidth, $ratioHeight)
1676
+    ];
1677 1677
 }
1678 1678
 
1679 1679
 /**
@@ -1693,25 +1693,25 @@  discard block
 block discarded – undo
1693 1693
  * @return array Liste [ largeur, hauteur, ratio de réduction ]
1694 1694
  **/
1695 1695
 function ratio_passe_partout(int $srcWidth, int $srcHeight, int $maxWidth, int $maxHeight): array {
1696
-	$ratioWidth = $srcWidth / $maxWidth;
1697
-	$ratioHeight = $srcHeight / $maxHeight;
1698
-
1699
-	if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1700
-		$destWidth = $srcWidth;
1701
-		$destHeight = $srcHeight;
1702
-	} elseif ($ratioWidth > $ratioHeight) {
1703
-		$destWidth = $srcWidth / $ratioHeight;
1704
-		$destHeight = $maxHeight;
1705
-	} else {
1706
-		$destWidth = $maxWidth;
1707
-		$destHeight = $srcHeight / $ratioWidth;
1708
-	}
1709
-
1710
-	return [
1711
-		intval(round($destWidth)),
1712
-		intval(round($destHeight)),
1713
-		min($ratioWidth, $ratioHeight)
1714
-	];
1696
+    $ratioWidth = $srcWidth / $maxWidth;
1697
+    $ratioHeight = $srcHeight / $maxHeight;
1698
+
1699
+    if ($srcWidth <= $maxWidth and $srcHeight <= $maxHeight) {
1700
+        $destWidth = $srcWidth;
1701
+        $destHeight = $srcHeight;
1702
+    } elseif ($ratioWidth > $ratioHeight) {
1703
+        $destWidth = $srcWidth / $ratioHeight;
1704
+        $destHeight = $maxHeight;
1705
+    } else {
1706
+        $destWidth = $maxWidth;
1707
+        $destHeight = $srcHeight / $ratioWidth;
1708
+    }
1709
+
1710
+    return [
1711
+        intval(round($destWidth)),
1712
+        intval(round($destHeight)),
1713
+        min($ratioWidth, $ratioHeight)
1714
+    ];
1715 1715
 }
1716 1716
 
1717 1717
 
@@ -1724,12 +1724,12 @@  discard block
 block discarded – undo
1724 1724
  * @return string
1725 1725
  */
1726 1726
 function process_image_svg_identite($image) {
1727
-	if ($image['creer']) {
1728
-		$source = $image['fichier'];
1729
-		_image_gd_output($source, $image);
1730
-	}
1727
+    if ($image['creer']) {
1728
+        $source = $image['fichier'];
1729
+        _image_gd_output($source, $image);
1730
+    }
1731 1731
 
1732
-	return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1732
+    return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1733 1733
 }
1734 1734
 
1735 1735
 
@@ -1762,111 +1762,111 @@  discard block
 block discarded – undo
1762 1762
  *     Code HTML de la balise img produite
1763 1763
  **/
1764 1764
 function process_image_reduire($fonction, $img, $taille, $taille_y, $force, $process = 'AUTO') {
1765
-	$image = false;
1766
-	if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1767
-		$process = $GLOBALS['meta']['image_process'];
1768
-	}
1769
-	# determiner le format de sortie
1770
-	$format_sortie = false; // le choix par defaut sera bon
1771
-	if ($process == 'netpbm') {
1772
-		$format_sortie = 'jpg';
1773
-	} elseif ($process == 'gd1' or $process == 'gd2') {
1774
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1775
-		// on verifie que l'extension choisie est bonne (en principe oui)
1776
-		$gd_formats = formats_image_acceptables(true);
1777
-		if (
1778
-			is_array($image)
1779
-			and (!in_array($image['format_dest'], $gd_formats)
1780
-				or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1781
-			)
1782
-		) {
1783
-			if ($image['format_source'] == 'jpg') {
1784
-				$formats_sortie = ['jpg', 'png', 'gif'];
1785
-			} else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1786
-			{
1787
-				$formats_sortie = ['png', 'jpg', 'gif'];
1788
-			}
1789
-			// Choisir le format destination
1790
-			// - on sauve de preference en JPEG (meilleure compression)
1791
-			// - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1792
-			# bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1793
-			# pas *ecrire*
1794
-			$format_sortie = '';
1795
-			foreach ($formats_sortie as $fmt) {
1796
-				if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1797
-					$format_sortie = $fmt;
1798
-					break;
1799
-				}
1800
-			}
1801
-			$image = false;
1802
-		}
1803
-	}
1804
-
1805
-	if (!is_array($image)) {
1806
-		$image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1807
-	}
1808
-
1809
-	if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1810
-		spip_log("image_reduire_src:pas de version locale de $img");
1811
-		// on peut resizer en mode html si on dispose des elements
1812
-		if (
1813
-			$srcw = extraire_attribut($img, 'width')
1814
-			and $srch = extraire_attribut($img, 'height')
1815
-		) {
1816
-			[$w, $h] = _image_ratio($srcw, $srch, $taille, $taille_y);
1817
-
1818
-			return _image_tag_changer_taille($img, $w, $h);
1819
-		}
1820
-		// la on n'a pas d'infos sur l'image source... on refile le truc a css
1821
-		// sous la forme style='max-width: NNpx;'
1822
-		return inserer_attribut(
1823
-			$img,
1824
-			'style',
1825
-			"max-width: ${taille}px; max-height: ${taille_y}px"
1826
-		);
1827
-	}
1828
-
1829
-	// si l'image est plus petite que la cible retourner une copie cachee de l'image
1830
-	if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1831
-		if ($image['creer']) {
1832
-			@copy($image['fichier'], $image['fichier_dest']);
1833
-		}
1834
-
1835
-		return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1836
-	}
1837
-
1838
-	if ($image['creer'] == false && !$force) {
1839
-		return _image_ecrire_tag(
1840
-			$image,
1841
-			['src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']]
1842
-		);
1843
-	}
1844
-
1845
-	if (in_array($image['format_source'], _image_extensions_acceptees_en_entree())) {
1846
-		$destWidth = $image['largeur_dest'];
1847
-		$destHeight = $image['hauteur_dest'];
1848
-		$logo = $image['fichier'];
1849
-		$date = $image['date_src'];
1850
-		$preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1851
-
1852
-		if ($preview && $preview['fichier']) {
1853
-			$logo = $preview['fichier'];
1854
-			$destWidth = $preview['width'];
1855
-			$destHeight = $preview['height'];
1856
-			$date = $preview['date'];
1857
-		}
1858
-		// dans l'espace prive mettre un timestamp sur l'adresse
1859
-		// de l'image, de facon a tromper le cache du navigateur
1860
-		// quand on fait supprimer/reuploader un logo
1861
-		// (pas de filemtime si SAFE MODE)
1862
-		$date = test_espace_prive() ? ('?' . $date) : '';
1863
-
1864
-		return _image_ecrire_tag($image, ['src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight]);
1865
-	}
1866
-	else {
1867
-		# BMP, tiff ... les redacteurs osent tout!
1868
-		return $img;
1869
-	}
1765
+    $image = false;
1766
+    if (($process == 'AUTO') and isset($GLOBALS['meta']['image_process'])) {
1767
+        $process = $GLOBALS['meta']['image_process'];
1768
+    }
1769
+    # determiner le format de sortie
1770
+    $format_sortie = false; // le choix par defaut sera bon
1771
+    if ($process == 'netpbm') {
1772
+        $format_sortie = 'jpg';
1773
+    } elseif ($process == 'gd1' or $process == 'gd2') {
1774
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1775
+        // on verifie que l'extension choisie est bonne (en principe oui)
1776
+        $gd_formats = formats_image_acceptables(true);
1777
+        if (
1778
+            is_array($image)
1779
+            and (!in_array($image['format_dest'], $gd_formats)
1780
+                or (!in_array($image['format_dest'], _image_extensions_acceptees_en_sortie()))
1781
+            )
1782
+        ) {
1783
+            if ($image['format_source'] == 'jpg') {
1784
+                $formats_sortie = ['jpg', 'png', 'gif'];
1785
+            } else // les gif sont passes en png preferentiellement pour etre homogene aux autres filtres images
1786
+            {
1787
+                $formats_sortie = ['png', 'jpg', 'gif'];
1788
+            }
1789
+            // Choisir le format destination
1790
+            // - on sauve de preference en JPEG (meilleure compression)
1791
+            // - pour le GIF : les GD recentes peuvent le lire mais pas l'ecrire
1792
+            # bug : gd_formats contient la liste des fichiers qu'on sait *lire*,
1793
+            # pas *ecrire*
1794
+            $format_sortie = '';
1795
+            foreach ($formats_sortie as $fmt) {
1796
+                if (in_array($fmt, $gd_formats) and in_array($fmt, _image_extensions_acceptees_en_sortie())) {
1797
+                    $format_sortie = $fmt;
1798
+                    break;
1799
+                }
1800
+            }
1801
+            $image = false;
1802
+        }
1803
+    }
1804
+
1805
+    if (!is_array($image)) {
1806
+        $image = _image_valeurs_trans($img, "reduire-{$taille}-{$taille_y}", $format_sortie, $fonction, false, _SVG_SUPPORTED);
1807
+    }
1808
+
1809
+    if (!is_array($image) or !$image['largeur'] or !$image['hauteur']) {
1810
+        spip_log("image_reduire_src:pas de version locale de $img");
1811
+        // on peut resizer en mode html si on dispose des elements
1812
+        if (
1813
+            $srcw = extraire_attribut($img, 'width')
1814
+            and $srch = extraire_attribut($img, 'height')
1815
+        ) {
1816
+            [$w, $h] = _image_ratio($srcw, $srch, $taille, $taille_y);
1817
+
1818
+            return _image_tag_changer_taille($img, $w, $h);
1819
+        }
1820
+        // la on n'a pas d'infos sur l'image source... on refile le truc a css
1821
+        // sous la forme style='max-width: NNpx;'
1822
+        return inserer_attribut(
1823
+            $img,
1824
+            'style',
1825
+            "max-width: ${taille}px; max-height: ${taille_y}px"
1826
+        );
1827
+    }
1828
+
1829
+    // si l'image est plus petite que la cible retourner une copie cachee de l'image
1830
+    if (($image['largeur'] <= $taille) && ($image['hauteur'] <= $taille_y)) {
1831
+        if ($image['creer']) {
1832
+            @copy($image['fichier'], $image['fichier_dest']);
1833
+        }
1834
+
1835
+        return _image_ecrire_tag($image, ['src' => $image['fichier_dest']]);
1836
+    }
1837
+
1838
+    if ($image['creer'] == false && !$force) {
1839
+        return _image_ecrire_tag(
1840
+            $image,
1841
+            ['src' => $image['fichier_dest'], 'width' => $image['largeur_dest'], 'height' => $image['hauteur_dest']]
1842
+        );
1843
+    }
1844
+
1845
+    if (in_array($image['format_source'], _image_extensions_acceptees_en_entree())) {
1846
+        $destWidth = $image['largeur_dest'];
1847
+        $destHeight = $image['hauteur_dest'];
1848
+        $logo = $image['fichier'];
1849
+        $date = $image['date_src'];
1850
+        $preview = _image_creer_vignette($image, $taille, $taille_y, $process, $force);
1851
+
1852
+        if ($preview && $preview['fichier']) {
1853
+            $logo = $preview['fichier'];
1854
+            $destWidth = $preview['width'];
1855
+            $destHeight = $preview['height'];
1856
+            $date = $preview['date'];
1857
+        }
1858
+        // dans l'espace prive mettre un timestamp sur l'adresse
1859
+        // de l'image, de facon a tromper le cache du navigateur
1860
+        // quand on fait supprimer/reuploader un logo
1861
+        // (pas de filemtime si SAFE MODE)
1862
+        $date = test_espace_prive() ? ('?' . $date) : '';
1863
+
1864
+        return _image_ecrire_tag($image, ['src' => "$logo$date", 'width' => $destWidth, 'height' => $destHeight]);
1865
+    }
1866
+    else {
1867
+        # BMP, tiff ... les redacteurs osent tout!
1868
+        return $img;
1869
+    }
1870 1870
 }
1871 1871
 
1872 1872
 /**
@@ -1881,145 +1881,145 @@  discard block
 block discarded – undo
1881 1881
  */
1882 1882
 class phpthumb_functions {
1883 1883
 
1884
-	/**
1885
-	 * Retourne la couleur d'un pixel dans une image
1886
-	 *
1887
-	 * @param ressource $img
1888
-	 * @param int $x
1889
-	 * @param int $y
1890
-	 * @return array|bool
1891
-	 */
1892
-	public static function GetPixelColor(&$img, $x, $y) {
1893
-		if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1894
-			return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1895
-		}
1896
-		return false;
1897
-	}
1898
-
1899
-	/**
1900
-	 * Retourne un nombre dans une représentation en Little Endian
1901
-	 *
1902
-	 * @param int $number
1903
-	 * @param int $minbytes
1904
-	 * @return string
1905
-	 */
1906
-	public static function LittleEndian2String($number, $minbytes = 1) {
1907
-		$intstring = '';
1908
-		while ($number > 0) {
1909
-			$intstring = $intstring . chr($number & 255);
1910
-			$number >>= 8;
1911
-		}
1912
-
1913
-		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1914
-	}
1915
-
1916
-	/**
1917
-	 * Transforme une ressource GD en image au format ICO
1918
-	 *
1919
-	 * @param array $gd_image_array
1920
-	 *     Tableau de ressources d'images GD
1921
-	 * @return string
1922
-	 *     Image au format ICO
1923
-	 */
1924
-	public static function GD2ICOstring(&$gd_image_array) {
1925
-		foreach ($gd_image_array as $key => $gd_image) {
1926
-			$ImageWidths[$key] = ImageSX($gd_image);
1927
-			$ImageHeights[$key] = ImageSY($gd_image);
1928
-			$bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1929
-			$totalcolors[$key] = ImageColorsTotal($gd_image);
1930
-
1931
-			$icXOR[$key] = '';
1932
-			for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1933
-				for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1934
-					$argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1935
-					$a = round(255 * ((127 - $argb['alpha']) / 127));
1936
-					$r = $argb['red'];
1937
-					$g = $argb['green'];
1938
-					$b = $argb['blue'];
1939
-
1940
-					if ($bpp[$key] == 32) {
1941
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1942
-					} elseif ($bpp[$key] == 24) {
1943
-						$icXOR[$key] .= chr($b) . chr($g) . chr($r);
1944
-					}
1945
-
1946
-					if ($a < 128) {
1947
-						@$icANDmask[$key][$y] .= '1';
1948
-					} else {
1949
-						@$icANDmask[$key][$y] .= '0';
1950
-					}
1951
-				}
1952
-				// mask bits are 32-bit aligned per scanline
1953
-				while (strlen($icANDmask[$key][$y]) % 32) {
1954
-					$icANDmask[$key][$y] .= '0';
1955
-				}
1956
-			}
1957
-			$icAND[$key] = '';
1958
-			foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1959
-				for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1960
-					$icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1961
-				}
1962
-			}
1963
-		}
1964
-
1965
-		foreach ($gd_image_array as $key => $gd_image) {
1966
-			$biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1967
-
1968
-			// BITMAPINFOHEADER - 40 bytes
1969
-			$BitmapInfoHeader[$key] = '';
1970
-			$BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1971
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1972
-			// The biHeight member specifies the combined
1973
-			// height of the XOR and AND masks.
1974
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1975
-			$BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1976
-			$BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1977
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1978
-			$BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1979
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1980
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1981
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1982
-			$BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1983
-		}
1984
-
1985
-
1986
-		$icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1987
-		$icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1988
-		$icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1989
-
1990
-		$dwImageOffset = 6 + (count($gd_image_array) * 16);
1991
-		foreach ($gd_image_array as $key => $gd_image) {
1992
-			// ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1993
-
1994
-			$icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1995
-			$icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1996
-			$icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1997
-			$icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1998
-
1999
-			$icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
2000
-			$icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
2001
-
2002
-			$dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
2003
-			$icondata .= phpthumb_functions::LittleEndian2String(
2004
-				$dwBytesInRes,
2005
-				4
2006
-			);     // dwBytesInRes;	// How many bytes in this resource?
2007
-
2008
-			$icondata .= phpthumb_functions::LittleEndian2String(
2009
-				$dwImageOffset,
2010
-				4
2011
-			);    // dwImageOffset;   // Where in the file is this image?
2012
-			$dwImageOffset += strlen($BitmapInfoHeader[$key]);
2013
-			$dwImageOffset += strlen($icXOR[$key]);
2014
-			$dwImageOffset += strlen($icAND[$key]);
2015
-		}
2016
-
2017
-		foreach ($gd_image_array as $key => $gd_image) {
2018
-			$icondata .= $BitmapInfoHeader[$key];
2019
-			$icondata .= $icXOR[$key];
2020
-			$icondata .= $icAND[$key];
2021
-		}
2022
-
2023
-		return $icondata;
2024
-	}
1884
+    /**
1885
+     * Retourne la couleur d'un pixel dans une image
1886
+     *
1887
+     * @param ressource $img
1888
+     * @param int $x
1889
+     * @param int $y
1890
+     * @return array|bool
1891
+     */
1892
+    public static function GetPixelColor(&$img, $x, $y) {
1893
+        if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
1894
+            return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
1895
+        }
1896
+        return false;
1897
+    }
1898
+
1899
+    /**
1900
+     * Retourne un nombre dans une représentation en Little Endian
1901
+     *
1902
+     * @param int $number
1903
+     * @param int $minbytes
1904
+     * @return string
1905
+     */
1906
+    public static function LittleEndian2String($number, $minbytes = 1) {
1907
+        $intstring = '';
1908
+        while ($number > 0) {
1909
+            $intstring = $intstring . chr($number & 255);
1910
+            $number >>= 8;
1911
+        }
1912
+
1913
+        return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
1914
+    }
1915
+
1916
+    /**
1917
+     * Transforme une ressource GD en image au format ICO
1918
+     *
1919
+     * @param array $gd_image_array
1920
+     *     Tableau de ressources d'images GD
1921
+     * @return string
1922
+     *     Image au format ICO
1923
+     */
1924
+    public static function GD2ICOstring(&$gd_image_array) {
1925
+        foreach ($gd_image_array as $key => $gd_image) {
1926
+            $ImageWidths[$key] = ImageSX($gd_image);
1927
+            $ImageHeights[$key] = ImageSY($gd_image);
1928
+            $bpp[$key] = ImageIsTrueColor($gd_image) ? 32 : 24;
1929
+            $totalcolors[$key] = ImageColorsTotal($gd_image);
1930
+
1931
+            $icXOR[$key] = '';
1932
+            for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
1933
+                for ($x = 0; $x < $ImageWidths[$key]; $x++) {
1934
+                    $argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
1935
+                    $a = round(255 * ((127 - $argb['alpha']) / 127));
1936
+                    $r = $argb['red'];
1937
+                    $g = $argb['green'];
1938
+                    $b = $argb['blue'];
1939
+
1940
+                    if ($bpp[$key] == 32) {
1941
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r) . chr($a);
1942
+                    } elseif ($bpp[$key] == 24) {
1943
+                        $icXOR[$key] .= chr($b) . chr($g) . chr($r);
1944
+                    }
1945
+
1946
+                    if ($a < 128) {
1947
+                        @$icANDmask[$key][$y] .= '1';
1948
+                    } else {
1949
+                        @$icANDmask[$key][$y] .= '0';
1950
+                    }
1951
+                }
1952
+                // mask bits are 32-bit aligned per scanline
1953
+                while (strlen($icANDmask[$key][$y]) % 32) {
1954
+                    $icANDmask[$key][$y] .= '0';
1955
+                }
1956
+            }
1957
+            $icAND[$key] = '';
1958
+            foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
1959
+                for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
1960
+                    $icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, '0', STR_PAD_LEFT)));
1961
+                }
1962
+            }
1963
+        }
1964
+
1965
+        foreach ($gd_image_array as $key => $gd_image) {
1966
+            $biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
1967
+
1968
+            // BITMAPINFOHEADER - 40 bytes
1969
+            $BitmapInfoHeader[$key] = '';
1970
+            $BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";                // DWORD  biSize;
1971
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageWidths[$key], 4);    // LONG   biWidth;
1972
+            // The biHeight member specifies the combined
1973
+            // height of the XOR and AND masks.
1974
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG   biHeight;
1975
+            $BitmapInfoHeader[$key] .= "\x01\x00";                    // WORD   biPlanes;
1976
+            $BitmapInfoHeader[$key] .= chr($bpp[$key]) . "\x00";              // wBitCount;
1977
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biCompression;
1978
+            $BitmapInfoHeader[$key] .= phpthumb_functions::LittleEndian2String($biSizeImage, 4);      // DWORD  biSizeImage;
1979
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biXPelsPerMeter;
1980
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // LONG   biYPelsPerMeter;
1981
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrUsed;
1982
+            $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";                // DWORD  biClrImportant;
1983
+        }
1984
+
1985
+
1986
+        $icondata = "\x00\x00";                    // idReserved;   // Reserved (must be 0)
1987
+        $icondata .= "\x01\x00";                    // idType;	   // Resource Type (1 for icons)
1988
+        $icondata .= phpthumb_functions::LittleEndian2String(count($gd_image_array), 2);  // idCount;	  // How many images?
1989
+
1990
+        $dwImageOffset = 6 + (count($gd_image_array) * 16);
1991
+        foreach ($gd_image_array as $key => $gd_image) {
1992
+            // ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
1993
+
1994
+            $icondata .= chr($ImageWidths[$key]);           // bWidth;		  // Width, in pixels, of the image
1995
+            $icondata .= chr($ImageHeights[$key]);          // bHeight;		 // Height, in pixels, of the image
1996
+            $icondata .= chr($totalcolors[$key]);           // bColorCount;	 // Number of colors in image (0 if >=8bpp)
1997
+            $icondata .= "\x00";                    // bReserved;	   // Reserved ( must be 0)
1998
+
1999
+            $icondata .= "\x01\x00";                  // wPlanes;		 // Color Planes
2000
+            $icondata .= chr($bpp[$key]) . "\x00";            // wBitCount;	   // Bits per pixel
2001
+
2002
+            $dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
2003
+            $icondata .= phpthumb_functions::LittleEndian2String(
2004
+                $dwBytesInRes,
2005
+                4
2006
+            );     // dwBytesInRes;	// How many bytes in this resource?
2007
+
2008
+            $icondata .= phpthumb_functions::LittleEndian2String(
2009
+                $dwImageOffset,
2010
+                4
2011
+            );    // dwImageOffset;   // Where in the file is this image?
2012
+            $dwImageOffset += strlen($BitmapInfoHeader[$key]);
2013
+            $dwImageOffset += strlen($icXOR[$key]);
2014
+            $dwImageOffset += strlen($icAND[$key]);
2015
+        }
2016
+
2017
+        foreach ($gd_image_array as $key => $gd_image) {
2018
+            $icondata .= $BitmapInfoHeader[$key];
2019
+            $icondata .= $icXOR[$key];
2020
+            $icondata .= $icAND[$key];
2021
+        }
2022
+
2023
+        return $icondata;
2024
+    }
2025 2025
 }
Please login to merge, or discard this patch.
ecrire/inc/svg.php 1 patch
Indentation   +448 added lines, -448 removed lines patch added patch discarded remove patch
@@ -17,13 +17,13 @@  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
 if (!defined('IMG_SVG')) {
24
-	// complete 	IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP
25
-	define('IMG_SVG', 128);
26
-	define('IMAGETYPE_SVG', 19);
24
+    // complete 	IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP
25
+    define('IMG_SVG', 128);
26
+    define('IMAGETYPE_SVG', 19);
27 27
 }
28 28
 
29 29
 /**
@@ -39,39 +39,39 @@  discard block
 block discarded – undo
39 39
  *   false si on a pas pu charger l'image
40 40
  */
41 41
 function svg_charger($fichier, $maxlen = null) {
42
-	if (strpos($fichier, 'data:image/svg+xml') === 0) {
43
-		$image = explode(';', $fichier, 2);
44
-		$image = end($image);
45
-		if (strpos($image, 'base64,') === 0) {
46
-			$image = base64_decode(substr($image, 7));
47
-		}
48
-		if (strpos($image, '<svg') !== false) {
49
-			return $image;
50
-		}
51
-		// encodage inconnu ou autre format d'image ?
52
-		return false;
53
-	}
54
-	// c'est peut etre deja une image svg ?
55
-	if (strpos($fichier, '<svg') !== false) {
56
-		return $fichier;
57
-	}
58
-	if (!file_exists($fichier)) {
59
-		$fichier  = supprimer_timestamp($fichier);
60
-		if (!file_exists($fichier)) {
61
-			return false;
62
-		}
63
-	}
64
-	if (is_null($maxlen)) {
65
-		$image = file_get_contents($fichier);
66
-	}
67
-	else {
68
-		$image = file_get_contents($fichier, false, null, 0, $maxlen);
69
-	}
70
-	// est-ce bien une image svg ?
71
-	if (strpos($image, '<svg') !== false) {
72
-		return $image;
73
-	}
74
-	return false;
42
+    if (strpos($fichier, 'data:image/svg+xml') === 0) {
43
+        $image = explode(';', $fichier, 2);
44
+        $image = end($image);
45
+        if (strpos($image, 'base64,') === 0) {
46
+            $image = base64_decode(substr($image, 7));
47
+        }
48
+        if (strpos($image, '<svg') !== false) {
49
+            return $image;
50
+        }
51
+        // encodage inconnu ou autre format d'image ?
52
+        return false;
53
+    }
54
+    // c'est peut etre deja une image svg ?
55
+    if (strpos($fichier, '<svg') !== false) {
56
+        return $fichier;
57
+    }
58
+    if (!file_exists($fichier)) {
59
+        $fichier  = supprimer_timestamp($fichier);
60
+        if (!file_exists($fichier)) {
61
+            return false;
62
+        }
63
+    }
64
+    if (is_null($maxlen)) {
65
+        $image = file_get_contents($fichier);
66
+    }
67
+    else {
68
+        $image = file_get_contents($fichier, false, null, 0, $maxlen);
69
+    }
70
+    // est-ce bien une image svg ?
71
+    if (strpos($image, '<svg') !== false) {
72
+        return $image;
73
+    }
74
+    return false;
75 75
 }
76 76
 
77 77
 /**
@@ -80,28 +80,28 @@  discard block
 block discarded – undo
80 80
  * @return array|bool
81 81
  */
82 82
 function svg_lire_balise_svg($fichier) {
83
-	if (!$debut_fichier = svg_charger($fichier, 4096)) {
84
-		return false;
85
-	}
86
-
87
-	if (($ps = stripos($debut_fichier, '<svg')) !== false) {
88
-		$pe = stripos($debut_fichier, '>', $ps);
89
-		$balise_svg = substr($debut_fichier, $ps, $pe - $ps + 1);
90
-
91
-		if (preg_match_all(',([\w:\-]+)=,Uims', $balise_svg, $matches)) {
92
-			if (!function_exists('extraire_attribut')) {
93
-				include_spip('inc/filtres');
94
-			}
95
-			$attributs = [];
96
-			foreach ($matches[1] as $att) {
97
-				$attributs[$att] = extraire_attribut($balise_svg, $att);
98
-			}
99
-
100
-			return [$balise_svg, $attributs];
101
-		}
102
-	}
103
-
104
-	return false;
83
+    if (!$debut_fichier = svg_charger($fichier, 4096)) {
84
+        return false;
85
+    }
86
+
87
+    if (($ps = stripos($debut_fichier, '<svg')) !== false) {
88
+        $pe = stripos($debut_fichier, '>', $ps);
89
+        $balise_svg = substr($debut_fichier, $ps, $pe - $ps + 1);
90
+
91
+        if (preg_match_all(',([\w:\-]+)=,Uims', $balise_svg, $matches)) {
92
+            if (!function_exists('extraire_attribut')) {
93
+                include_spip('inc/filtres');
94
+            }
95
+            $attributs = [];
96
+            foreach ($matches[1] as $att) {
97
+                $attributs[$att] = extraire_attribut($balise_svg, $att);
98
+            }
99
+
100
+            return [$balise_svg, $attributs];
101
+        }
102
+    }
103
+
104
+    return false;
105 105
 }
106 106
 
107 107
 /**
@@ -111,12 +111,12 @@  discard block
 block discarded – undo
111 111
  */
112 112
 function svg_lire_attributs($img) {
113 113
 
114
-	if ($svg_infos = svg_lire_balise_svg($img)) {
115
-		[$balise_svg, $attributs] = $svg_infos;
116
-		return $attributs;
117
-	}
114
+    if ($svg_infos = svg_lire_balise_svg($img)) {
115
+        [$balise_svg, $attributs] = $svg_infos;
116
+        return $attributs;
117
+    }
118 118
 
119
-	return false;
119
+    return false;
120 120
 }
121 121
 
122 122
 /**
@@ -126,38 +126,38 @@  discard block
 block discarded – undo
126 126
  * @return bool|float|int
127 127
  */
128 128
 function svg_dimension_to_pixels($dimension, $precision = 2) {
129
-	if (preg_match(',^(-?\d+(\.\d+)?)([^\d]*),i', trim($dimension), $m)) {
130
-		switch (strtolower($m[2])) {
131
-			case '%':
132
-				// on ne sait pas faire :(
133
-				return false;
134
-				break;
135
-			case 'em':
136
-				return round($m[1] * 16, $precision); // 16px font-size par defaut
137
-				break;
138
-			case 'ex':
139
-				return round($m[1] * 16, $precision); // 16px font-size par defaut
140
-				break;
141
-			case 'pc':
142
-				return round($m[1] * 16, $precision); // 1/6 inch = 96px/6 in CSS
143
-				break;
144
-			case 'cm':
145
-				return round($m[1] * 96 / 2.54, $precision); // 96px / 2.54cm;
146
-				break;
147
-			case 'mm':
148
-				return round($m[1] * 96 / 25.4, $precision); // 96px / 25.4mm;
149
-				break;
150
-			case 'in':
151
-				return round($m[1] * 96, $precision); // 1 inch = 96px in CSS
152
-				break;
153
-			case 'px':
154
-			case 'pt':
155
-			default:
156
-				return $m[1];
157
-				break;
158
-		}
159
-	}
160
-	return false;
129
+    if (preg_match(',^(-?\d+(\.\d+)?)([^\d]*),i', trim($dimension), $m)) {
130
+        switch (strtolower($m[2])) {
131
+            case '%':
132
+                // on ne sait pas faire :(
133
+                return false;
134
+                break;
135
+            case 'em':
136
+                return round($m[1] * 16, $precision); // 16px font-size par defaut
137
+                break;
138
+            case 'ex':
139
+                return round($m[1] * 16, $precision); // 16px font-size par defaut
140
+                break;
141
+            case 'pc':
142
+                return round($m[1] * 16, $precision); // 1/6 inch = 96px/6 in CSS
143
+                break;
144
+            case 'cm':
145
+                return round($m[1] * 96 / 2.54, $precision); // 96px / 2.54cm;
146
+                break;
147
+            case 'mm':
148
+                return round($m[1] * 96 / 25.4, $precision); // 96px / 25.4mm;
149
+                break;
150
+            case 'in':
151
+                return round($m[1] * 96, $precision); // 1 inch = 96px in CSS
152
+                break;
153
+            case 'px':
154
+            case 'pt':
155
+            default:
156
+                return $m[1];
157
+                break;
158
+        }
159
+    }
160
+    return false;
161 161
 }
162 162
 
163 163
 /**
@@ -168,15 +168,15 @@  discard block
 block discarded – undo
168 168
  * @return string
169 169
  */
170 170
 function svg_change_balise_svg($svg, $old_balise_svg, $attributs) {
171
-	$new_balise_svg = '<svg';
172
-	foreach ($attributs as $k => $v) {
173
-		$new_balise_svg .= " $k=\"" . entites_html($v) . '"';
174
-	}
175
-	$new_balise_svg .= '>';
176
-
177
-	$p = strpos($svg, $old_balise_svg);
178
-	$svg = substr_replace($svg, $new_balise_svg, $p, strlen($old_balise_svg));
179
-	return $svg;
171
+    $new_balise_svg = '<svg';
172
+    foreach ($attributs as $k => $v) {
173
+        $new_balise_svg .= " $k=\"" . entites_html($v) . '"';
174
+    }
175
+    $new_balise_svg .= '>';
176
+
177
+    $p = strpos($svg, $old_balise_svg);
178
+    $svg = substr_replace($svg, $new_balise_svg, $p, strlen($old_balise_svg));
179
+    return $svg;
180 180
 }
181 181
 
182 182
 /**
@@ -188,15 +188,15 @@  discard block
 block discarded – undo
188 188
  */
189 189
 function svg_insert_shapes($svg, $shapes, $start = true) {
190 190
 
191
-	if ($start === false or $start === 'end') {
192
-		$svg = str_replace('</svg>', $shapes . '</svg>', $svg);
193
-	}
194
-	else {
195
-		$p = stripos($svg, '<svg');
196
-		$p = strpos($svg, '>', $p);
197
-		$svg = substr_replace($svg, $shapes, $p + 1, 0);
198
-	}
199
-	return $svg;
191
+    if ($start === false or $start === 'end') {
192
+        $svg = str_replace('</svg>', $shapes . '</svg>', $svg);
193
+    }
194
+    else {
195
+        $p = stripos($svg, '<svg');
196
+        $p = strpos($svg, '>', $p);
197
+        $svg = substr_replace($svg, $shapes, $p + 1, 0);
198
+    }
199
+    return $svg;
200 200
 }
201 201
 
202 202
 /**
@@ -209,13 +209,13 @@  discard block
 block discarded – undo
209 209
  * @return string
210 210
  */
211 211
 function svg_clip_in_box($svg, $x, $y, $width, $height) {
212
-	$rect = "<rect x=\"$x\" y=\"$y\" width=\"$width\" height=\"$height\" />";
213
-	$id = 'clip-' . substr(md5($rect . strlen($svg)), 0, 8);
214
-	$clippath = "<clipPath id=\"$id\">$rect</clipPath>";
215
-	$g = "<g clip-path=\"url(#$id)\">";
216
-	$svg = svg_insert_shapes($svg, $clippath . $g);
217
-	$svg = svg_insert_shapes($svg, '</g>', false);
218
-	return $svg;
212
+    $rect = "<rect x=\"$x\" y=\"$y\" width=\"$width\" height=\"$height\" />";
213
+    $id = 'clip-' . substr(md5($rect . strlen($svg)), 0, 8);
214
+    $clippath = "<clipPath id=\"$id\">$rect</clipPath>";
215
+    $g = "<g clip-path=\"url(#$id)\">";
216
+    $svg = svg_insert_shapes($svg, $clippath . $g);
217
+    $svg = svg_insert_shapes($svg, '</g>', false);
218
+    return $svg;
219 219
 }
220 220
 
221 221
 /**
@@ -226,22 +226,22 @@  discard block
 block discarded – undo
226 226
  * @return bool|string
227 227
  */
228 228
 function svg_redimensionner($img, $new_width, $new_height) {
229
-	if (
230
-		$svg = svg_charger($img)
231
-		and $svg_infos = svg_lire_balise_svg($svg)
232
-	) {
233
-		[$balise_svg, $attributs] = $svg_infos;
234
-		if (!isset($attributs['viewBox'])) {
235
-			$attributs['viewBox'] = '0 0 ' . $attributs['width'] . ' ' . $attributs['height'];
236
-		}
237
-		$attributs['width'] = strval($new_width);
238
-		$attributs['height'] = strval($new_height);
239
-
240
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
241
-		return $svg;
242
-	}
243
-
244
-	return $img;
229
+    if (
230
+        $svg = svg_charger($img)
231
+        and $svg_infos = svg_lire_balise_svg($svg)
232
+    ) {
233
+        [$balise_svg, $attributs] = $svg_infos;
234
+        if (!isset($attributs['viewBox'])) {
235
+            $attributs['viewBox'] = '0 0 ' . $attributs['width'] . ' ' . $attributs['height'];
236
+        }
237
+        $attributs['width'] = strval($new_width);
238
+        $attributs['height'] = strval($new_height);
239
+
240
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
241
+        return $svg;
242
+    }
243
+
244
+    return $img;
245 245
 }
246 246
 
247 247
 /**
@@ -250,15 +250,15 @@  discard block
 block discarded – undo
250 250
  * @return string
251 251
  */
252 252
 function svg_couleur_to_hexa($couleur) {
253
-	if (strpos($couleur, 'rgb(') === 0) {
254
-		$c = explode(',', substr($couleur, 4));
255
-		$couleur = _couleur_dec_to_hex(intval($c[0]), intval($c[1]), intval($c[2]));
256
-	}
257
-	else {
258
-		$couleur = couleur_html_to_hex($couleur);
259
-	}
260
-	$couleur = '#' . ltrim($couleur, '#');
261
-	return $couleur;
253
+    if (strpos($couleur, 'rgb(') === 0) {
254
+        $c = explode(',', substr($couleur, 4));
255
+        $couleur = _couleur_dec_to_hex(intval($c[0]), intval($c[1]), intval($c[2]));
256
+    }
257
+    else {
258
+        $couleur = couleur_html_to_hex($couleur);
259
+    }
260
+    $couleur = '#' . ltrim($couleur, '#');
261
+    return $couleur;
262 262
 }
263 263
 
264 264
 /**
@@ -267,11 +267,11 @@  discard block
 block discarded – undo
267 267
  * @return array
268 268
  */
269 269
 function svg_couleur_to_rgb($couleur) {
270
-	if (strpos($couleur, 'rgb(') === 0) {
271
-		$c = explode(',', substr($couleur, 4));
272
-		return ['red' => intval($c[0]),'green' => intval($c[1]),'blue' => intval($c[2])];
273
-	}
274
-	return _couleur_hex_to_dec($couleur);
270
+    if (strpos($couleur, 'rgb(') === 0) {
271
+        $c = explode(',', substr($couleur, 4));
272
+        return ['red' => intval($c[0]),'green' => intval($c[1]),'blue' => intval($c[2])];
273
+    }
274
+    return _couleur_hex_to_dec($couleur);
275 275
 }
276 276
 
277 277
 
@@ -281,70 +281,70 @@  discard block
 block discarded – undo
281 281
  * @return array
282 282
  */
283 283
 function svg_getimagesize_from_attr($attributs) {
284
-	$width = 350; // default width
285
-	$height = 150; // default height
286
-
287
-	$viewBox = "0 0 $width $height";
288
-	if (isset($attributs['viewBox'])) {
289
-		$viewBox = $attributs['viewBox'];
290
-		$viewBox = preg_replace(',\s+,', ' ', $viewBox);
291
-	}
292
-	// et on la convertit en px
293
-	$viewBox = explode(' ', $viewBox);
294
-	$viewBox = array_map('svg_dimension_to_pixels', $viewBox);
295
-	if (!$viewBox[2]) {
296
-		$viewBox[2] = $width;
297
-	}
298
-	if (!$viewBox[3]) {
299
-		$viewBox[3] = $height;
300
-	}
301
-
302
-	$coeff = 1;
303
-	if (
304
-		isset($attributs['width'])
305
-		and $w = svg_dimension_to_pixels($attributs['width'])
306
-	) {
307
-		$width = $w;
308
-	}
309
-	else {
310
-		// si on recupere la taille de la viewbox mais si la viewbox est petite on met un multiplicateur pour la taille finale
311
-		$width = $viewBox[2];
312
-		if ($width < 1) {
313
-			$coeff = max($coeff, 1000);
314
-		}
315
-		elseif ($width < 10) {
316
-			$coeff = max($coeff, 100);
317
-		}
318
-		elseif ($width < 100) {
319
-			$coeff = max($coeff, 10);
320
-		}
321
-	}
322
-	if (
323
-		isset($attributs['height'])
324
-		and $h = svg_dimension_to_pixels($attributs['height'])
325
-	) {
326
-		$height = $h;
327
-	}
328
-	else {
329
-		$height = $viewBox[3];
330
-		if ($height < 1) {
331
-			$coeff = max($coeff, 1000);
332
-		}
333
-		elseif ($height < 10) {
334
-			$coeff = max($coeff, 100);
335
-		}
336
-		elseif ($height < 100) {
337
-			$coeff = max($coeff, 10);
338
-		}
339
-	}
340
-
341
-	// arrondir le width et height en pixel in fine
342
-	$width = round($coeff * $width);
343
-	$height = round($coeff * $height);
344
-
345
-	$viewBox = implode(' ', $viewBox);
346
-
347
-	return [$width, $height, $viewBox];
284
+    $width = 350; // default width
285
+    $height = 150; // default height
286
+
287
+    $viewBox = "0 0 $width $height";
288
+    if (isset($attributs['viewBox'])) {
289
+        $viewBox = $attributs['viewBox'];
290
+        $viewBox = preg_replace(',\s+,', ' ', $viewBox);
291
+    }
292
+    // et on la convertit en px
293
+    $viewBox = explode(' ', $viewBox);
294
+    $viewBox = array_map('svg_dimension_to_pixels', $viewBox);
295
+    if (!$viewBox[2]) {
296
+        $viewBox[2] = $width;
297
+    }
298
+    if (!$viewBox[3]) {
299
+        $viewBox[3] = $height;
300
+    }
301
+
302
+    $coeff = 1;
303
+    if (
304
+        isset($attributs['width'])
305
+        and $w = svg_dimension_to_pixels($attributs['width'])
306
+    ) {
307
+        $width = $w;
308
+    }
309
+    else {
310
+        // si on recupere la taille de la viewbox mais si la viewbox est petite on met un multiplicateur pour la taille finale
311
+        $width = $viewBox[2];
312
+        if ($width < 1) {
313
+            $coeff = max($coeff, 1000);
314
+        }
315
+        elseif ($width < 10) {
316
+            $coeff = max($coeff, 100);
317
+        }
318
+        elseif ($width < 100) {
319
+            $coeff = max($coeff, 10);
320
+        }
321
+    }
322
+    if (
323
+        isset($attributs['height'])
324
+        and $h = svg_dimension_to_pixels($attributs['height'])
325
+    ) {
326
+        $height = $h;
327
+    }
328
+    else {
329
+        $height = $viewBox[3];
330
+        if ($height < 1) {
331
+            $coeff = max($coeff, 1000);
332
+        }
333
+        elseif ($height < 10) {
334
+            $coeff = max($coeff, 100);
335
+        }
336
+        elseif ($height < 100) {
337
+            $coeff = max($coeff, 10);
338
+        }
339
+    }
340
+
341
+    // arrondir le width et height en pixel in fine
342
+    $width = round($coeff * $width);
343
+    $height = round($coeff * $height);
344
+
345
+    $viewBox = implode(' ', $viewBox);
346
+
347
+    return [$width, $height, $viewBox];
348 348
 }
349 349
 
350 350
 /**
@@ -360,25 +360,25 @@  discard block
 block discarded – undo
360 360
  * @return string
361 361
  */
362 362
 function svg_force_viewBox_px($img, $force_width_and_height = false) {
363
-	if (
364
-		$svg = svg_charger($img)
365
-		and $svg_infos = svg_lire_balise_svg($svg)
366
-	) {
367
-		[$balise_svg, $attributs] = $svg_infos;
363
+    if (
364
+        $svg = svg_charger($img)
365
+        and $svg_infos = svg_lire_balise_svg($svg)
366
+    ) {
367
+        [$balise_svg, $attributs] = $svg_infos;
368 368
 
369
-		[$width, $height, $viewBox] = svg_getimagesize_from_attr($attributs);
369
+        [$width, $height, $viewBox] = svg_getimagesize_from_attr($attributs);
370 370
 
371
-		if ($force_width_and_height) {
372
-			$attributs['width'] = $width;
373
-			$attributs['height'] = $height;
374
-		}
371
+        if ($force_width_and_height) {
372
+            $attributs['width'] = $width;
373
+            $attributs['height'] = $height;
374
+        }
375 375
 
376
-		$attributs['viewBox'] = $viewBox;
376
+        $attributs['viewBox'] = $viewBox;
377 377
 
378
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
379
-		return $svg;
380
-	}
381
-	return $img;
378
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
379
+        return $svg;
380
+    }
381
+    return $img;
382 382
 }
383 383
 
384 384
 /**
@@ -387,12 +387,12 @@  discard block
 block discarded – undo
387 387
  * @return array|mixed
388 388
  */
389 389
 function svg_extract_couleurs($img) {
390
-	if ($svg = svg_charger($img)) {
391
-		if (preg_match_all('/(#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])|(rgb\([\s\d]+,[\s\d]+,[\s\d]+\))|(#[0-9a-f][0-9a-f][0-9a-f])/imS', $svg, $matches)) {
392
-			return $matches[0];
393
-		}
394
-	}
395
-	return [];
390
+    if ($svg = svg_charger($img)) {
391
+        if (preg_match_all('/(#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])|(rgb\([\s\d]+,[\s\d]+,[\s\d]+\))|(#[0-9a-f][0-9a-f][0-9a-f])/imS', $svg, $matches)) {
392
+            return $matches[0];
393
+        }
394
+    }
395
+    return [];
396 396
 }
397 397
 
398 398
 /**
@@ -403,58 +403,58 @@  discard block
 block discarded – undo
403 403
  * @return bool|string
404 404
  */
405 405
 function svg_recadrer($img, $new_width, $new_height, $offset_width, $offset_height, $background_color = '') {
406
-	if (
407
-		$svg = svg_force_viewBox_px($img)
408
-		and $svg_infos = svg_lire_balise_svg($svg)
409
-	) {
410
-		[$balise_svg, $attributs] = $svg_infos;
411
-		$viewBox = explode(' ', $attributs['viewBox']);
412
-
413
-		$viewport_w = $new_width;
414
-		$viewport_h = $new_height;
415
-		$viewport_ox = $offset_width;
416
-		$viewport_oy = $offset_height;
417
-
418
-		// si on a un width/height qui rescale, il faut rescaler
419
-		if (
420
-			isset($attributs['width'])
421
-			and $w = svg_dimension_to_pixels($attributs['width'])
422
-			and isset($attributs['height'])
423
-			and $h = svg_dimension_to_pixels($attributs['height'])
424
-		) {
425
-			$xscale = $viewBox[2] / $w;
426
-			$viewport_w = round($viewport_w * $xscale, 2);
427
-			$viewport_ox = round($viewport_ox * $xscale, 2);
428
-			$yscale = $viewBox[3] / $h;
429
-			$viewport_h = round($viewport_h * $yscale, 2);
430
-			$viewport_oy = round($viewport_oy * $yscale, 2);
431
-		}
432
-
433
-		if ($viewport_w > $viewBox[2] or $viewport_h > $viewBox[3]) {
434
-			$svg = svg_clip_in_box($svg, $viewBox[0], $viewBox[1], $viewBox[2], $viewBox[3]);
435
-		}
436
-
437
-		// maintenant on redefinit la viewBox
438
-		$viewBox[0] += $viewport_ox;
439
-		$viewBox[1] += $viewport_oy;
440
-		$viewBox[2] = $viewport_w;
441
-		$viewBox[3] = $viewport_h;
442
-
443
-		$attributs['viewBox'] = implode(' ', $viewBox);
444
-		$attributs['width'] = strval($new_width);
445
-		$attributs['height'] = strval($new_height);
446
-
447
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
448
-
449
-		// ajouter un background
450
-		if ($background_color and $background_color !== 'transparent') {
451
-			$svg = svg_ajouter_background($svg, $background_color);
452
-		}
453
-
454
-		return $svg;
455
-	}
456
-
457
-	return $img;
406
+    if (
407
+        $svg = svg_force_viewBox_px($img)
408
+        and $svg_infos = svg_lire_balise_svg($svg)
409
+    ) {
410
+        [$balise_svg, $attributs] = $svg_infos;
411
+        $viewBox = explode(' ', $attributs['viewBox']);
412
+
413
+        $viewport_w = $new_width;
414
+        $viewport_h = $new_height;
415
+        $viewport_ox = $offset_width;
416
+        $viewport_oy = $offset_height;
417
+
418
+        // si on a un width/height qui rescale, il faut rescaler
419
+        if (
420
+            isset($attributs['width'])
421
+            and $w = svg_dimension_to_pixels($attributs['width'])
422
+            and isset($attributs['height'])
423
+            and $h = svg_dimension_to_pixels($attributs['height'])
424
+        ) {
425
+            $xscale = $viewBox[2] / $w;
426
+            $viewport_w = round($viewport_w * $xscale, 2);
427
+            $viewport_ox = round($viewport_ox * $xscale, 2);
428
+            $yscale = $viewBox[3] / $h;
429
+            $viewport_h = round($viewport_h * $yscale, 2);
430
+            $viewport_oy = round($viewport_oy * $yscale, 2);
431
+        }
432
+
433
+        if ($viewport_w > $viewBox[2] or $viewport_h > $viewBox[3]) {
434
+            $svg = svg_clip_in_box($svg, $viewBox[0], $viewBox[1], $viewBox[2], $viewBox[3]);
435
+        }
436
+
437
+        // maintenant on redefinit la viewBox
438
+        $viewBox[0] += $viewport_ox;
439
+        $viewBox[1] += $viewport_oy;
440
+        $viewBox[2] = $viewport_w;
441
+        $viewBox[3] = $viewport_h;
442
+
443
+        $attributs['viewBox'] = implode(' ', $viewBox);
444
+        $attributs['width'] = strval($new_width);
445
+        $attributs['height'] = strval($new_height);
446
+
447
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
448
+
449
+        // ajouter un background
450
+        if ($background_color and $background_color !== 'transparent') {
451
+            $svg = svg_ajouter_background($svg, $background_color);
452
+        }
453
+
454
+        return $svg;
455
+    }
456
+
457
+    return $img;
458 458
 }
459 459
 
460 460
 /**
@@ -464,26 +464,26 @@  discard block
 block discarded – undo
464 464
  * @return bool|string
465 465
  */
466 466
 function svg_ajouter_background($img, $background_color) {
467
-	if (
468
-		$svg = svg_charger($img)
469
-		and $svg_infos = svg_lire_balise_svg($svg)
470
-	) {
471
-		if ($background_color and $background_color !== 'transparent') {
472
-			[$balise_svg, $attributs] = $svg_infos;
473
-
474
-			$background_color = svg_couleur_to_hexa($background_color);
475
-			if (isset($attributs['viewBox'])) {
476
-				$viewBox = explode(' ', $attributs['viewBox']);
477
-				$rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\"/>";
478
-			}
479
-			else {
480
-				$rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
481
-			}
482
-			$svg = svg_insert_shapes($svg, $rect);
483
-		}
484
-		return $svg;
485
-	}
486
-	return $img;
467
+    if (
468
+        $svg = svg_charger($img)
469
+        and $svg_infos = svg_lire_balise_svg($svg)
470
+    ) {
471
+        if ($background_color and $background_color !== 'transparent') {
472
+            [$balise_svg, $attributs] = $svg_infos;
473
+
474
+            $background_color = svg_couleur_to_hexa($background_color);
475
+            if (isset($attributs['viewBox'])) {
476
+                $viewBox = explode(' ', $attributs['viewBox']);
477
+                $rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\"/>";
478
+            }
479
+            else {
480
+                $rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
481
+            }
482
+            $svg = svg_insert_shapes($svg, $rect);
483
+        }
484
+        return $svg;
485
+    }
486
+    return $img;
487 487
 }
488 488
 
489 489
 
@@ -494,26 +494,26 @@  discard block
 block discarded – undo
494 494
  * @return bool|string
495 495
  */
496 496
 function svg_ajouter_voile($img, $background_color, $opacity) {
497
-	if (
498
-		$svg = svg_charger($img)
499
-		and $svg_infos = svg_lire_balise_svg($svg)
500
-	) {
501
-		if ($background_color and $background_color !== 'transparent') {
502
-			[$balise_svg, $attributs] = $svg_infos;
503
-
504
-			$background_color = svg_couleur_to_hexa($background_color);
505
-			if (isset($attributs['viewBox'])) {
506
-				$viewBox = explode(' ', $attributs['viewBox']);
507
-				$rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\" opacity=\"$opacity\"/>";
508
-			}
509
-			else {
510
-				$rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
511
-			}
512
-			$svg = svg_insert_shapes($svg, $rect, false);
513
-		}
514
-		return $svg;
515
-	}
516
-	return $img;
497
+    if (
498
+        $svg = svg_charger($img)
499
+        and $svg_infos = svg_lire_balise_svg($svg)
500
+    ) {
501
+        if ($background_color and $background_color !== 'transparent') {
502
+            [$balise_svg, $attributs] = $svg_infos;
503
+
504
+            $background_color = svg_couleur_to_hexa($background_color);
505
+            if (isset($attributs['viewBox'])) {
506
+                $viewBox = explode(' ', $attributs['viewBox']);
507
+                $rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\" opacity=\"$opacity\"/>";
508
+            }
509
+            else {
510
+                $rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
511
+            }
512
+            $svg = svg_insert_shapes($svg, $rect, false);
513
+        }
514
+        return $svg;
515
+    }
516
+    return $img;
517 517
 }
518 518
 
519 519
 
@@ -524,27 +524,27 @@  discard block
 block discarded – undo
524 524
  * @return bool|string
525 525
  */
526 526
 function svg_transformer($img, $attributs) {
527
-	if (
528
-		$svg = svg_charger($img)
529
-		and $svg_infos = svg_lire_balise_svg($svg)
530
-	) {
531
-		if ($attributs) {
532
-			[$balise_svg, ] = $svg_infos;
533
-			$g = '<g';
534
-			foreach ($attributs as $k => $v) {
535
-				if (strlen($v)) {
536
-					$g .= " $k=\"" . attribut_html($v) . '"';
537
-				}
538
-			}
539
-			if (strlen($g) > 2) {
540
-				$g .= '>';
541
-				$svg = svg_insert_shapes($svg, $g);
542
-				$svg = svg_insert_shapes($svg, '</g>', false);
543
-			}
544
-		}
545
-		return $svg;
546
-	}
547
-	return $img;
527
+    if (
528
+        $svg = svg_charger($img)
529
+        and $svg_infos = svg_lire_balise_svg($svg)
530
+    ) {
531
+        if ($attributs) {
532
+            [$balise_svg, ] = $svg_infos;
533
+            $g = '<g';
534
+            foreach ($attributs as $k => $v) {
535
+                if (strlen($v)) {
536
+                    $g .= " $k=\"" . attribut_html($v) . '"';
537
+                }
538
+            }
539
+            if (strlen($g) > 2) {
540
+                $g .= '>';
541
+                $svg = svg_insert_shapes($svg, $g);
542
+                $svg = svg_insert_shapes($svg, '</g>', false);
543
+            }
544
+        }
545
+        return $svg;
546
+    }
547
+    return $img;
548 548
 }
549 549
 
550 550
 /**
@@ -555,21 +555,21 @@  discard block
 block discarded – undo
555 555
  * @return bool|string
556 556
  */
557 557
 function svg_apply_filter($img, $filter_def) {
558
-	if (
559
-		$svg = svg_charger($img)
560
-		and $svg_infos = svg_lire_balise_svg($svg)
561
-	) {
562
-		if ($filter_def) {
563
-			[$balise_svg, ] = $svg_infos;
564
-			$filter_id = 'filter-' . substr(md5($filter_def . strlen($svg)), 0, 8);
565
-			$filter = "<defs><filter id=\"$filter_id\">$filter_def</filter></defs>";
566
-			$g = "<g filter=\"url(#$filter_id)\">";
567
-			$svg = svg_insert_shapes($svg, $filter . $g);
568
-			$svg = svg_insert_shapes($svg, '</g>', false);
569
-		}
570
-		return $svg;
571
-	}
572
-	return $img;
558
+    if (
559
+        $svg = svg_charger($img)
560
+        and $svg_infos = svg_lire_balise_svg($svg)
561
+    ) {
562
+        if ($filter_def) {
563
+            [$balise_svg, ] = $svg_infos;
564
+            $filter_id = 'filter-' . substr(md5($filter_def . strlen($svg)), 0, 8);
565
+            $filter = "<defs><filter id=\"$filter_id\">$filter_def</filter></defs>";
566
+            $g = "<g filter=\"url(#$filter_id)\">";
567
+            $svg = svg_insert_shapes($svg, $filter . $g);
568
+            $svg = svg_insert_shapes($svg, '</g>', false);
569
+        }
570
+        return $svg;
571
+    }
572
+    return $img;
573 573
 }
574 574
 
575 575
 /**
@@ -579,8 +579,8 @@  discard block
 block discarded – undo
579 579
  * @return string
580 580
  */
581 581
 function svg_filter_blur($img, $blur_width) {
582
-	$blur_width = intval($blur_width);
583
-	return svg_apply_filter($img, "<feGaussianBlur stdDeviation=\"$blur_width\"/>");
582
+    $blur_width = intval($blur_width);
583
+    return svg_apply_filter($img, "<feGaussianBlur stdDeviation=\"$blur_width\"/>");
584 584
 }
585 585
 
586 586
 /**
@@ -590,10 +590,10 @@  discard block
 block discarded – undo
590 590
  * @return bool|string
591 591
  */
592 592
 function svg_filter_grayscale($img, $intensity) {
593
-	$value = round(1.0 - $intensity, 2);
594
-	//$filter = "<feColorMatrix type=\"matrix\" values=\"0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\"/>";
595
-	$filter = "<feColorMatrix type=\"saturate\" values=\"$value\"/>";
596
-	return svg_apply_filter($img, $filter);
593
+    $value = round(1.0 - $intensity, 2);
594
+    //$filter = "<feColorMatrix type=\"matrix\" values=\"0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\"/>";
595
+    $filter = "<feColorMatrix type=\"saturate\" values=\"$value\"/>";
596
+    return svg_apply_filter($img, $filter);
597 597
 }
598 598
 
599 599
 /**
@@ -603,8 +603,8 @@  discard block
 block discarded – undo
603 603
  * @return bool|string
604 604
  */
605 605
 function svg_filter_sepia($img, $intensity) {
606
-	$filter = '<feColorMatrix type="matrix" values="0.30 0.30 0.30 0.0 0 0.25 0.25 0.25 0.0 0 0.20 0.20 0.20 0.0 0 0.00 0.00 0.00 1 0"/>';
607
-	return svg_apply_filter($img, $filter);
606
+    $filter = '<feColorMatrix type="matrix" values="0.30 0.30 0.30 0.0 0 0.25 0.25 0.25 0.0 0 0.20 0.20 0.20 0.0 0 0.00 0.00 0.00 1 0"/>';
607
+    return svg_apply_filter($img, $filter);
608 608
 }
609 609
 
610 610
 /**
@@ -614,31 +614,31 @@  discard block
 block discarded – undo
614 614
  * @return bool|string
615 615
  */
616 616
 function svg_flip($img, $HorV) {
617
-	if (
618
-		$svg = svg_force_viewBox_px($img)
619
-		and $svg_infos = svg_lire_balise_svg($svg)
620
-	) {
621
-		[$balise_svg, $atts] = $svg_infos;
622
-		$viewBox = explode(' ', $atts['viewBox']);
623
-
624
-		if (!in_array($HorV, ['h', 'H'])) {
625
-			$transform = 'scale(-1,1)';
626
-
627
-			$x = intval($viewBox[0]) + intval($viewBox[2] / 2);
628
-			$mx = -$x;
629
-			$transform = "translate($x, 0) $transform translate($mx, 0)";
630
-		}
631
-		else {
632
-			$transform = 'scale(1,-1)';
633
-
634
-			$y = intval($viewBox[1]) + intval($viewBox[3] / 2);
635
-			$my = -$y;
636
-			$transform = "translate(0, $y) $transform translate(0, $my)";
637
-		}
638
-		$svg = svg_transformer($svg, ['transform' => $transform]);
639
-		return $svg;
640
-	}
641
-	return $img;
617
+    if (
618
+        $svg = svg_force_viewBox_px($img)
619
+        and $svg_infos = svg_lire_balise_svg($svg)
620
+    ) {
621
+        [$balise_svg, $atts] = $svg_infos;
622
+        $viewBox = explode(' ', $atts['viewBox']);
623
+
624
+        if (!in_array($HorV, ['h', 'H'])) {
625
+            $transform = 'scale(-1,1)';
626
+
627
+            $x = intval($viewBox[0]) + intval($viewBox[2] / 2);
628
+            $mx = -$x;
629
+            $transform = "translate($x, 0) $transform translate($mx, 0)";
630
+        }
631
+        else {
632
+            $transform = 'scale(1,-1)';
633
+
634
+            $y = intval($viewBox[1]) + intval($viewBox[3] / 2);
635
+            $my = -$y;
636
+            $transform = "translate(0, $y) $transform translate(0, $my)";
637
+        }
638
+        $svg = svg_transformer($svg, ['transform' => $transform]);
639
+        return $svg;
640
+    }
641
+    return $img;
642 642
 }
643 643
 
644 644
 /**
@@ -652,20 +652,20 @@  discard block
 block discarded – undo
652 652
  * @return bool|string
653 653
  */
654 654
 function svg_rotate($img, $angle, $center_x, $center_y) {
655
-	if (
656
-		$svg = svg_force_viewBox_px($img)
657
-		and $svg_infos = svg_lire_balise_svg($svg)
658
-	) {
659
-		[$balise_svg, $atts] = $svg_infos;
660
-		$viewBox = explode(' ', $atts['viewBox']);
661
-
662
-		$center_x = round($viewBox[0] + $center_x * $viewBox[2]);
663
-		$center_y = round($viewBox[1] + $center_y * $viewBox[3]);
664
-		$svg = svg_transformer($svg, ['transform' => "rotate($angle $center_x $center_y)"]);
665
-
666
-		return $svg;
667
-	}
668
-	return $img;
655
+    if (
656
+        $svg = svg_force_viewBox_px($img)
657
+        and $svg_infos = svg_lire_balise_svg($svg)
658
+    ) {
659
+        [$balise_svg, $atts] = $svg_infos;
660
+        $viewBox = explode(' ', $atts['viewBox']);
661
+
662
+        $center_x = round($viewBox[0] + $center_x * $viewBox[2]);
663
+        $center_y = round($viewBox[1] + $center_y * $viewBox[3]);
664
+        $svg = svg_transformer($svg, ['transform' => "rotate($angle $center_x $center_y)"]);
665
+
666
+        return $svg;
667
+    }
668
+    return $img;
669 669
 }
670 670
 
671 671
 /**
@@ -677,41 +677,41 @@  discard block
 block discarded – undo
677 677
  * @return bool|mixed|string
678 678
  */
679 679
 function svg_filtrer_couleurs($img, $callback_filter) {
680
-	if (
681
-		$svg = svg_force_viewBox_px($img)
682
-		and $colors = svg_extract_couleurs($svg)
683
-	) {
684
-		$colors = array_unique($colors);
685
-
686
-		$short = [];
687
-		$long = [];
688
-		while (count($colors)) {
689
-			$c = array_shift($colors);
690
-			if (strlen($c) == 4) {
691
-				$short[] = $c;
692
-			}
693
-			else {
694
-				$long[] = $c;
695
-			}
696
-		}
697
-
698
-		$colors = [...$long, ...$short];
699
-		$new_colors = [];
700
-		$colors = array_flip($colors);
701
-		foreach ($colors as $c => $k) {
702
-			$colors[$c] = "@@@COLOR$$k$@@@";
703
-		}
704
-
705
-
706
-		foreach ($colors as $original => $replace) {
707
-			$new = svg_couleur_to_hexa($original);
708
-			$new_colors[$replace] = $callback_filter($new);
709
-		}
710
-
711
-		$svg = str_replace(array_keys($colors), array_values($colors), $svg);
712
-		$svg = str_replace(array_keys($new_colors), array_values($new_colors), $svg);
713
-
714
-		return $svg;
715
-	}
716
-	return $img;
680
+    if (
681
+        $svg = svg_force_viewBox_px($img)
682
+        and $colors = svg_extract_couleurs($svg)
683
+    ) {
684
+        $colors = array_unique($colors);
685
+
686
+        $short = [];
687
+        $long = [];
688
+        while (count($colors)) {
689
+            $c = array_shift($colors);
690
+            if (strlen($c) == 4) {
691
+                $short[] = $c;
692
+            }
693
+            else {
694
+                $long[] = $c;
695
+            }
696
+        }
697
+
698
+        $colors = [...$long, ...$short];
699
+        $new_colors = [];
700
+        $colors = array_flip($colors);
701
+        foreach ($colors as $c => $k) {
702
+            $colors[$c] = "@@@COLOR$$k$@@@";
703
+        }
704
+
705
+
706
+        foreach ($colors as $original => $replace) {
707
+            $new = svg_couleur_to_hexa($original);
708
+            $new_colors[$replace] = $callback_filter($new);
709
+        }
710
+
711
+        $svg = str_replace(array_keys($colors), array_values($colors), $svg);
712
+        $svg = str_replace(array_keys($new_colors), array_values($new_colors), $svg);
713
+
714
+        return $svg;
715
+    }
716
+    return $img;
717 717
 }
Please login to merge, or discard this patch.
ecrire/inc/informer.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -11,74 +11,74 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 # Les information d'une rubrique selectionnee dans le mini navigateur
18 18
 
19 19
 // https://code.spip.net/@inc_informer_dist
20 20
 function inc_informer_dist($id, $col, $exclus, $rac, $type, $do = 'aff') {
21
-	include_spip('inc/texte');
22
-	$titre = $descriptif = '';
23
-	if ($type == 'rubrique') {
24
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
25
-		if ($row) {
26
-			$titre = typo($row['titre']);
27
-			$descriptif = propre($row['descriptif']);
28
-		} else {
29
-			$titre = _T('info_racine_site');
30
-		}
31
-	}
21
+    include_spip('inc/texte');
22
+    $titre = $descriptif = '';
23
+    if ($type == 'rubrique') {
24
+        $row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
25
+        if ($row) {
26
+            $titre = typo($row['titre']);
27
+            $descriptif = propre($row['descriptif']);
28
+        } else {
29
+            $titre = _T('info_racine_site');
30
+        }
31
+    }
32 32
 
33
-	$res = '';
34
-	if ($type == 'rubrique' and $GLOBALS['spip_display'] != 1 and isset($GLOBALS['meta']['image_process'])) {
35
-		if ($GLOBALS['meta']['image_process'] != 'non') {
36
-			$chercher_logo = charger_fonction('chercher_logo', 'inc');
37
-			if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
38
-				[$fid, $dir, $nom, $format] = $res;
39
-				include_spip('inc/filtres_images_mini');
40
-				$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
41
-				if ($res) {
42
-					$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
43
-				}
44
-			}
45
-		}
46
-	}
33
+    $res = '';
34
+    if ($type == 'rubrique' and $GLOBALS['spip_display'] != 1 and isset($GLOBALS['meta']['image_process'])) {
35
+        if ($GLOBALS['meta']['image_process'] != 'non') {
36
+            $chercher_logo = charger_fonction('chercher_logo', 'inc');
37
+            if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
38
+                [$fid, $dir, $nom, $format] = $res;
39
+                include_spip('inc/filtres_images_mini');
40
+                $res = image_reduire("<img src='$fid' alt='' />", 100, 48);
41
+                if ($res) {
42
+                    $res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
43
+                }
44
+            }
45
+        }
46
+    }
47 47
 
48
-	$rac = spip_htmlentities($rac, ENT_QUOTES);
49
-	$do = spip_htmlentities($do, ENT_QUOTES);
50
-	$id = intval($id);
48
+    $rac = spip_htmlentities($rac, ENT_QUOTES);
49
+    $do = spip_htmlentities($do, ENT_QUOTES);
50
+    $id = intval($id);
51 51
 
52 52
 # ce lien provoque la selection (directe) de la rubrique cliquee
53 53
 # et l'affichage de son titre dans le bandeau
54
-	$titre = strtr(
55
-		str_replace(
56
-			"'",
57
-			'&#8217;',
58
-			str_replace('"', '&#34;', textebrut($titre))
59
-		),
60
-		"\n\r",
61
-		'  '
62
-	);
54
+    $titre = strtr(
55
+        str_replace(
56
+            "'",
57
+            '&#8217;',
58
+            str_replace('"', '&#34;', textebrut($titre))
59
+        ),
60
+        "\n\r",
61
+        '  '
62
+    );
63 63
 
64
-	$js_func = $do . '_selection_titre';
64
+    $js_func = $do . '_selection_titre';
65 65
 
66
-	return "<div style='display: none;'>"
67
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
68
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
69
-	. entites_html($titre)
70
-	. '" />'
71
-	. '</div>'
72
-	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
73
-	. '<div class="informer__item">'
74
-	. (!$res ? '' : $res)
75
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
76
-	. (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
77
-	. '</div>'
78
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
79
-	. "<input type='submit' class='fondo btn submit' value='"
80
-	. _T('bouton_choisir')
81
-	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
82
-	. '</div>'
83
-	. '</div>';
66
+    return "<div style='display: none;'>"
67
+    . "<input type='text' id='" . $rac . "_sel' value='$id' />"
68
+    . "<input type='text' id='" . $rac . "_sel2' value=\""
69
+    . entites_html($titre)
70
+    . '" />'
71
+    . '</div>'
72
+    . "<div class='informer' style='padding: 5px; border-top: 0px;'>"
73
+    . '<div class="informer__item">'
74
+    . (!$res ? '' : $res)
75
+    . "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
76
+    . (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
77
+    . '</div>'
78
+    . "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
79
+    . "<input type='submit' class='fondo btn submit' value='"
80
+    . _T('bouton_choisir')
81
+    . "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
82
+    . '</div>'
83
+    . '</div>';
84 84
 }
Please login to merge, or discard this patch.
ecrire/inc/rechercher.php 1 patch
Indentation   +317 added lines, -317 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
 defined('_RECHERCHE_LOCK_KEY') || define('_RECHERCHE_LOCK_KEY', 'fulltext');
@@ -35,22 +35,22 @@  discard block
 block discarded – undo
35 35
  * @return array Couples (type d'objet => Couples (champ => score))
36 36
  */
37 37
 function liste_des_champs() {
38
-	static $liste = null;
39
-	if (is_null($liste)) {
40
-		$liste = [];
41
-		// recuperer les tables_objets_sql declarees
42
-		include_spip('base/objets');
43
-		$tables_objets = lister_tables_objets_sql();
44
-		foreach ($tables_objets as $t => $infos) {
45
-			if ($infos['rechercher_champs']) {
46
-				$liste[$infos['type']] = $infos['rechercher_champs'];
47
-			}
48
-		}
49
-		// puis passer dans le pipeline
50
-		$liste = pipeline('rechercher_liste_des_champs', $liste);
51
-	}
52
-
53
-	return $liste;
38
+    static $liste = null;
39
+    if (is_null($liste)) {
40
+        $liste = [];
41
+        // recuperer les tables_objets_sql declarees
42
+        include_spip('base/objets');
43
+        $tables_objets = lister_tables_objets_sql();
44
+        foreach ($tables_objets as $t => $infos) {
45
+            if ($infos['rechercher_champs']) {
46
+                $liste[$infos['type']] = $infos['rechercher_champs'];
47
+            }
48
+        }
49
+        // puis passer dans le pipeline
50
+        $liste = pipeline('rechercher_liste_des_champs', $liste);
51
+    }
52
+
53
+    return $liste;
54 54
 }
55 55
 
56 56
 
@@ -58,176 +58,176 @@  discard block
 block discarded – undo
58 58
 // en ne regardant que le titre ou le nom
59 59
 // https://code.spip.net/@liste_des_jointures
60 60
 function liste_des_jointures() {
61
-	static $liste = null;
62
-	if (is_null($liste)) {
63
-		$liste = [];
64
-		// recuperer les tables_objets_sql declarees
65
-		include_spip('base/objets');
66
-		$tables_objets = lister_tables_objets_sql();
67
-		foreach ($tables_objets as $t => $infos) {
68
-			if ($infos['rechercher_jointures']) {
69
-				$liste[$infos['type']] = $infos['rechercher_jointures'];
70
-			}
71
-		}
72
-		// puis passer dans le pipeline
73
-		$liste = pipeline('rechercher_liste_des_jointures', $liste);
74
-	}
75
-
76
-	return $liste;
61
+    static $liste = null;
62
+    if (is_null($liste)) {
63
+        $liste = [];
64
+        // recuperer les tables_objets_sql declarees
65
+        include_spip('base/objets');
66
+        $tables_objets = lister_tables_objets_sql();
67
+        foreach ($tables_objets as $t => $infos) {
68
+            if ($infos['rechercher_jointures']) {
69
+                $liste[$infos['type']] = $infos['rechercher_jointures'];
70
+            }
71
+        }
72
+        // puis passer dans le pipeline
73
+        $liste = pipeline('rechercher_liste_des_jointures', $liste);
74
+    }
75
+
76
+    return $liste;
77 77
 }
78 78
 
79 79
 function expression_recherche($recherche, $options) {
80
-	// ne calculer qu'une seule fois l'expression par hit
81
-	// (meme si utilisee dans plusieurs boucles)
82
-	static $expression = [];
83
-	$key = serialize([$recherche, $options['preg_flags']]);
84
-	if (isset($expression[$key])) {
85
-		return $expression[$key];
86
-	}
87
-
88
-	$u = $GLOBALS['meta']['pcre_u'];
89
-	if ($u and strpos($options['preg_flags'], (string) $u) === false) {
90
-		$options['preg_flags'] .= $u;
91
-	}
92
-	include_spip('inc/charsets');
93
-	$recherche = trim($recherche);
94
-
95
-	// retirer les + de +truc et les * de truc*
96
-	$recherche = preg_replace(',(^|\s)\+(\w),Uims', '$1$2', $recherche);
97
-	$recherche = preg_replace(',(\w)\*($|\s),Uims', '$1$2', $recherche);
98
-
99
-	$is_preg = false;
100
-	if (substr($recherche, 0, 1) == '/' and substr($recherche, -1, 1) == '/' and strlen($recherche) > 2) {
101
-		// c'est une preg
102
-		$recherche_trans = translitteration($recherche);
103
-		$preg = $recherche_trans . $options['preg_flags'];
104
-		$is_preg = true;
105
-	} else {
106
-		// s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP,
107
-		// sauf ceux de moins de 4 lettres (on supprime ainsi 'le', 'les', 'un',
108
-		// 'une', 'des' ...)
109
-
110
-		// attention : plusieurs mots entre guillemets sont a rechercher tels quels
111
-		$recherche_trans = $recherche_mod = $recherche_org = $recherche;
112
-
113
-		// les expressions entre " " sont un mot a chercher tel quel
114
-		// -> on remplace les espaces par un \x1 et on enleve les guillemets
115
-		if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
116
-			foreach ($matches as $match) {
117
-				$word = preg_replace(',\s+,Uims', "\x1", $match);
118
-				$word = trim($word, '"');
119
-				$recherche_mod = str_replace($match, $word, $recherche_mod);
120
-			}
121
-		}
122
-
123
-		if (preg_match(',\s+,' . $u, $recherche_mod)) {
124
-			$is_preg = true;
125
-
126
-			$recherche_inter = '|';
127
-			$recherche_mots = explode(' ', $recherche_mod);
128
-			$min_long = defined('_RECHERCHE_MIN_CAR') ? _RECHERCHE_MIN_CAR : 4;
129
-			$petits_mots = true;
130
-			foreach ($recherche_mots as $mot) {
131
-				if (strlen($mot) >= $min_long) {
132
-					// echapper les caracteres de regexp qui sont eventuellement dans la recherche
133
-					$recherche_inter .= preg_quote($mot) . ' ';
134
-					$petits_mots = false;
135
-				}
136
-			}
137
-			$recherche_inter = str_replace("\x1", '\s', $recherche_inter);
138
-
139
-			// mais on cherche quand même l'expression complète, même si elle
140
-			// comporte des mots de moins de quatre lettres
141
-			$recherche = trim(preg_replace(',\s+,' . $u, '|', $recherche_inter), '|');
142
-			if (!$recherche or $petits_mots) {
143
-				$recherche = preg_quote($recherche_org);
144
-			}
145
-			$recherche_trans = translitteration($recherche);
146
-		}
147
-
148
-		$preg = '/' . str_replace('/', '\\/', $recherche_trans) . '/' . $options['preg_flags'];
149
-	}
150
-
151
-	// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
152
-	// ou si l'expression reguliere est invalide
153
-	if (
154
-		!$is_preg
155
-		or (@preg_match($preg, '') === false)
156
-	) {
157
-		$methode = 'LIKE';
158
-		$u = $GLOBALS['meta']['pcre_u'];
159
-
160
-		// echapper les % et _
161
-		$q = str_replace(['%', '_'], ['\%', '\_'], trim($recherche));
162
-
163
-		// eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
164
-		$recherche = preg_quote($recherche, '/');
165
-		$recherche_trans = translitteration($recherche);
166
-		$recherche_mod = $recherche_trans;
167
-
168
-		// les expressions entre " " sont un mot a chercher tel quel
169
-		// -> on remplace les espaces par un _ et on enleve les guillemets
170
-		// corriger le like dans le $q
171
-		if (preg_match(',["][^"]+["],Uims', $q, $matches)) {
172
-			foreach ($matches as $match) {
173
-				$word = preg_replace(',\s+,Uims', '_', $match);
174
-				$word = trim($word, '"');
175
-				$q = str_replace($match, $word, $q);
176
-			}
177
-		}
178
-		// corriger la regexp
179
-		if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
180
-			foreach ($matches as $match) {
181
-				$word = preg_replace(',\s+,Uims', '[\s]', $match);
182
-				$word = trim($word, '"');
183
-				$recherche_mod = str_replace($match, $word, $recherche_mod);
184
-			}
185
-		}
186
-		$q = sql_quote(
187
-			'%'
188
-			. preg_replace(',\s+,' . $u, '%', $q)
189
-			. '%'
190
-		);
191
-
192
-		$preg = '/' . preg_replace(',\s+,' . $u, '.+', trim($recherche_mod)) . '/' . $options['preg_flags'];
193
-	} else {
194
-		$methode = 'REGEXP';
195
-		$q = sql_quote(trim($recherche, '/'));
196
-	}
197
-
198
-	// tous les caracteres transliterables de $q sont remplaces par un joker
199
-	// permet de matcher en SQL meme si on est sensible aux accents (SQLite)
200
-	$q_t = $q;
201
-	for ($i = 0; $i < spip_strlen($q); $i++) {
202
-		$char = spip_substr($q, $i, 1);
203
-		if (
204
-			!is_ascii($char)
205
-			and $char_t = translitteration($char)
206
-			and $char_t !== $char
207
-		) {
208
-			// on utilise ..?.? car le char utf peut etre encode sur 1, 2 ou 3 bytes
209
-			// mais c'est un pis aller cf #4354
210
-			$q_t = str_replace($char, $is_preg ? '..?.?' : '_', $q_t);
211
-		}
212
-	}
213
-
214
-	$q = $q_t;
215
-
216
-	// fix : SQLite 3 est sensible aux accents, on jokerise les caracteres
217
-	// les plus frequents qui peuvent etre accentues
218
-	// (oui c'est tres dicustable...)
219
-	if (
220
-		isset($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'])
221
-		and strncmp($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'], 'sqlite', 6) == 0
222
-	) {
223
-		$q_t = strtr($q, 'aeuioc', $is_preg ? '......' : '______');
224
-		// si il reste au moins un char significatif...
225
-		if (preg_match(",[^'%_.],", $q_t)) {
226
-			$q = $q_t;
227
-		}
228
-	}
229
-
230
-	return $expression[$key] = [$methode, $q, $preg];
80
+    // ne calculer qu'une seule fois l'expression par hit
81
+    // (meme si utilisee dans plusieurs boucles)
82
+    static $expression = [];
83
+    $key = serialize([$recherche, $options['preg_flags']]);
84
+    if (isset($expression[$key])) {
85
+        return $expression[$key];
86
+    }
87
+
88
+    $u = $GLOBALS['meta']['pcre_u'];
89
+    if ($u and strpos($options['preg_flags'], (string) $u) === false) {
90
+        $options['preg_flags'] .= $u;
91
+    }
92
+    include_spip('inc/charsets');
93
+    $recherche = trim($recherche);
94
+
95
+    // retirer les + de +truc et les * de truc*
96
+    $recherche = preg_replace(',(^|\s)\+(\w),Uims', '$1$2', $recherche);
97
+    $recherche = preg_replace(',(\w)\*($|\s),Uims', '$1$2', $recherche);
98
+
99
+    $is_preg = false;
100
+    if (substr($recherche, 0, 1) == '/' and substr($recherche, -1, 1) == '/' and strlen($recherche) > 2) {
101
+        // c'est une preg
102
+        $recherche_trans = translitteration($recherche);
103
+        $preg = $recherche_trans . $options['preg_flags'];
104
+        $is_preg = true;
105
+    } else {
106
+        // s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP,
107
+        // sauf ceux de moins de 4 lettres (on supprime ainsi 'le', 'les', 'un',
108
+        // 'une', 'des' ...)
109
+
110
+        // attention : plusieurs mots entre guillemets sont a rechercher tels quels
111
+        $recherche_trans = $recherche_mod = $recherche_org = $recherche;
112
+
113
+        // les expressions entre " " sont un mot a chercher tel quel
114
+        // -> on remplace les espaces par un \x1 et on enleve les guillemets
115
+        if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
116
+            foreach ($matches as $match) {
117
+                $word = preg_replace(',\s+,Uims', "\x1", $match);
118
+                $word = trim($word, '"');
119
+                $recherche_mod = str_replace($match, $word, $recherche_mod);
120
+            }
121
+        }
122
+
123
+        if (preg_match(',\s+,' . $u, $recherche_mod)) {
124
+            $is_preg = true;
125
+
126
+            $recherche_inter = '|';
127
+            $recherche_mots = explode(' ', $recherche_mod);
128
+            $min_long = defined('_RECHERCHE_MIN_CAR') ? _RECHERCHE_MIN_CAR : 4;
129
+            $petits_mots = true;
130
+            foreach ($recherche_mots as $mot) {
131
+                if (strlen($mot) >= $min_long) {
132
+                    // echapper les caracteres de regexp qui sont eventuellement dans la recherche
133
+                    $recherche_inter .= preg_quote($mot) . ' ';
134
+                    $petits_mots = false;
135
+                }
136
+            }
137
+            $recherche_inter = str_replace("\x1", '\s', $recherche_inter);
138
+
139
+            // mais on cherche quand même l'expression complète, même si elle
140
+            // comporte des mots de moins de quatre lettres
141
+            $recherche = trim(preg_replace(',\s+,' . $u, '|', $recherche_inter), '|');
142
+            if (!$recherche or $petits_mots) {
143
+                $recherche = preg_quote($recherche_org);
144
+            }
145
+            $recherche_trans = translitteration($recherche);
146
+        }
147
+
148
+        $preg = '/' . str_replace('/', '\\/', $recherche_trans) . '/' . $options['preg_flags'];
149
+    }
150
+
151
+    // Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
152
+    // ou si l'expression reguliere est invalide
153
+    if (
154
+        !$is_preg
155
+        or (@preg_match($preg, '') === false)
156
+    ) {
157
+        $methode = 'LIKE';
158
+        $u = $GLOBALS['meta']['pcre_u'];
159
+
160
+        // echapper les % et _
161
+        $q = str_replace(['%', '_'], ['\%', '\_'], trim($recherche));
162
+
163
+        // eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
164
+        $recherche = preg_quote($recherche, '/');
165
+        $recherche_trans = translitteration($recherche);
166
+        $recherche_mod = $recherche_trans;
167
+
168
+        // les expressions entre " " sont un mot a chercher tel quel
169
+        // -> on remplace les espaces par un _ et on enleve les guillemets
170
+        // corriger le like dans le $q
171
+        if (preg_match(',["][^"]+["],Uims', $q, $matches)) {
172
+            foreach ($matches as $match) {
173
+                $word = preg_replace(',\s+,Uims', '_', $match);
174
+                $word = trim($word, '"');
175
+                $q = str_replace($match, $word, $q);
176
+            }
177
+        }
178
+        // corriger la regexp
179
+        if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
180
+            foreach ($matches as $match) {
181
+                $word = preg_replace(',\s+,Uims', '[\s]', $match);
182
+                $word = trim($word, '"');
183
+                $recherche_mod = str_replace($match, $word, $recherche_mod);
184
+            }
185
+        }
186
+        $q = sql_quote(
187
+            '%'
188
+            . preg_replace(',\s+,' . $u, '%', $q)
189
+            . '%'
190
+        );
191
+
192
+        $preg = '/' . preg_replace(',\s+,' . $u, '.+', trim($recherche_mod)) . '/' . $options['preg_flags'];
193
+    } else {
194
+        $methode = 'REGEXP';
195
+        $q = sql_quote(trim($recherche, '/'));
196
+    }
197
+
198
+    // tous les caracteres transliterables de $q sont remplaces par un joker
199
+    // permet de matcher en SQL meme si on est sensible aux accents (SQLite)
200
+    $q_t = $q;
201
+    for ($i = 0; $i < spip_strlen($q); $i++) {
202
+        $char = spip_substr($q, $i, 1);
203
+        if (
204
+            !is_ascii($char)
205
+            and $char_t = translitteration($char)
206
+            and $char_t !== $char
207
+        ) {
208
+            // on utilise ..?.? car le char utf peut etre encode sur 1, 2 ou 3 bytes
209
+            // mais c'est un pis aller cf #4354
210
+            $q_t = str_replace($char, $is_preg ? '..?.?' : '_', $q_t);
211
+        }
212
+    }
213
+
214
+    $q = $q_t;
215
+
216
+    // fix : SQLite 3 est sensible aux accents, on jokerise les caracteres
217
+    // les plus frequents qui peuvent etre accentues
218
+    // (oui c'est tres dicustable...)
219
+    if (
220
+        isset($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'])
221
+        and strncmp($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'], 'sqlite', 6) == 0
222
+    ) {
223
+        $q_t = strtr($q, 'aeuioc', $is_preg ? '......' : '______');
224
+        // si il reste au moins un char significatif...
225
+        if (preg_match(",[^'%_.],", $q_t)) {
226
+            $q = $q_t;
227
+        }
228
+    }
229
+
230
+    return $expression[$key] = [$methode, $q, $preg];
231 231
 }
232 232
 
233 233
 
@@ -254,143 +254,143 @@  discard block
 block discarded – undo
254 254
  * @return array
255 255
  */
256 256
 function recherche_en_base($recherche = '', $tables = null, $options = [], $serveur = '') {
257
-	include_spip('base/abstract_sql');
258
-
259
-	if (!is_array($tables)) {
260
-		$liste = liste_des_champs();
261
-
262
-		if (
263
-			is_string($tables)
264
-			and $tables != ''
265
-		) {
266
-			$toutes = [];
267
-			foreach (explode(',', $tables) as $t) {
268
-				$t = trim($t);
269
-				if (isset($liste[$t])) {
270
-					$toutes[$t] = $liste[$t];
271
-				}
272
-			}
273
-			$tables = $toutes;
274
-			unset($toutes);
275
-		} else {
276
-			$tables = $liste;
277
-		}
278
-	}
279
-
280
-	if (!strlen($recherche) or !count($tables)) {
281
-		return [];
282
-	}
283
-
284
-	include_spip('inc/autoriser');
285
-
286
-	// options par defaut
287
-	$options = array_merge(
288
-		[
289
-		'preg_flags' => 'UimsS',
290
-		'toutvoir' => false,
291
-		'champs' => false,
292
-		'score' => false,
293
-		'matches' => false,
294
-		'jointures' => false,
295
-		'serveur' => $serveur
296
-		],
297
-		$options
298
-	);
299
-
300
-	$results = [];
301
-
302
-	// Utiliser l'iterateur (DATA:recherche)
303
-	// pour recuperer les couples (id_objet, score)
304
-	// Le resultat est au format {
305
-	//      id1 = { 'score' => x, attrs => { } },
306
-	//      id2 = { 'score' => x, attrs => { } },
307
-	// }
308
-
309
-	include_spip('inc/recherche_to_array');
310
-
311
-	foreach ($tables as $table => $champs) {
312
-		# lock via memoization, si dispo
313
-		if (function_exists('cache_lock')) {
314
-			cache_lock($lock = _RECHERCHE_LOCK_KEY . ' ' . $table . ' ' . $recherche);
315
-		}
316
-
317
-		spip_timer('rech');
318
-
319
-		# TODO : ici plutot charger un iterateur via l'API iterateurs
320
-		$to_array = charger_fonction('recherche_to_array', 'inc');
321
-		$results[$table] = $to_array(
322
-			$recherche,
323
-			array_merge($options, ['table' => $table, 'champs' => $champs])
324
-		);
325
-		##var_dump($results[$table]);
326
-
327
-
328
-		spip_log(
329
-			"recherche $table ($recherche) : " . (is_countable($results[$table]) ? count($results[$table]) : 0) . ' resultats ' . spip_timer('rech'),
330
-			'recherche'
331
-		);
332
-
333
-		if (isset($lock)) {
334
-			cache_unlock($lock);
335
-		}
336
-	}
337
-
338
-	return $results;
257
+    include_spip('base/abstract_sql');
258
+
259
+    if (!is_array($tables)) {
260
+        $liste = liste_des_champs();
261
+
262
+        if (
263
+            is_string($tables)
264
+            and $tables != ''
265
+        ) {
266
+            $toutes = [];
267
+            foreach (explode(',', $tables) as $t) {
268
+                $t = trim($t);
269
+                if (isset($liste[$t])) {
270
+                    $toutes[$t] = $liste[$t];
271
+                }
272
+            }
273
+            $tables = $toutes;
274
+            unset($toutes);
275
+        } else {
276
+            $tables = $liste;
277
+        }
278
+    }
279
+
280
+    if (!strlen($recherche) or !count($tables)) {
281
+        return [];
282
+    }
283
+
284
+    include_spip('inc/autoriser');
285
+
286
+    // options par defaut
287
+    $options = array_merge(
288
+        [
289
+        'preg_flags' => 'UimsS',
290
+        'toutvoir' => false,
291
+        'champs' => false,
292
+        'score' => false,
293
+        'matches' => false,
294
+        'jointures' => false,
295
+        'serveur' => $serveur
296
+        ],
297
+        $options
298
+    );
299
+
300
+    $results = [];
301
+
302
+    // Utiliser l'iterateur (DATA:recherche)
303
+    // pour recuperer les couples (id_objet, score)
304
+    // Le resultat est au format {
305
+    //      id1 = { 'score' => x, attrs => { } },
306
+    //      id2 = { 'score' => x, attrs => { } },
307
+    // }
308
+
309
+    include_spip('inc/recherche_to_array');
310
+
311
+    foreach ($tables as $table => $champs) {
312
+        # lock via memoization, si dispo
313
+        if (function_exists('cache_lock')) {
314
+            cache_lock($lock = _RECHERCHE_LOCK_KEY . ' ' . $table . ' ' . $recherche);
315
+        }
316
+
317
+        spip_timer('rech');
318
+
319
+        # TODO : ici plutot charger un iterateur via l'API iterateurs
320
+        $to_array = charger_fonction('recherche_to_array', 'inc');
321
+        $results[$table] = $to_array(
322
+            $recherche,
323
+            array_merge($options, ['table' => $table, 'champs' => $champs])
324
+        );
325
+        ##var_dump($results[$table]);
326
+
327
+
328
+        spip_log(
329
+            "recherche $table ($recherche) : " . (is_countable($results[$table]) ? count($results[$table]) : 0) . ' resultats ' . spip_timer('rech'),
330
+            'recherche'
331
+        );
332
+
333
+        if (isset($lock)) {
334
+            cache_unlock($lock);
335
+        }
336
+    }
337
+
338
+    return $results;
339 339
 }
340 340
 
341 341
 
342 342
 // Effectue une recherche sur toutes les tables de la base de donnees
343 343
 // https://code.spip.net/@remplace_en_base
344 344
 function remplace_en_base($recherche = '', $remplace = null, $tables = null, $options = []) {
345
-	include_spip('inc/modifier');
346
-
347
-	// options par defaut
348
-	$options = array_merge(
349
-		[
350
-		'preg_flags' => 'UimsS',
351
-		'toutmodifier' => false
352
-		],
353
-		$options
354
-	);
355
-	$options['champs'] = true;
356
-
357
-
358
-	if (!is_array($tables)) {
359
-		$tables = liste_des_champs();
360
-	}
361
-
362
-	$results = recherche_en_base($recherche, $tables, $options);
363
-
364
-	$preg = '/' . str_replace('/', '\\/', $recherche) . '/' . $options['preg_flags'];
365
-
366
-	foreach ($results as $table => $r) {
367
-		$_id_table = id_table_objet($table);
368
-		foreach ($r as $id => $x) {
369
-			if (
370
-				$options['toutmodifier']
371
-				or autoriser('modifier', $table, $id)
372
-			) {
373
-				$modifs = [];
374
-				foreach ($x['champs'] as $key => $val) {
375
-					if ($key == $_id_table) {
376
-						continue;
377
-					}
378
-					$repl = preg_replace($preg, $remplace, $val);
379
-					if ($repl <> $val) {
380
-						$modifs[$key] = $repl;
381
-					}
382
-				}
383
-				if ($modifs) {
384
-					objet_modifier_champs(
385
-						$table,
386
-						$id,
387
-						[
388
-							'champs' => array_keys($modifs),
389
-						],
390
-						$modifs
391
-					);
392
-				}
393
-			}
394
-		}
395
-	}
345
+    include_spip('inc/modifier');
346
+
347
+    // options par defaut
348
+    $options = array_merge(
349
+        [
350
+        'preg_flags' => 'UimsS',
351
+        'toutmodifier' => false
352
+        ],
353
+        $options
354
+    );
355
+    $options['champs'] = true;
356
+
357
+
358
+    if (!is_array($tables)) {
359
+        $tables = liste_des_champs();
360
+    }
361
+
362
+    $results = recherche_en_base($recherche, $tables, $options);
363
+
364
+    $preg = '/' . str_replace('/', '\\/', $recherche) . '/' . $options['preg_flags'];
365
+
366
+    foreach ($results as $table => $r) {
367
+        $_id_table = id_table_objet($table);
368
+        foreach ($r as $id => $x) {
369
+            if (
370
+                $options['toutmodifier']
371
+                or autoriser('modifier', $table, $id)
372
+            ) {
373
+                $modifs = [];
374
+                foreach ($x['champs'] as $key => $val) {
375
+                    if ($key == $_id_table) {
376
+                        continue;
377
+                    }
378
+                    $repl = preg_replace($preg, $remplace, $val);
379
+                    if ($repl <> $val) {
380
+                        $modifs[$key] = $repl;
381
+                    }
382
+                }
383
+                if ($modifs) {
384
+                    objet_modifier_champs(
385
+                        $table,
386
+                        $id,
387
+                        [
388
+                            'champs' => array_keys($modifs),
389
+                        ],
390
+                        $modifs
391
+                    );
392
+                }
393
+            }
394
+        }
395
+    }
396 396
 }
Please login to merge, or discard this patch.