Completed
Push — master ( 5b53e6...916bf1 )
by cam
01:08
created
ecrire/public/fonctions.php 1 patch
Indentation   +364 added lines, -364 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
  **/
24 24
 
25 25
 if (!defined('_ECRIRE_INC_VERSION')) {
26
-	return;
26
+    return;
27 27
 }
28 28
 
29 29
 // public/interfaces definit des traitements sur les champs qui utilisent des fonctions de inc/texte
@@ -55,75 +55,75 @@  discard block
 block discarded – undo
55 55
  *     Introduction calculée
56 56
  **/
57 57
 function filtre_introduction_dist($descriptif, $texte, $longueur, $connect, $suite = null) {
58
-	// Si un descriptif est envoye, on l'utilise directement
59
-	if (strlen($descriptif)) {
60
-		return appliquer_traitement_champ($descriptif, 'introduction', '', [], $connect);
61
-	}
62
-
63
-	// De preference ce qui est marque <intro>...</intro>
64
-	$intro = '';
65
-	$texte = preg_replace(',(</?)intro>,i', "\\1intro>", $texte); // minuscules
66
-	while ($fin = strpos($texte, '</intro>')) {
67
-		$zone = substr($texte, 0, $fin);
68
-		$texte = substr($texte, $fin + strlen('</intro>'));
69
-		if ($deb = strpos($zone, '<intro>') or substr($zone, 0, 7) == '<intro>') {
70
-			$zone = substr($zone, $deb + 7);
71
-		}
72
-		$intro .= $zone;
73
-	}
74
-
75
-	// [12025] On ne *PEUT* pas couper simplement ici car c'est du texte brut,
76
-	// qui inclus raccourcis et modeles
77
-	// un simple <articlexx> peut etre ensuite transforme en 1000 lignes ...
78
-	// par ailleurs le nettoyage des raccourcis ne tient pas compte
79
-	// des surcharges et enrichissement de propre
80
-	// couper doit se faire apres propre
81
-	//$texte = nettoyer_raccourcis_typo($intro ? $intro : $texte, $connect);
82
-
83
-	// Cependant pour des questions de perfs on coupe quand meme, en prenant
84
-	// large et en se mefiant des tableaux #1323
85
-
86
-	if (strlen($intro)) {
87
-		$texte = $intro;
88
-	} else {
89
-		if (
90
-			strpos("\n" . $texte, "\n|") === false
91
-			and strlen($texte) > 2.5 * $longueur
92
-		) {
93
-			if (strpos($texte, '<multi') !== false) {
94
-				$texte = extraire_multi($texte);
95
-			}
96
-			$texte = couper($texte, 2 * $longueur);
97
-		}
98
-	}
99
-
100
-	// ne pas tenir compte des notes
101
-	if ($notes = charger_fonction('notes', 'inc', true)) {
102
-		$notes('', 'empiler');
103
-	}
104
-	// Supprimer les modèles avant le propre afin d'éviter qu'ils n'ajoutent du texte indésirable
105
-	// dans l'introduction.
106
-	$texte = supprime_img($texte, '');
107
-	$texte = appliquer_traitement_champ($texte, 'introduction', '', [], $connect);
108
-
109
-	if ($notes) {
110
-		$notes('', 'depiler');
111
-	}
112
-
113
-	if (is_null($suite) and defined('_INTRODUCTION_SUITE')) {
114
-		$suite = _INTRODUCTION_SUITE;
115
-	}
116
-	$texte = couper($texte, $longueur, $suite);
117
-	// comme on a coupe il faut repasser la typo (on a perdu les insecables)
118
-	$texte = typo($texte, true, $connect, []);
119
-
120
-	// et reparagrapher si necessaire (coherence avec le cas descriptif)
121
-	// une introduction a tojours un <p>
122
-	if ($GLOBALS['toujours_paragrapher']) { // Fermer les paragraphes
123
-	$texte = paragrapher($texte, $GLOBALS['toujours_paragrapher']);
124
-	}
125
-
126
-	return $texte;
58
+    // Si un descriptif est envoye, on l'utilise directement
59
+    if (strlen($descriptif)) {
60
+        return appliquer_traitement_champ($descriptif, 'introduction', '', [], $connect);
61
+    }
62
+
63
+    // De preference ce qui est marque <intro>...</intro>
64
+    $intro = '';
65
+    $texte = preg_replace(',(</?)intro>,i', "\\1intro>", $texte); // minuscules
66
+    while ($fin = strpos($texte, '</intro>')) {
67
+        $zone = substr($texte, 0, $fin);
68
+        $texte = substr($texte, $fin + strlen('</intro>'));
69
+        if ($deb = strpos($zone, '<intro>') or substr($zone, 0, 7) == '<intro>') {
70
+            $zone = substr($zone, $deb + 7);
71
+        }
72
+        $intro .= $zone;
73
+    }
74
+
75
+    // [12025] On ne *PEUT* pas couper simplement ici car c'est du texte brut,
76
+    // qui inclus raccourcis et modeles
77
+    // un simple <articlexx> peut etre ensuite transforme en 1000 lignes ...
78
+    // par ailleurs le nettoyage des raccourcis ne tient pas compte
79
+    // des surcharges et enrichissement de propre
80
+    // couper doit se faire apres propre
81
+    //$texte = nettoyer_raccourcis_typo($intro ? $intro : $texte, $connect);
82
+
83
+    // Cependant pour des questions de perfs on coupe quand meme, en prenant
84
+    // large et en se mefiant des tableaux #1323
85
+
86
+    if (strlen($intro)) {
87
+        $texte = $intro;
88
+    } else {
89
+        if (
90
+            strpos("\n" . $texte, "\n|") === false
91
+            and strlen($texte) > 2.5 * $longueur
92
+        ) {
93
+            if (strpos($texte, '<multi') !== false) {
94
+                $texte = extraire_multi($texte);
95
+            }
96
+            $texte = couper($texte, 2 * $longueur);
97
+        }
98
+    }
99
+
100
+    // ne pas tenir compte des notes
101
+    if ($notes = charger_fonction('notes', 'inc', true)) {
102
+        $notes('', 'empiler');
103
+    }
104
+    // Supprimer les modèles avant le propre afin d'éviter qu'ils n'ajoutent du texte indésirable
105
+    // dans l'introduction.
106
+    $texte = supprime_img($texte, '');
107
+    $texte = appliquer_traitement_champ($texte, 'introduction', '', [], $connect);
108
+
109
+    if ($notes) {
110
+        $notes('', 'depiler');
111
+    }
112
+
113
+    if (is_null($suite) and defined('_INTRODUCTION_SUITE')) {
114
+        $suite = _INTRODUCTION_SUITE;
115
+    }
116
+    $texte = couper($texte, $longueur, $suite);
117
+    // comme on a coupe il faut repasser la typo (on a perdu les insecables)
118
+    $texte = typo($texte, true, $connect, []);
119
+
120
+    // et reparagrapher si necessaire (coherence avec le cas descriptif)
121
+    // une introduction a tojours un <p>
122
+    if ($GLOBALS['toujours_paragrapher']) { // Fermer les paragraphes
123
+    $texte = paragrapher($texte, $GLOBALS['toujours_paragrapher']);
124
+    }
125
+
126
+    return $texte;
127 127
 }
128 128
 
129 129
 
@@ -158,73 +158,73 @@  discard block
 block discarded – undo
158 158
  *     Code HTML de la pagination
159 159
  **/
160 160
 function filtre_pagination_dist(
161
-	$total,
162
-	$nom,
163
-	$position,
164
-	$pas,
165
-	$liste = true,
166
-	$modele = '',
167
-	string $connect = '',
168
-	$env = []
161
+    $total,
162
+    $nom,
163
+    $position,
164
+    $pas,
165
+    $liste = true,
166
+    $modele = '',
167
+    string $connect = '',
168
+    $env = []
169 169
 ) {
170
-	static $ancres = [];
171
-	if ($pas < 1) {
172
-		return '';
173
-	}
174
-	$ancre = 'pagination' . $nom; // #pagination_articles
175
-	$debut = 'debut' . $nom; // 'debut_articles'
176
-
177
-	// n'afficher l'ancre qu'une fois
178
-	if (!isset($ancres[$ancre])) {
179
-		$bloc_ancre = $ancres[$ancre] = "<a id='" . $ancre . "' class='pagination_ancre'></a>";
180
-	} else {
181
-		$bloc_ancre = '';
182
-	}
183
-	// liste = false : on ne veut que l'ancre
184
-	if (!$liste) {
185
-		return $ancres[$ancre];
186
-	}
187
-
188
-	$self = (empty($env['self']) ? self() : $env['self']);
189
-	$pagination = [
190
-		'debut' => $debut,
191
-		'url' => parametre_url($self, 'fragment', ''), // nettoyer l'id ahah eventuel
192
-		'total' => $total,
193
-		'position' => intval($position),
194
-		'pas' => $pas,
195
-		'nombre_pages' => floor(($total - 1) / $pas) + 1,
196
-		'page_courante' => floor(intval($position) / $pas) + 1,
197
-		'ancre' => $ancre,
198
-		'bloc_ancre' => $bloc_ancre
199
-	];
200
-	if (is_array($env)) {
201
-		$pagination = array_merge($env, $pagination);
202
-	}
203
-
204
-	// Pas de pagination
205
-	if ($pagination['nombre_pages'] <= 1) {
206
-		return '';
207
-	}
208
-
209
-	if ($modele) {
210
-		$pagination['type_pagination'] = $modele;
211
-		if (trouver_fond('pagination_' . $modele, 'modeles')) {
212
-			$modele = '_' . $modele;
213
-		}
214
-		else {
215
-			$modele = '';
216
-		}
217
-	}
218
-
219
-	if (!defined('_PAGINATION_NOMBRE_LIENS_MAX')) {
220
-		define('_PAGINATION_NOMBRE_LIENS_MAX', 10);
221
-	}
222
-	if (!defined('_PAGINATION_NOMBRE_LIENS_MAX_ECRIRE')) {
223
-		define('_PAGINATION_NOMBRE_LIENS_MAX_ECRIRE', 5);
224
-	}
225
-
226
-
227
-	return recuperer_fond("modeles/pagination$modele", $pagination, ['trim' => true], $connect);
170
+    static $ancres = [];
171
+    if ($pas < 1) {
172
+        return '';
173
+    }
174
+    $ancre = 'pagination' . $nom; // #pagination_articles
175
+    $debut = 'debut' . $nom; // 'debut_articles'
176
+
177
+    // n'afficher l'ancre qu'une fois
178
+    if (!isset($ancres[$ancre])) {
179
+        $bloc_ancre = $ancres[$ancre] = "<a id='" . $ancre . "' class='pagination_ancre'></a>";
180
+    } else {
181
+        $bloc_ancre = '';
182
+    }
183
+    // liste = false : on ne veut que l'ancre
184
+    if (!$liste) {
185
+        return $ancres[$ancre];
186
+    }
187
+
188
+    $self = (empty($env['self']) ? self() : $env['self']);
189
+    $pagination = [
190
+        'debut' => $debut,
191
+        'url' => parametre_url($self, 'fragment', ''), // nettoyer l'id ahah eventuel
192
+        'total' => $total,
193
+        'position' => intval($position),
194
+        'pas' => $pas,
195
+        'nombre_pages' => floor(($total - 1) / $pas) + 1,
196
+        'page_courante' => floor(intval($position) / $pas) + 1,
197
+        'ancre' => $ancre,
198
+        'bloc_ancre' => $bloc_ancre
199
+    ];
200
+    if (is_array($env)) {
201
+        $pagination = array_merge($env, $pagination);
202
+    }
203
+
204
+    // Pas de pagination
205
+    if ($pagination['nombre_pages'] <= 1) {
206
+        return '';
207
+    }
208
+
209
+    if ($modele) {
210
+        $pagination['type_pagination'] = $modele;
211
+        if (trouver_fond('pagination_' . $modele, 'modeles')) {
212
+            $modele = '_' . $modele;
213
+        }
214
+        else {
215
+            $modele = '';
216
+        }
217
+    }
218
+
219
+    if (!defined('_PAGINATION_NOMBRE_LIENS_MAX')) {
220
+        define('_PAGINATION_NOMBRE_LIENS_MAX', 10);
221
+    }
222
+    if (!defined('_PAGINATION_NOMBRE_LIENS_MAX_ECRIRE')) {
223
+        define('_PAGINATION_NOMBRE_LIENS_MAX_ECRIRE', 5);
224
+    }
225
+
226
+
227
+    return recuperer_fond("modeles/pagination$modele", $pagination, ['trim' => true], $connect);
228 228
 }
229 229
 
230 230
 
@@ -243,44 +243,44 @@  discard block
 block discarded – undo
243 243
  *     Liste (première page, dernière page).
244 244
  **/
245 245
 function filtre_bornes_pagination_dist($courante, $nombre, $max = 10) {
246
-	if ($max <= 0 or $max >= $nombre) {
247
-		return [1, $nombre];
248
-	}
249
-	if ($max <= 1) {
250
-		return [$courante, $courante];
251
-	}
252
-
253
-	$premiere = max(1, $courante - floor(($max - 1) / 2));
254
-	$derniere = min($nombre, $premiere + $max - 2);
255
-	$premiere = $derniere == $nombre ? $derniere - $max + 1 : $premiere;
256
-
257
-	return [$premiere, $derniere];
246
+    if ($max <= 0 or $max >= $nombre) {
247
+        return [1, $nombre];
248
+    }
249
+    if ($max <= 1) {
250
+        return [$courante, $courante];
251
+    }
252
+
253
+    $premiere = max(1, $courante - floor(($max - 1) / 2));
254
+    $derniere = min($nombre, $premiere + $max - 2);
255
+    $premiere = $derniere == $nombre ? $derniere - $max + 1 : $premiere;
256
+
257
+    return [$premiere, $derniere];
258 258
 }
259 259
 
260 260
 function filtre_pagination_affiche_texte_lien_page_dist($type_pagination, $numero_page, $rang_item) {
261
-	if ($numero_page === 'tous') {
262
-		return '&#8734;';
263
-	}
264
-	if ($numero_page === 'prev') {
265
-		return '&lt;';
266
-	}
267
-	if ($numero_page === 'next') {
268
-		return '&gt;';
269
-	}
270
-
271
-	switch ($type_pagination) {
272
-		case 'resultats':
273
-			return $rang_item + 1; // 1 11 21 31...
274
-		case 'naturel':
275
-			return $rang_item ?: 1; // 1 10 20 30...
276
-		case 'rang':
277
-			return $rang_item; // 0 10 20 30...
278
-
279
-		case 'page':
280
-		case 'prive':
281
-		default:
282
-			return $numero_page; // 1 2 3 4 5...
283
-	}
261
+    if ($numero_page === 'tous') {
262
+        return '&#8734;';
263
+    }
264
+    if ($numero_page === 'prev') {
265
+        return '&lt;';
266
+    }
267
+    if ($numero_page === 'next') {
268
+        return '&gt;';
269
+    }
270
+
271
+    switch ($type_pagination) {
272
+        case 'resultats':
273
+            return $rang_item + 1; // 1 11 21 31...
274
+        case 'naturel':
275
+            return $rang_item ?: 1; // 1 10 20 30...
276
+        case 'rang':
277
+            return $rang_item; // 0 10 20 30...
278
+
279
+        case 'page':
280
+        case 'prive':
281
+        default:
282
+            return $numero_page; // 1 2 3 4 5...
283
+    }
284 284
 }
285 285
 
286 286
 /**
@@ -293,15 +293,15 @@  discard block
 block discarded – undo
293 293
  **/
294 294
 function lister_objets_avec_logos($type) {
295 295
 
296
-	$objet = objet_type($type);
297
-	$ids = sql_allfetsel('L.id_objet', 'spip_documents AS D JOIN spip_documents_liens AS L ON L.id_document=D.id_document', 'D.mode=' . sql_quote('logoon') . ' AND L.objet=' . sql_quote($objet));
298
-	if ($ids) {
299
-		$ids = array_column($ids, 'id_objet');
300
-		return implode(',', $ids);
301
-	}
302
-	else {
303
-		return '0';
304
-	}
296
+    $objet = objet_type($type);
297
+    $ids = sql_allfetsel('L.id_objet', 'spip_documents AS D JOIN spip_documents_liens AS L ON L.id_document=D.id_document', 'D.mode=' . sql_quote('logoon') . ' AND L.objet=' . sql_quote($objet));
298
+    if ($ids) {
299
+        $ids = array_column($ids, 'id_objet');
300
+        return implode(',', $ids);
301
+    }
302
+    else {
303
+        return '0';
304
+    }
305 305
 }
306 306
 
307 307
 
@@ -317,14 +317,14 @@  discard block
 block discarded – undo
317 317
  *     Code HTML des notes
318 318
  **/
319 319
 function calculer_notes() {
320
-	$r = '';
321
-	if ($notes = charger_fonction('notes', 'inc', true)) {
322
-		$r = $notes([]);
323
-		$notes('', 'depiler');
324
-		$notes('', 'empiler');
325
-	}
326
-
327
-	return $r;
320
+    $r = '';
321
+    if ($notes = charger_fonction('notes', 'inc', true)) {
322
+        $r = $notes([]);
323
+        $notes('', 'depiler');
324
+        $notes('', 'empiler');
325
+    }
326
+
327
+    return $r;
328 328
 }
329 329
 
330 330
 
@@ -341,10 +341,10 @@  discard block
 block discarded – undo
341 341
  * @return string
342 342
  */
343 343
 function retrouver_rang_lien($objet_source, $ids, $objet_lie, $idl, $objet_lien) {
344
-	$res = lister_objets_liens($objet_source, $objet_lie, $idl, $objet_lien);
345
-	$res = array_column($res, 'rang_lien', $objet_source);
344
+    $res = lister_objets_liens($objet_source, $objet_lie, $idl, $objet_lien);
345
+    $res = array_column($res, 'rang_lien', $objet_source);
346 346
 
347
-	return ($res[$ids] ?? '');
347
+    return ($res[$ids] ?? '');
348 348
 }
349 349
 
350 350
 
@@ -361,19 +361,19 @@  discard block
 block discarded – undo
361 361
  * @private
362 362
  */
363 363
 function lister_objets_liens($objet_source, $objet, $id_objet, $objet_lien) {
364
-	static $liens = [];
365
-	if (!isset($liens["$objet_source-$objet-$id_objet-$objet_lien"])) {
366
-		include_spip('action/editer_liens');
367
-		// quand $objet == $objet_lien == $objet_source on reste sur le cas par defaut de $objet_lien == $objet_source
368
-		if ($objet_lien == $objet and $objet_lien !== $objet_source) {
369
-			$res = objet_trouver_liens([$objet => $id_objet], [$objet_source => '*']);
370
-		} else {
371
-			$res = objet_trouver_liens([$objet_source => '*'], [$objet => $id_objet]);
372
-		}
373
-
374
-		$liens["$objet_source-$objet-$id_objet-$objet_lien"] = $res;
375
-	}
376
-	return $liens["$objet_source-$objet-$id_objet-$objet_lien"];
364
+    static $liens = [];
365
+    if (!isset($liens["$objet_source-$objet-$id_objet-$objet_lien"])) {
366
+        include_spip('action/editer_liens');
367
+        // quand $objet == $objet_lien == $objet_source on reste sur le cas par defaut de $objet_lien == $objet_source
368
+        if ($objet_lien == $objet and $objet_lien !== $objet_source) {
369
+            $res = objet_trouver_liens([$objet => $id_objet], [$objet_source => '*']);
370
+        } else {
371
+            $res = objet_trouver_liens([$objet_source => '*'], [$objet => $id_objet]);
372
+        }
373
+
374
+        $liens["$objet_source-$objet-$id_objet-$objet_lien"] = $res;
375
+    }
376
+    return $liens["$objet_source-$objet-$id_objet-$objet_lien"];
377 377
 }
378 378
 
379 379
 /**
@@ -387,24 +387,24 @@  discard block
 block discarded – undo
387 387
  * @return int|string
388 388
  */
389 389
 function calculer_rang_smart($titre, $objet_source, $id, $env) {
390
-	// Cas du #RANG utilisé dans #FORMULAIRE_EDITER_LIENS -> attraper le rang du lien
391
-	// permet de voir le rang du lien si il y en a un en base, meme avant un squelette xxxx-lies.html ne gerant pas les liens
392
-	if (
393
-		isset($env['form']) and $env['form']
394
-		and isset($env['_objet_lien']) and $env['_objet_lien']
395
-		and (function_exists('lien_triables') or include_spip('action/editer_liens'))
396
-		and $r = objet_associable($env['_objet_lien'])
397
-		and [$p, $table_lien] = $r
398
-		and lien_triables($table_lien)
399
-		and isset($env['objet']) and $env['objet']
400
-		and isset($env['id_objet']) and $env['id_objet']
401
-		and $objet_source
402
-		and $id = intval($id)
403
-	) {
404
-		$rang = retrouver_rang_lien($objet_source, $id, $env['objet'], $env['id_objet'], $env['_objet_lien']);
405
-		return ($rang ?: '');
406
-	}
407
-	return recuperer_numero($titre);
390
+    // Cas du #RANG utilisé dans #FORMULAIRE_EDITER_LIENS -> attraper le rang du lien
391
+    // permet de voir le rang du lien si il y en a un en base, meme avant un squelette xxxx-lies.html ne gerant pas les liens
392
+    if (
393
+        isset($env['form']) and $env['form']
394
+        and isset($env['_objet_lien']) and $env['_objet_lien']
395
+        and (function_exists('lien_triables') or include_spip('action/editer_liens'))
396
+        and $r = objet_associable($env['_objet_lien'])
397
+        and [$p, $table_lien] = $r
398
+        and lien_triables($table_lien)
399
+        and isset($env['objet']) and $env['objet']
400
+        and isset($env['id_objet']) and $env['id_objet']
401
+        and $objet_source
402
+        and $id = intval($id)
403
+    ) {
404
+        $rang = retrouver_rang_lien($objet_source, $id, $env['objet'], $env['id_objet'], $env['_objet_lien']);
405
+        return ($rang ?: '');
406
+    }
407
+    return recuperer_numero($titre);
408 408
 }
409 409
 
410 410
 /**
@@ -431,72 +431,72 @@  discard block
 block discarded – undo
431 431
  */
432 432
 function calculer_balise_tri(string $champ_ou_sens, string $libelle, string $classe, string $tri_nom, string $tri_champ, string $tri_sens, $liste_tri_sens_defaut): string {
433 433
 
434
-	$url = self('&');
435
-	$tri_sens = (int) $tri_sens;
436
-	$alias_sens = [
437
-		'<' => -1,
438
-		'>' => 1,
439
-		'inverse' => -1,
440
-	];
441
-
442
-	// Normaliser la liste des sens de tri par défaut
443
-	// On ajoute un jocker pour les champs non présents dans la liste
444
-	// avec la valeur du 1er item de la liste, idem critère {tri}
445
-	if (is_array($liste_tri_sens_defaut)) {
446
-		$liste_tri_sens_defaut['*'] = array_values($liste_tri_sens_defaut)[0];
447
-	} else {
448
-		$liste_tri_sens_defaut = [
449
-			'*' => (int) ($alias_sens[$liste_tri_sens_defaut] ?? $liste_tri_sens_defaut),
450
-		];
451
-	}
452
-
453
-	// Les sens de tri actuel et nouveau :
454
-	// Soit c'est un sens fixe donné en paramètre (< ou >)
455
-	$is_sens_fixe = array_key_exists($champ_ou_sens, $alias_sens);
456
-	if ($is_sens_fixe) {
457
-		$tri_sens_actuel = $tri_sens;
458
-		$tri_sens_nouveau = $alias_sens[$champ_ou_sens];
459
-	// Soit c'est le champ utilisé actuellement pour le tri → on inverse le sens
460
-	} elseif ($champ_ou_sens === $tri_champ) {
461
-		$tri_sens_actuel = $tri_sens;
462
-		$tri_sens_nouveau = $tri_sens * -1;
463
-	// Sinon c'est un nouveau champ, et on prend son tri par défaut
464
-	} else {
465
-		$tri_sens_actuel = $tri_sens_nouveau = (int) ($liste_tri_sens_defaut[$champ_ou_sens] ?? $liste_tri_sens_defaut['*']);
466
-	}
467
-
468
-	// URL : ajouter le champ sur lequel porte le tri
469
-	if (!$is_sens_fixe) {
470
-		$param_tri = "tri$tri_nom";
471
-		$url = parametre_url($url, $param_tri, $champ_ou_sens);
472
-	}
473
-
474
-	// URL : n'ajouter le sens de tri que si nécessaire,
475
-	// c.à.d différent du sens par défaut pour le champ
476
-	$param_sens = "sens$tri_nom";
477
-	$tri_sens_defaut_champ = (int) ($liste_tri_sens_defaut[$champ_ou_sens] ?? $liste_tri_sens_defaut['*']);
478
-	if ($tri_sens_nouveau !== $tri_sens_defaut_champ) {
479
-		$url = parametre_url($url, $param_sens, $tri_sens_nouveau);
480
-	} else {
481
-		$url = parametre_url($url, $param_sens, '');
482
-	}
483
-
484
-	// Drapeau pour garder en session ?
485
-	$param_memo = (!$is_sens_fixe ? $param_tri : $param_sens);
486
-	$url = parametre_url($url, 'var_memotri', strncmp($tri_nom, 'session', 7) == 0 ? $param_memo : '');
487
-
488
-	// Classes : on indique le sens de tri et l'item exposé
489
-	if (!$is_sens_fixe) {
490
-		$classe .= ' item-tri item-tri_' . ($tri_sens_actuel === 1 ? 'asc' : 'desc');
491
-	}
492
-	if ($champ_ou_sens === $tri_champ) {
493
-		$classe .= ' item-tri_actif';
494
-	}
495
-
496
-	// Lien
497
-	$balise = lien_ou_expose($url, $libelle, false, $classe);
498
-
499
-	return $balise;
434
+    $url = self('&');
435
+    $tri_sens = (int) $tri_sens;
436
+    $alias_sens = [
437
+        '<' => -1,
438
+        '>' => 1,
439
+        'inverse' => -1,
440
+    ];
441
+
442
+    // Normaliser la liste des sens de tri par défaut
443
+    // On ajoute un jocker pour les champs non présents dans la liste
444
+    // avec la valeur du 1er item de la liste, idem critère {tri}
445
+    if (is_array($liste_tri_sens_defaut)) {
446
+        $liste_tri_sens_defaut['*'] = array_values($liste_tri_sens_defaut)[0];
447
+    } else {
448
+        $liste_tri_sens_defaut = [
449
+            '*' => (int) ($alias_sens[$liste_tri_sens_defaut] ?? $liste_tri_sens_defaut),
450
+        ];
451
+    }
452
+
453
+    // Les sens de tri actuel et nouveau :
454
+    // Soit c'est un sens fixe donné en paramètre (< ou >)
455
+    $is_sens_fixe = array_key_exists($champ_ou_sens, $alias_sens);
456
+    if ($is_sens_fixe) {
457
+        $tri_sens_actuel = $tri_sens;
458
+        $tri_sens_nouveau = $alias_sens[$champ_ou_sens];
459
+    // Soit c'est le champ utilisé actuellement pour le tri → on inverse le sens
460
+    } elseif ($champ_ou_sens === $tri_champ) {
461
+        $tri_sens_actuel = $tri_sens;
462
+        $tri_sens_nouveau = $tri_sens * -1;
463
+    // Sinon c'est un nouveau champ, et on prend son tri par défaut
464
+    } else {
465
+        $tri_sens_actuel = $tri_sens_nouveau = (int) ($liste_tri_sens_defaut[$champ_ou_sens] ?? $liste_tri_sens_defaut['*']);
466
+    }
467
+
468
+    // URL : ajouter le champ sur lequel porte le tri
469
+    if (!$is_sens_fixe) {
470
+        $param_tri = "tri$tri_nom";
471
+        $url = parametre_url($url, $param_tri, $champ_ou_sens);
472
+    }
473
+
474
+    // URL : n'ajouter le sens de tri que si nécessaire,
475
+    // c.à.d différent du sens par défaut pour le champ
476
+    $param_sens = "sens$tri_nom";
477
+    $tri_sens_defaut_champ = (int) ($liste_tri_sens_defaut[$champ_ou_sens] ?? $liste_tri_sens_defaut['*']);
478
+    if ($tri_sens_nouveau !== $tri_sens_defaut_champ) {
479
+        $url = parametre_url($url, $param_sens, $tri_sens_nouveau);
480
+    } else {
481
+        $url = parametre_url($url, $param_sens, '');
482
+    }
483
+
484
+    // Drapeau pour garder en session ?
485
+    $param_memo = (!$is_sens_fixe ? $param_tri : $param_sens);
486
+    $url = parametre_url($url, 'var_memotri', strncmp($tri_nom, 'session', 7) == 0 ? $param_memo : '');
487
+
488
+    // Classes : on indique le sens de tri et l'item exposé
489
+    if (!$is_sens_fixe) {
490
+        $classe .= ' item-tri item-tri_' . ($tri_sens_actuel === 1 ? 'asc' : 'desc');
491
+    }
492
+    if ($champ_ou_sens === $tri_champ) {
493
+        $classe .= ' item-tri_actif';
494
+    }
495
+
496
+    // Lien
497
+    $balise = lien_ou_expose($url, $libelle, false, $classe);
498
+
499
+    return $balise;
500 500
 }
501 501
 
502 502
 
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
  * @return string
513 513
  */
514 514
 function tri_protege_champ($t) {
515
-	return preg_replace(',[^\s\w.+\[\]],', '', $t);
515
+    return preg_replace(',[^\s\w.+\[\]],', '', $t);
516 516
 }
517 517
 
518 518
 /**
@@ -525,43 +525,43 @@  discard block
 block discarded – undo
525 525
  * @return string
526 526
  */
527 527
 function tri_champ_order($t, $from = null, $senstri = '') {
528
-	if (strncmp($t, 'multi ', 6) == 0) {
529
-		return 'multi' . $senstri;
530
-	}
531
-
532
-	$champ = $t;
533
-
534
-	$prefixe = '';
535
-	foreach (['num ', 'sinum '] as $p) {
536
-		if (strpos($t, $p) === 0) {
537
-			$champ = substr($t, strlen($p));
538
-			$prefixe = $p;
539
-		}
540
-	}
541
-
542
-	// enlever les autres espaces non evacues par tri_protege_champ
543
-	$champ = preg_replace(',\s,', '', $champ);
544
-
545
-	if (is_array($from)) {
546
-		$trouver_table = charger_fonction('trouver_table', 'base');
547
-		foreach ($from as $idt => $table_sql) {
548
-			if (
549
-				$desc = $trouver_table($table_sql)
550
-				and isset($desc['field'][$champ])
551
-			) {
552
-				$champ = "$idt.$champ";
553
-				break;
554
-			}
555
-		}
556
-	}
557
-	switch ($prefixe) {
558
-		case 'num ':
559
-			return "CASE( 0+$champ ) WHEN 0 THEN 1 ELSE 0 END{$senstri}, 0+$champ{$senstri}";
560
-		case 'sinum ':
561
-			return "CASE( 0+$champ ) WHEN 0 THEN 1 ELSE 0 END{$senstri}";
562
-		default:
563
-			return $champ . $senstri;
564
-	}
528
+    if (strncmp($t, 'multi ', 6) == 0) {
529
+        return 'multi' . $senstri;
530
+    }
531
+
532
+    $champ = $t;
533
+
534
+    $prefixe = '';
535
+    foreach (['num ', 'sinum '] as $p) {
536
+        if (strpos($t, $p) === 0) {
537
+            $champ = substr($t, strlen($p));
538
+            $prefixe = $p;
539
+        }
540
+    }
541
+
542
+    // enlever les autres espaces non evacues par tri_protege_champ
543
+    $champ = preg_replace(',\s,', '', $champ);
544
+
545
+    if (is_array($from)) {
546
+        $trouver_table = charger_fonction('trouver_table', 'base');
547
+        foreach ($from as $idt => $table_sql) {
548
+            if (
549
+                $desc = $trouver_table($table_sql)
550
+                and isset($desc['field'][$champ])
551
+            ) {
552
+                $champ = "$idt.$champ";
553
+                break;
554
+            }
555
+        }
556
+    }
557
+    switch ($prefixe) {
558
+        case 'num ':
559
+            return "CASE( 0+$champ ) WHEN 0 THEN 1 ELSE 0 END{$senstri}, 0+$champ{$senstri}";
560
+        case 'sinum ':
561
+            return "CASE( 0+$champ ) WHEN 0 THEN 1 ELSE 0 END{$senstri}";
562
+        default:
563
+            return $champ . $senstri;
564
+    }
565 565
 }
566 566
 
567 567
 /**
@@ -575,18 +575,18 @@  discard block
 block discarded – undo
575 575
  * @return string
576 576
  */
577 577
 function tri_champ_select($t) {
578
-	if (strncmp($t, 'multi ', 6) == 0) {
579
-		$t = substr($t, 6);
580
-		$t = preg_replace(',\s,', '', $t);
581
-		$t = sql_multi($t, $GLOBALS['spip_lang']);
582
-
583
-		return $t;
584
-	}
585
-	if (trim($t) == 'hasard') {
586
-		return 'rand() AS hasard';
587
-	}
588
-
589
-	return "''";
578
+    if (strncmp($t, 'multi ', 6) == 0) {
579
+        $t = substr($t, 6);
580
+        $t = preg_replace(',\s,', '', $t);
581
+        $t = sql_multi($t, $GLOBALS['spip_lang']);
582
+
583
+        return $t;
584
+    }
585
+    if (trim($t) == 'hasard') {
586
+        return 'rand() AS hasard';
587
+    }
588
+
589
+    return "''";
590 590
 }
591 591
 
592 592
 /**
@@ -598,16 +598,16 @@  discard block
 block discarded – undo
598 598
  * @return string
599 599
  */
600 600
 function formate_liste_critere_par_ordre_liste($valeurs, $serveur = '') {
601
-	if (!is_array($valeurs)) {
602
-		return '';
603
-	}
604
-	$f = sql_serveur('quote', $serveur, true);
605
-	if (!is_string($f) or !$f) {
606
-		return '';
607
-	}
608
-	$valeurs = implode(',', array_map($f, array_unique($valeurs)));
609
-
610
-	return $valeurs;
601
+    if (!is_array($valeurs)) {
602
+        return '';
603
+    }
604
+    $f = sql_serveur('quote', $serveur, true);
605
+    if (!is_string($f) or !$f) {
606
+        return '';
607
+    }
608
+    $valeurs = implode(',', array_map($f, array_unique($valeurs)));
609
+
610
+    return $valeurs;
611 611
 }
612 612
 
613 613
 /**
@@ -630,20 +630,20 @@  discard block
 block discarded – undo
630 630
  *     Valeur $defaut sinon.
631 631
  **/
632 632
 function appliquer_filtre_sinon($arg, $filtre, $args, $defaut = '') {
633
-	// Si c'est un filtre d'image, on utilise image_filtrer()
634
-	// Attention : les 2 premiers arguments sont inversés dans ce cas
635
-	if (trouver_filtre_matrice($filtre) and substr($filtre, 0, 6) == 'image_') {
636
-		include_spip('inc/filtres_images_lib_mini');
637
-		$args[1] = $args[0];
638
-		$args[0] = $filtre;
639
-		return image_graver(image_filtrer($args));
640
-	}
641
-
642
-	$f = chercher_filtre($filtre);
643
-	if (!$f) {
644
-		return $defaut;
645
-	}
646
-	array_shift($args); // enlever $arg
647
-	array_shift($args); // enlever $filtre
648
-	return $f($arg, ...$args);
633
+    // Si c'est un filtre d'image, on utilise image_filtrer()
634
+    // Attention : les 2 premiers arguments sont inversés dans ce cas
635
+    if (trouver_filtre_matrice($filtre) and substr($filtre, 0, 6) == 'image_') {
636
+        include_spip('inc/filtres_images_lib_mini');
637
+        $args[1] = $args[0];
638
+        $args[0] = $filtre;
639
+        return image_graver(image_filtrer($args));
640
+    }
641
+
642
+    $f = chercher_filtre($filtre);
643
+    if (!$f) {
644
+        return $defaut;
645
+    }
646
+    array_shift($args); // enlever $arg
647
+    array_shift($args); // enlever $filtre
648
+    return $f($arg, ...$args);
649 649
 }
Please login to merge, or discard this patch.
ecrire/inc/drapeau_edition.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
  * @package SPIP\Core\Drapeaux\Edition
31 31
  **/
32 32
 if (!defined('_ECRIRE_INC_VERSION')) {
33
-	return;
33
+    return;
34 34
 }
35 35
 
36 36
 
@@ -45,46 +45,46 @@  discard block
 block discarded – undo
45 45
  *     `[ type d'objet ][id_objet][id_auteur][nom de l'auteur] = time()`
46 46
  **/
47 47
 function lire_tableau_edition() {
48
-	$edition = @unserialize($GLOBALS['meta']['drapeau_edition']);
49
-	if (!$edition) {
50
-		return [];
51
-	}
52
-	$changed = false;
48
+    $edition = @unserialize($GLOBALS['meta']['drapeau_edition']);
49
+    if (!$edition) {
50
+        return [];
51
+    }
52
+    $changed = false;
53 53
 
54
-	$bon_pour_le_service = time() - 3600;
55
-	// parcourir le tableau et virer les vieux
56
-	foreach ($edition as $objet => $data) {
57
-		if (!is_array($data)) {
58
-			unset($edition[$objet]);
59
-		} // vieille version
60
-		else {
61
-			foreach ($data as $id => $tab) {
62
-				if (!is_array($tab)) {
63
-					unset($edition[$objet][$tab]);
64
-				} // vieille version
65
-				else {
66
-					foreach ($tab as $n => $duo) {
67
-						if (current($duo) < $bon_pour_le_service) {
68
-							unset($edition[$objet][$id][$n]);
69
-							$changed = true;
70
-						}
71
-					}
72
-				}
73
-				if (!$edition[$objet][$id]) {
74
-					unset($edition[$objet][$id]);
75
-				}
76
-			}
77
-		}
78
-		if (!$edition[$objet]) {
79
-			unset($edition[$objet]);
80
-		}
81
-	}
54
+    $bon_pour_le_service = time() - 3600;
55
+    // parcourir le tableau et virer les vieux
56
+    foreach ($edition as $objet => $data) {
57
+        if (!is_array($data)) {
58
+            unset($edition[$objet]);
59
+        } // vieille version
60
+        else {
61
+            foreach ($data as $id => $tab) {
62
+                if (!is_array($tab)) {
63
+                    unset($edition[$objet][$tab]);
64
+                } // vieille version
65
+                else {
66
+                    foreach ($tab as $n => $duo) {
67
+                        if (current($duo) < $bon_pour_le_service) {
68
+                            unset($edition[$objet][$id][$n]);
69
+                            $changed = true;
70
+                        }
71
+                    }
72
+                }
73
+                if (!$edition[$objet][$id]) {
74
+                    unset($edition[$objet][$id]);
75
+                }
76
+            }
77
+        }
78
+        if (!$edition[$objet]) {
79
+            unset($edition[$objet]);
80
+        }
81
+    }
82 82
 
83
-	if ($changed) {
84
-		ecrire_tableau_edition($edition);
85
-	}
83
+    if ($changed) {
84
+        ecrire_tableau_edition($edition);
85
+    }
86 86
 
87
-	return $edition;
87
+    return $edition;
88 88
 }
89 89
 
90 90
 /**
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
  *     `[ type d'objet ][id_objet][id_auteur][nom de l'auteur] = time()`
98 98
  **/
99 99
 function ecrire_tableau_edition($edition) {
100
-	ecrire_meta('drapeau_edition', serialize($edition));
100
+    ecrire_meta('drapeau_edition', serialize($edition));
101 101
 }
102 102
 
103 103
 /**
@@ -117,22 +117,22 @@  discard block
 block discarded – undo
117 117
  *     Type d'objet édité
118 118
  */
119 119
 function signale_edition($id, $auteur, $type = 'article') {
120
-	include_spip('base/objets');
121
-	include_spip('inc/filtres');
122
-	if (objet_info($type, 'editable') !== 'oui') {
123
-		return;
124
-	}
120
+    include_spip('base/objets');
121
+    include_spip('inc/filtres');
122
+    if (objet_info($type, 'editable') !== 'oui') {
123
+        return;
124
+    }
125 125
 
126
-	$edition = lire_tableau_edition();
126
+    $edition = lire_tableau_edition();
127 127
 	
128
-	$nom = $auteur['nom'] ?? $GLOBALS['ip'];
129
-	$id_a = $auteur['id_auteur'] ?? $GLOBALS['ip'];
128
+    $nom = $auteur['nom'] ?? $GLOBALS['ip'];
129
+    $id_a = $auteur['id_auteur'] ?? $GLOBALS['ip'];
130 130
 
131
-	if (!isset($edition[$type][$id]) or !is_array($edition[$type][$id])) {
132
-		$edition[$type][$id] = [];
133
-	}
134
-	$edition[$type][$id][$id_a][$nom] = time();
135
-	ecrire_tableau_edition($edition);
131
+    if (!isset($edition[$type][$id]) or !is_array($edition[$type][$id])) {
132
+        $edition[$type][$id] = [];
133
+    }
134
+    $edition[$type][$id][$id_a][$nom] = time();
135
+    ecrire_tableau_edition($edition);
136 136
 }
137 137
 
138 138
 /**
@@ -149,9 +149,9 @@  discard block
 block discarded – undo
149 149
  */
150 150
 function qui_edite($id, $type = 'article') {
151 151
 
152
-	$edition = lire_tableau_edition();
152
+    $edition = lire_tableau_edition();
153 153
 
154
-	return empty($edition[$type][$id]) ? [] : $edition[$type][$id];
154
+    return empty($edition[$type][$id]) ? [] : $edition[$type][$id];
155 155
 }
156 156
 
157 157
 /**
@@ -165,23 +165,23 @@  discard block
 block discarded – undo
165 165
  *     Liste de tableaux `['nom_auteur_modif' => x|y|z, 'date_diff' => n]`
166 166
  */
167 167
 function mention_qui_edite($id, $type = 'article'): array {
168
-	$modif = qui_edite($id, $type);
169
-	unset($modif[$GLOBALS['visiteur_session']['id_auteur']]);
168
+    $modif = qui_edite($id, $type);
169
+    unset($modif[$GLOBALS['visiteur_session']['id_auteur']]);
170 170
 
171
-	if ($modif) {
172
-		$quand = 0;
173
-		foreach ($modif as $duo) {
174
-			$auteurs[] = typo(key($duo));
175
-			$quand = max($quand, current($duo));
176
-		}
171
+    if ($modif) {
172
+        $quand = 0;
173
+        foreach ($modif as $duo) {
174
+            $auteurs[] = typo(key($duo));
175
+            $quand = max($quand, current($duo));
176
+        }
177 177
 
178
-		// format lie a la chaine de langue 'avis_article_modifie'
179
-		return [
180
-			'nom_auteur_modif' => join(' | ', $auteurs),
181
-			'date_diff' => ceil((time() - $quand) / 60)
182
-		];
183
-	}
184
-	return [];
178
+        // format lie a la chaine de langue 'avis_article_modifie'
179
+        return [
180
+            'nom_auteur_modif' => join(' | ', $auteurs),
181
+            'date_diff' => ceil((time() - $quand) / 60)
182
+        ];
183
+    }
184
+    return [];
185 185
 }
186 186
 
187 187
 /**
@@ -195,25 +195,25 @@  discard block
 block discarded – undo
195 195
  *     Liste de tableaux `['objet' => x, 'id_objet' => n]`
196 196
  */
197 197
 function liste_drapeau_edition($id_auteur) {
198
-	$edition = lire_tableau_edition();
199
-	$objets_ouverts = [];
198
+    $edition = lire_tableau_edition();
199
+    $objets_ouverts = [];
200 200
 
201
-	foreach ($edition as $objet => $data) {
202
-		foreach ($data as $id => $auteurs) {
203
-			if (
204
-				isset($auteurs[$id_auteur])
205
-				and is_array($auteurs[$id_auteur]) // precaution
206
-				and (array_pop($auteurs[$id_auteur]) > time() - 3600)
207
-			) {
208
-				$objets_ouverts[] = [
209
-					'objet' => $objet,
210
-					'id_objet' => $id,
211
-				];
212
-			}
213
-		}
214
-	}
201
+    foreach ($edition as $objet => $data) {
202
+        foreach ($data as $id => $auteurs) {
203
+            if (
204
+                isset($auteurs[$id_auteur])
205
+                and is_array($auteurs[$id_auteur]) // precaution
206
+                and (array_pop($auteurs[$id_auteur]) > time() - 3600)
207
+            ) {
208
+                $objets_ouverts[] = [
209
+                    'objet' => $objet,
210
+                    'id_objet' => $id,
211
+                ];
212
+            }
213
+        }
214
+    }
215 215
 
216
-	return $objets_ouverts;
216
+    return $objets_ouverts;
217 217
 }
218 218
 
219 219
 /**
@@ -226,15 +226,15 @@  discard block
 block discarded – undo
226 226
  * @return void
227 227
  */
228 228
 function debloquer_tous($id_auteur) {
229
-	$edition = lire_tableau_edition();
230
-	foreach ($edition as $objet => $data) {
231
-		foreach ($data as $id => $auteurs) {
232
-			if (isset($auteurs[$id_auteur])) {
233
-				unset($edition[$objet][$id][$id_auteur]);
234
-				ecrire_tableau_edition($edition);
235
-			}
236
-		}
237
-	}
229
+    $edition = lire_tableau_edition();
230
+    foreach ($edition as $objet => $data) {
231
+        foreach ($data as $id => $auteurs) {
232
+            if (isset($auteurs[$id_auteur])) {
233
+                unset($edition[$objet][$id][$id_auteur]);
234
+                ecrire_tableau_edition($edition);
235
+            }
236
+        }
237
+    }
238 238
 }
239 239
 
240 240
 /**
@@ -252,19 +252,19 @@  discard block
 block discarded – undo
252 252
  * @return void
253 253
  */
254 254
 function debloquer_edition($id_auteur, $id_objet, $type = 'article') {
255
-	$edition = lire_tableau_edition();
255
+    $edition = lire_tableau_edition();
256 256
 
257
-	foreach ($edition as $objet => $data) {
258
-		if ($objet == $type) {
259
-			foreach ($data as $id => $auteurs) {
260
-				if (
261
-					$id == $id_objet
262
-					and isset($auteurs[$id_auteur])
263
-				) {
264
-					unset($edition[$objet][$id][$id_auteur]);
265
-					ecrire_tableau_edition($edition);
266
-				}
267
-			}
268
-		}
269
-	}
257
+    foreach ($edition as $objet => $data) {
258
+        if ($objet == $type) {
259
+            foreach ($data as $id => $auteurs) {
260
+                if (
261
+                    $id == $id_objet
262
+                    and isset($auteurs[$id_auteur])
263
+                ) {
264
+                    unset($edition[$objet][$id][$id_auteur]);
265
+                    ecrire_tableau_edition($edition);
266
+                }
267
+            }
268
+        }
269
+    }
270 270
 }
Please login to merge, or discard this patch.
config/ecran_securite.php 1 patch
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -15,11 +15,11 @@  discard block
 block discarded – undo
15 15
  * Test utilisateur
16 16
  */
17 17
 if (isset($_GET['test_ecran_securite'])) {
18
-	$ecran_securite_raison = 'test ' . _ECRAN_SECURITE;
18
+    $ecran_securite_raison = 'test ' . _ECRAN_SECURITE;
19 19
 }
20 20
 
21 21
 if (file_exists($f = __DIR__ . DIRECTORY_SEPARATOR  . 'ecran_securite_options.php')) {
22
-	include ($f);
22
+    include ($f);
23 23
 }
24 24
 
25 25
 /*
@@ -29,222 +29,222 @@  discard block
 block discarded – undo
29 29
  * le load depasse ECRAN_SECURITE_LOAD)
30 30
  */
31 31
 if (!defined('_IS_BOT') and isset($_GET['var_isbot'])) {
32
-	define('_IS_BOT', $_GET['var_isbot'] ? true : false);
32
+    define('_IS_BOT', $_GET['var_isbot'] ? true : false);
33 33
 }
34 34
 
35 35
 /*
36 36
  * Détecteur de robot d'indexation
37 37
  */
38 38
 if (!defined('_IS_BOT')) {
39
-	define(
40
-		'_IS_BOT',
41
-		isset($_SERVER['HTTP_USER_AGENT'])
42
-			and preg_match(
43
-				','
44
-					. implode('|', array(
45
-						// mots generiques
46
-						'bot',
47
-						'slurp',
48
-						'crawler',
49
-						'crwlr',
50
-						'java',
51
-						'monitoring',
52
-						'spider',
53
-						'webvac',
54
-						'yandex',
55
-						'MSIE 6\.0', // botnet 99,9% du temps
56
-						// UA plus cibles
57
-						'200please',
58
-						'80legs',
59
-						'a6-indexer',
60
-						'aboundex',
61
-						'accoona',
62
-						'acrylicapps',
63
-						'addthis',
64
-						'adressendeutschland',
65
-						'alexa',
66
-						'altavista',
67
-						'analyticsseo',
68
-						'antennapod',
69
-						'arachnys',
70
-						'archive',
71
-						'argclrint',
72
-						'aspseek',
73
-						'baidu',
74
-						'begunadvertising',
75
-						'bing',
76
-						'bloglines',
77
-						'buck',
78
-						'browsershots',
79
-						'bubing',
80
-						'butterfly',
81
-						'changedetection',
82
-						'charlotte',
83
-						'chilkat',
84
-						'china',
85
-						'coccoc',
86
-						'crowsnest',
87
-						'dataminr',
88
-						'daumoa',
89
-						'dlvr\.it',
90
-						'dlweb',
91
-						'drupal',
92
-						'ec2linkfinder',
93
-						'eset\.com',
94
-						'estyle',
95
-						'exalead',
96
-						'ezooms',
97
-						'facebookexternalhit',
98
-						'facebookplatform',
99
-						'fairshare',
100
-						'feedfetcher',
101
-						'feedfetcher-google',
102
-						'feedly',
103
-						'fetch',
104
-						'flipboardproxy',
105
-						'genieo',
106
-						'google',
107
-						'go-http-client',
108
-						'grapeshot',
109
-						'hatena-useragent',
110
-						'head',
111
-						'hosttracker',
112
-						'hubspot',
113
-						'ia_archiver',
114
-						'ichiro',
115
-						'iltrovatore-setaccio',
116
-						'immediatenet',
117
-						'ina',
118
-						'inoreader',
119
-						'infegyatlas',
120
-						'infohelfer',
121
-						'instapaper',
122
-						'jabse',
123
-						'james',
124
-						'jersey',
125
-						'kumkie',
126
-						'linkdex',
127
-						'linkfluence',
128
-						'linkwalker',
129
-						'litefinder',
130
-						'loadimpactpageanalyzer',
131
-						'ltx71',
132
-						'luminate',
133
-						'lycos',
134
-						'lycosa',
135
-						'mediapartners-google',
136
-						'msai',
137
-						'myapp',
138
-						'nativehost',
139
-						'najdi',
140
-						'netcraftsurveyagent',
141
-						'netestate',
142
-						'netseer',
143
-						'netnewswire',
144
-						'newspaper',
145
-						'newsblur',
146
-						'nuhk',
147
-						'nuzzel',
148
-						'okhttp',
149
-						'otmedia',
150
-						'owlin',
151
-						'owncloud',
152
-						'panscient',
153
-						'paper\.li',
154
-						'parsijoo',
155
-						'protopage',
156
-						'plukkie',
157
-						'proximic',
158
-						'pubsub',
159
-						'python',
160
-						'qirina',
161
-						'qoshe',
162
-						'qualidator',
163
-						'qwantify',
164
-						'rambler',
165
-						'readability',
166
-						'ruby',
167
-						'sbsearch',
168
-						'scoop\.it',
169
-						'scooter',
170
-						'scoutjet',
171
-						'scrapy',
172
-						'scrubby',
173
-						'scrubbybloglines',
174
-						'shareaholic',
175
-						'shopwiki',
176
-						'simplepie',
177
-						'sistrix',
178
-						'sitechecker',
179
-						'siteexplorer',
180
-						'snapshot',
181
-						'sogou',
182
-						'special_archiver',
183
-						'speedy',
184
-						'spinn3r',
185
-						'spreadtrum',
186
-						'steeler',
187
-						'subscriber',
188
-						'suma',
189
-						'superdownloads',
190
-						'svenska-webbsido',
191
-						'teoma',
192
-						'the knowledge AI',
193
-						'thumbshots',
194
-						'tineye',
195
-						'traackr',
196
-						'trendiction',
197
-						'trendsmap',
198
-						'tweetedtimes',
199
-						'tweetmeme',
200
-						'universalfeedparser',
201
-						'uaslinkchecker',
202
-						'undrip',
203
-						'unwindfetchor',
204
-						'upday',
205
-						'vedma',
206
-						'vkshare',
207
-						'vm',
208
-						'wch',
209
-						'webalta',
210
-						'webcookies',
211
-						'webparser',
212
-						'webthumbnail',
213
-						'wesee',
214
-						'wise-guys',
215
-						'woko',
216
-						'wordpress',
217
-						'wotbox',
218
-						'y!j-bri',
219
-						'y!j-bro',
220
-						'y!j-brw',
221
-						'y!j-bsc',
222
-						'yahoo',
223
-						'yahoo!',
224
-						'yahooysmcm',
225
-						'ymobactus',
226
-						'yats',
227
-						'yeti',
228
-						'zeerch'
229
-					)) . ',i',
230
-				(string)$_SERVER['HTTP_USER_AGENT']
231
-			)
232
-	);
39
+    define(
40
+        '_IS_BOT',
41
+        isset($_SERVER['HTTP_USER_AGENT'])
42
+            and preg_match(
43
+                ','
44
+                    . implode('|', array(
45
+                        // mots generiques
46
+                        'bot',
47
+                        'slurp',
48
+                        'crawler',
49
+                        'crwlr',
50
+                        'java',
51
+                        'monitoring',
52
+                        'spider',
53
+                        'webvac',
54
+                        'yandex',
55
+                        'MSIE 6\.0', // botnet 99,9% du temps
56
+                        // UA plus cibles
57
+                        '200please',
58
+                        '80legs',
59
+                        'a6-indexer',
60
+                        'aboundex',
61
+                        'accoona',
62
+                        'acrylicapps',
63
+                        'addthis',
64
+                        'adressendeutschland',
65
+                        'alexa',
66
+                        'altavista',
67
+                        'analyticsseo',
68
+                        'antennapod',
69
+                        'arachnys',
70
+                        'archive',
71
+                        'argclrint',
72
+                        'aspseek',
73
+                        'baidu',
74
+                        'begunadvertising',
75
+                        'bing',
76
+                        'bloglines',
77
+                        'buck',
78
+                        'browsershots',
79
+                        'bubing',
80
+                        'butterfly',
81
+                        'changedetection',
82
+                        'charlotte',
83
+                        'chilkat',
84
+                        'china',
85
+                        'coccoc',
86
+                        'crowsnest',
87
+                        'dataminr',
88
+                        'daumoa',
89
+                        'dlvr\.it',
90
+                        'dlweb',
91
+                        'drupal',
92
+                        'ec2linkfinder',
93
+                        'eset\.com',
94
+                        'estyle',
95
+                        'exalead',
96
+                        'ezooms',
97
+                        'facebookexternalhit',
98
+                        'facebookplatform',
99
+                        'fairshare',
100
+                        'feedfetcher',
101
+                        'feedfetcher-google',
102
+                        'feedly',
103
+                        'fetch',
104
+                        'flipboardproxy',
105
+                        'genieo',
106
+                        'google',
107
+                        'go-http-client',
108
+                        'grapeshot',
109
+                        'hatena-useragent',
110
+                        'head',
111
+                        'hosttracker',
112
+                        'hubspot',
113
+                        'ia_archiver',
114
+                        'ichiro',
115
+                        'iltrovatore-setaccio',
116
+                        'immediatenet',
117
+                        'ina',
118
+                        'inoreader',
119
+                        'infegyatlas',
120
+                        'infohelfer',
121
+                        'instapaper',
122
+                        'jabse',
123
+                        'james',
124
+                        'jersey',
125
+                        'kumkie',
126
+                        'linkdex',
127
+                        'linkfluence',
128
+                        'linkwalker',
129
+                        'litefinder',
130
+                        'loadimpactpageanalyzer',
131
+                        'ltx71',
132
+                        'luminate',
133
+                        'lycos',
134
+                        'lycosa',
135
+                        'mediapartners-google',
136
+                        'msai',
137
+                        'myapp',
138
+                        'nativehost',
139
+                        'najdi',
140
+                        'netcraftsurveyagent',
141
+                        'netestate',
142
+                        'netseer',
143
+                        'netnewswire',
144
+                        'newspaper',
145
+                        'newsblur',
146
+                        'nuhk',
147
+                        'nuzzel',
148
+                        'okhttp',
149
+                        'otmedia',
150
+                        'owlin',
151
+                        'owncloud',
152
+                        'panscient',
153
+                        'paper\.li',
154
+                        'parsijoo',
155
+                        'protopage',
156
+                        'plukkie',
157
+                        'proximic',
158
+                        'pubsub',
159
+                        'python',
160
+                        'qirina',
161
+                        'qoshe',
162
+                        'qualidator',
163
+                        'qwantify',
164
+                        'rambler',
165
+                        'readability',
166
+                        'ruby',
167
+                        'sbsearch',
168
+                        'scoop\.it',
169
+                        'scooter',
170
+                        'scoutjet',
171
+                        'scrapy',
172
+                        'scrubby',
173
+                        'scrubbybloglines',
174
+                        'shareaholic',
175
+                        'shopwiki',
176
+                        'simplepie',
177
+                        'sistrix',
178
+                        'sitechecker',
179
+                        'siteexplorer',
180
+                        'snapshot',
181
+                        'sogou',
182
+                        'special_archiver',
183
+                        'speedy',
184
+                        'spinn3r',
185
+                        'spreadtrum',
186
+                        'steeler',
187
+                        'subscriber',
188
+                        'suma',
189
+                        'superdownloads',
190
+                        'svenska-webbsido',
191
+                        'teoma',
192
+                        'the knowledge AI',
193
+                        'thumbshots',
194
+                        'tineye',
195
+                        'traackr',
196
+                        'trendiction',
197
+                        'trendsmap',
198
+                        'tweetedtimes',
199
+                        'tweetmeme',
200
+                        'universalfeedparser',
201
+                        'uaslinkchecker',
202
+                        'undrip',
203
+                        'unwindfetchor',
204
+                        'upday',
205
+                        'vedma',
206
+                        'vkshare',
207
+                        'vm',
208
+                        'wch',
209
+                        'webalta',
210
+                        'webcookies',
211
+                        'webparser',
212
+                        'webthumbnail',
213
+                        'wesee',
214
+                        'wise-guys',
215
+                        'woko',
216
+                        'wordpress',
217
+                        'wotbox',
218
+                        'y!j-bri',
219
+                        'y!j-bro',
220
+                        'y!j-brw',
221
+                        'y!j-bsc',
222
+                        'yahoo',
223
+                        'yahoo!',
224
+                        'yahooysmcm',
225
+                        'ymobactus',
226
+                        'yats',
227
+                        'yeti',
228
+                        'zeerch'
229
+                    )) . ',i',
230
+                (string)$_SERVER['HTTP_USER_AGENT']
231
+            )
232
+    );
233 233
 }
234 234
 if (!defined('_IS_BOT_FRIEND')) {
235
-	define(
236
-		'_IS_BOT_FRIEND',
237
-		isset($_SERVER['HTTP_USER_AGENT'])
238
-			and preg_match(
239
-				',' . implode('|', array(
240
-					'facebookexternalhit',
241
-					'twitterbot',
242
-					'flipboardproxy',
243
-					'wordpress'
244
-				)) . ',i',
245
-				(string)$_SERVER['HTTP_USER_AGENT']
246
-			)
247
-	);
235
+    define(
236
+        '_IS_BOT_FRIEND',
237
+        isset($_SERVER['HTTP_USER_AGENT'])
238
+            and preg_match(
239
+                ',' . implode('|', array(
240
+                    'facebookexternalhit',
241
+                    'twitterbot',
242
+                    'flipboardproxy',
243
+                    'wordpress'
244
+                )) . ',i',
245
+                (string)$_SERVER['HTTP_USER_AGENT']
246
+            )
247
+    );
248 248
 }
249 249
 
250 250
 /*
@@ -256,28 +256,28 @@  discard block
 block discarded – undo
256 256
  */
257 257
 $_exceptions = array('id_table', 'id_base', 'id_parent', 'id_article_pdf');
258 258
 foreach ($_GET as $var => $val) {
259
-	if (
260
-		$_GET[$var] and strncmp($var, "id_", 3) == 0
261
-		and !in_array($var, $_exceptions)
262
-	) {
263
-		$_GET[$var] = is_array($_GET[$var]) ? @array_map('intval', $_GET[$var]) : intval($_GET[$var]);
264
-	}
259
+    if (
260
+        $_GET[$var] and strncmp($var, "id_", 3) == 0
261
+        and !in_array($var, $_exceptions)
262
+    ) {
263
+        $_GET[$var] = is_array($_GET[$var]) ? @array_map('intval', $_GET[$var]) : intval($_GET[$var]);
264
+    }
265 265
 }
266 266
 foreach ($_POST as $var => $val) {
267
-	if (
268
-		$_POST[$var] and strncmp($var, "id_", 3) == 0
269
-		and !in_array($var, $_exceptions)
270
-	) {
271
-		$_POST[$var] = is_array($_POST[$var]) ? @array_map('intval', $_POST[$var]) : intval($_POST[$var]);
272
-	}
267
+    if (
268
+        $_POST[$var] and strncmp($var, "id_", 3) == 0
269
+        and !in_array($var, $_exceptions)
270
+    ) {
271
+        $_POST[$var] = is_array($_POST[$var]) ? @array_map('intval', $_POST[$var]) : intval($_POST[$var]);
272
+    }
273 273
 }
274 274
 foreach ($GLOBALS as $var => $val) {
275
-	if (
276
-		$GLOBALS[$var] and strncmp($var, "id_", 3) == 0
277
-		and !in_array($var, $_exceptions)
278
-	) {
279
-		$GLOBALS[$var] = is_array($GLOBALS[$var]) ? @array_map('intval', $GLOBALS[$var]) : intval($GLOBALS[$var]);
280
-	}
275
+    if (
276
+        $GLOBALS[$var] and strncmp($var, "id_", 3) == 0
277
+        and !in_array($var, $_exceptions)
278
+    ) {
279
+        $GLOBALS[$var] = is_array($GLOBALS[$var]) ? @array_map('intval', $GLOBALS[$var]) : intval($GLOBALS[$var]);
280
+    }
281 281
 }
282 282
 
283 283
 /*
@@ -290,116 +290,116 @@  discard block
 block discarded – undo
290 290
  * Contrôle de quelques variables (XSS)
291 291
  */
292 292
 foreach (array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
293
-	if (isset($_GET[$var])) {
294
-		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
295
-	}
296
-	if (isset($_POST[$var])) {
297
-		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
298
-	}
293
+    if (isset($_GET[$var])) {
294
+        $_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
295
+    }
296
+    if (isset($_POST[$var])) {
297
+        $_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
298
+    }
299 299
 }
300 300
 
301 301
 /*
302 302
  * Filtre l'accès à spip_acces_doc (injection SQL en 1.8.2x)
303 303
  */
304 304
 if (isset($_SERVER['REQUEST_URI'])) {
305
-	if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
306
-		$file = addslashes((string)$_GET['file']);
307
-	}
305
+    if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
306
+        $file = addslashes((string)$_GET['file']);
307
+    }
308 308
 }
309 309
 
310 310
 /*
311 311
  * Pas d'inscription abusive
312 312
  */
313 313
 if (
314
-	isset($_REQUEST['mode']) and isset($_REQUEST['page'])
315
-	and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
316
-	and $_REQUEST['page'] == "identifiants"
314
+    isset($_REQUEST['mode']) and isset($_REQUEST['page'])
315
+    and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
316
+    and $_REQUEST['page'] == "identifiants"
317 317
 ) {
318
-	$ecran_securite_raison = "identifiants";
318
+    $ecran_securite_raison = "identifiants";
319 319
 }
320 320
 
321 321
 /*
322 322
  * Agenda joue à l'injection php
323 323
  */
324 324
 if (
325
-	isset($_REQUEST['partie_cal'])
326
-	and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal'])
325
+    isset($_REQUEST['partie_cal'])
326
+    and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal'])
327 327
 ) {
328
-	$ecran_securite_raison = "partie_cal";
328
+    $ecran_securite_raison = "partie_cal";
329 329
 }
330 330
 if (
331
-	isset($_REQUEST['echelle'])
332
-	and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle'])
331
+    isset($_REQUEST['echelle'])
332
+    and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle'])
333 333
 ) {
334
-	$ecran_securite_raison = "echelle";
334
+    $ecran_securite_raison = "echelle";
335 335
 }
336 336
 
337 337
 /*
338 338
  * Espace privé
339 339
  */
340 340
 if (
341
-	isset($_REQUEST['exec'])
342
-	and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec'])
341
+    isset($_REQUEST['exec'])
342
+    and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec'])
343 343
 ) {
344
-	$ecran_securite_raison = "exec";
344
+    $ecran_securite_raison = "exec";
345 345
 }
346 346
 if (
347
-	isset($_REQUEST['cherche_auteur'])
348
-	and preg_match(',[<],', (string)$_REQUEST['cherche_auteur'])
347
+    isset($_REQUEST['cherche_auteur'])
348
+    and preg_match(',[<],', (string)$_REQUEST['cherche_auteur'])
349 349
 ) {
350
-	$ecran_securite_raison = "cherche_auteur";
350
+    $ecran_securite_raison = "cherche_auteur";
351 351
 }
352 352
 if (
353
-	isset($_REQUEST['exec'])
354
-	and $_REQUEST['exec'] == 'auteurs'
355
-	and isset($_REQUEST['recherche'])
356
-	and preg_match(',[<],', (string)$_REQUEST['recherche'])
353
+    isset($_REQUEST['exec'])
354
+    and $_REQUEST['exec'] == 'auteurs'
355
+    and isset($_REQUEST['recherche'])
356
+    and preg_match(',[<],', (string)$_REQUEST['recherche'])
357 357
 ) {
358
-	$ecran_securite_raison = "recherche";
358
+    $ecran_securite_raison = "recherche";
359 359
 }
360 360
 if (
361
-	isset($_REQUEST['exec'])
362
-	and $_REQUEST['exec'] == 'info_plugin'
363
-	and isset($_REQUEST['plugin'])
364
-	and preg_match(',[<],', (string)$_REQUEST['plugin'])
361
+    isset($_REQUEST['exec'])
362
+    and $_REQUEST['exec'] == 'info_plugin'
363
+    and isset($_REQUEST['plugin'])
364
+    and preg_match(',[<],', (string)$_REQUEST['plugin'])
365 365
 ) {
366
-	$ecran_securite_raison = "plugin";
366
+    $ecran_securite_raison = "plugin";
367 367
 }
368 368
 if (
369
-	isset($_REQUEST['exec'])
370
-	and $_REQUEST['exec'] == 'puce_statut'
371
-	and isset($_REQUEST['id'])
372
-	and !intval($_REQUEST['id'])
369
+    isset($_REQUEST['exec'])
370
+    and $_REQUEST['exec'] == 'puce_statut'
371
+    and isset($_REQUEST['id'])
372
+    and !intval($_REQUEST['id'])
373 373
 ) {
374
-	$ecran_securite_raison = "puce_statut";
374
+    $ecran_securite_raison = "puce_statut";
375 375
 }
376 376
 if (
377
-	isset($_REQUEST['action'])
378
-	and $_REQUEST['action'] == 'configurer'
377
+    isset($_REQUEST['action'])
378
+    and $_REQUEST['action'] == 'configurer'
379 379
 ) {
380
-	if (
381
-		@file_exists('inc_version.php')
382
-		or @file_exists('ecrire/inc_version.php')
383
-	) {
384
-		function action_configurer() {
385
-			include_spip('inc/autoriser');
386
-			if (!autoriser('configurer', _request('configuration'))) {
387
-				include_spip('inc/minipres');
388
-				echo minipres(_T('info_acces_interdit'));
389
-				exit;
390
-			}
391
-			require _DIR_RESTREINT . 'action/configurer.php';
392
-			action_configurer_dist();
393
-		}
394
-	}
380
+    if (
381
+        @file_exists('inc_version.php')
382
+        or @file_exists('ecrire/inc_version.php')
383
+    ) {
384
+        function action_configurer() {
385
+            include_spip('inc/autoriser');
386
+            if (!autoriser('configurer', _request('configuration'))) {
387
+                include_spip('inc/minipres');
388
+                echo minipres(_T('info_acces_interdit'));
389
+                exit;
390
+            }
391
+            require _DIR_RESTREINT . 'action/configurer.php';
392
+            action_configurer_dist();
393
+        }
394
+    }
395 395
 }
396 396
 if (
397
-	isset($_REQUEST['action'])
398
-	and $_REQUEST['action'] == 'ordonner_liens_documents'
399
-	and isset($_REQUEST['ordre'])
400
-	and is_string($_REQUEST['ordre'])
397
+    isset($_REQUEST['action'])
398
+    and $_REQUEST['action'] == 'ordonner_liens_documents'
399
+    and isset($_REQUEST['ordre'])
400
+    and is_string($_REQUEST['ordre'])
401 401
 ) {
402
-	$ecran_securite_raison = "ordre a la chaine";
402
+    $ecran_securite_raison = "ordre a la chaine";
403 403
 }
404 404
 
405 405
 
@@ -407,29 +407,29 @@  discard block
 block discarded – undo
407 407
  * Bloque les requêtes contenant %00 (manipulation d'include)
408 408
  */
409 409
 if (strpos(
410
-	(function_exists('get_magic_quotes_gpc') and @get_magic_quotes_gpc())
411
-		? stripslashes(serialize($_REQUEST))
412
-		: serialize($_REQUEST),
413
-	chr(0)
410
+    (function_exists('get_magic_quotes_gpc') and @get_magic_quotes_gpc())
411
+        ? stripslashes(serialize($_REQUEST))
412
+        : serialize($_REQUEST),
413
+    chr(0)
414 414
 ) !== false) {
415
-	$ecran_securite_raison = "%00";
415
+    $ecran_securite_raison = "%00";
416 416
 }
417 417
 
418 418
 /*
419 419
  * Bloque les requêtes fond=formulaire_
420 420
  */
421 421
 if (
422
-	isset($_REQUEST['fond'])
423
-	and preg_match(',^formulaire_,i', $_REQUEST['fond'])
422
+    isset($_REQUEST['fond'])
423
+    and preg_match(',^formulaire_,i', $_REQUEST['fond'])
424 424
 ) {
425
-	$ecran_securite_raison = "fond=formulaire_";
425
+    $ecran_securite_raison = "fond=formulaire_";
426 426
 }
427 427
 
428 428
 /*
429 429
  * Bloque les requêtes du type ?GLOBALS[type_urls]=toto (bug vieux php)
430 430
  */
431 431
 if (isset($_REQUEST['GLOBALS'])) {
432
-	$ecran_securite_raison = "GLOBALS[GLOBALS]";
432
+    $ecran_securite_raison = "GLOBALS[GLOBALS]";
433 433
 }
434 434
 
435 435
 /*
@@ -438,14 +438,14 @@  discard block
 block discarded – undo
438 438
  * les paginations entremélées
439 439
  */
440 440
 if (_IS_BOT) {
441
-	if (
442
-		(isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
443
-		or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
444
-		or (isset($_REQUEST['calendrier_annee']) and strpos((string)$_SERVER['REQUEST_URI'], 'debut_'))
445
-		or (isset($_REQUEST['calendrier_annee']) and preg_match(',[?&]calendrier_annee=.*&calendrier_annee=,', (string)$_SERVER['REQUEST_URI']))
446
-	) {
447
-		$ecran_securite_raison = "robot agenda/double pagination";
448
-	}
441
+    if (
442
+        (isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
443
+        or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
444
+        or (isset($_REQUEST['calendrier_annee']) and strpos((string)$_SERVER['REQUEST_URI'], 'debut_'))
445
+        or (isset($_REQUEST['calendrier_annee']) and preg_match(',[?&]calendrier_annee=.*&calendrier_annee=,', (string)$_SERVER['REQUEST_URI']))
446
+    ) {
447
+        $ecran_securite_raison = "robot agenda/double pagination";
448
+    }
449 449
 }
450 450
 
451 451
 /*
@@ -453,82 +453,82 @@  discard block
 block discarded – undo
453 453
  * Bloque un XSS sur une page inexistante
454 454
  */
455 455
 if (isset($_REQUEST['page'])) {
456
-	if ($_REQUEST['page'] == 'test_cfg') {
457
-		$ecran_securite_raison = "test_cfg";
458
-	}
459
-	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page'])) {
460
-		$ecran_securite_raison = "xsspage";
461
-	}
462
-	if (
463
-		$_REQUEST['page'] == '404'
464
-		and isset($_REQUEST['erreur'])
465
-	) {
466
-		$ecran_securite_raison = "xss404";
467
-	}
456
+    if ($_REQUEST['page'] == 'test_cfg') {
457
+        $ecran_securite_raison = "test_cfg";
458
+    }
459
+    if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page'])) {
460
+        $ecran_securite_raison = "xsspage";
461
+    }
462
+    if (
463
+        $_REQUEST['page'] == '404'
464
+        and isset($_REQUEST['erreur'])
465
+    ) {
466
+        $ecran_securite_raison = "xss404";
467
+    }
468 468
 }
469 469
 
470 470
 /*
471 471
  * XSS par array
472 472
  */
473 473
 foreach (array('var_login') as $var) {
474
-	if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var])) {
475
-		$ecran_securite_raison = "xss " . $var;
476
-	}
474
+    if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var])) {
475
+        $ecran_securite_raison = "xss " . $var;
476
+    }
477 477
 }
478 478
 
479 479
 /*
480 480
  * Parade antivirale contre un cheval de troie
481 481
  */
482 482
 if (!function_exists('tmp_lkojfghx')) {
483
-	function tmp_lkojfghx() {}
484
-	function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
485
-		// si jamais on est arrivé ici sur une erreur php
486
-		// et qu'un autre gestionnaire d'erreur est défini, l'appeller
487
-		if ($b && $GLOBALS['tmp_xhgfjokl']) {
488
-			call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
489
-		}
490
-	}
483
+    function tmp_lkojfghx() {}
484
+    function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
485
+        // si jamais on est arrivé ici sur une erreur php
486
+        // et qu'un autre gestionnaire d'erreur est défini, l'appeller
487
+        if ($b && $GLOBALS['tmp_xhgfjokl']) {
488
+            call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
489
+        }
490
+    }
491 491
 }
492 492
 if (isset($_POST['tmp_lkojfghx3'])) {
493
-	$ecran_securite_raison = "gumblar";
493
+    $ecran_securite_raison = "gumblar";
494 494
 }
495 495
 
496 496
 /*
497 497
  * Outils XML mal sécurisés < 2.0.9
498 498
  */
499 499
 if (isset($_REQUEST['transformer_xml'])) {
500
-	$ecran_securite_raison = "transformer_xml";
500
+    $ecran_securite_raison = "transformer_xml";
501 501
 }
502 502
 
503 503
 /*
504 504
  * Outils XML mal sécurisés again
505 505
  */
506 506
 if (isset($_REQUEST['var_url']) and $_REQUEST['var_url'] and isset($_REQUEST['exec']) and $_REQUEST['exec'] == 'valider_xml') {
507
-	$url = trim($_REQUEST['var_url']);
508
-	if (
509
-		strncmp($url, '/', 1) == 0
510
-		or (($p = strpos($url, '..')) !== false and strpos($url, '..', $p + 3) !== false)
511
-		or (($p = strpos($url, '..')) !== false and strpos($url, 'IMG', $p + 3) !== false)
512
-		or (strpos($url, '://') !== false or strpos($url, ':\\') !== false)
513
-	) {
514
-		$ecran_securite_raison = 'URL interdite pour var_url';
515
-	}
507
+    $url = trim($_REQUEST['var_url']);
508
+    if (
509
+        strncmp($url, '/', 1) == 0
510
+        or (($p = strpos($url, '..')) !== false and strpos($url, '..', $p + 3) !== false)
511
+        or (($p = strpos($url, '..')) !== false and strpos($url, 'IMG', $p + 3) !== false)
512
+        or (strpos($url, '://') !== false or strpos($url, ':\\') !== false)
513
+    ) {
514
+        $ecran_securite_raison = 'URL interdite pour var_url';
515
+    }
516 516
 }
517 517
 
518 518
 /*
519 519
  * Sauvegarde mal securisée < 2.0.9
520 520
  */
521 521
 if (
522
-	isset($_REQUEST['nom_sauvegarde'])
523
-	and strstr((string)$_REQUEST['nom_sauvegarde'], '/')
522
+    isset($_REQUEST['nom_sauvegarde'])
523
+    and strstr((string)$_REQUEST['nom_sauvegarde'], '/')
524 524
 ) {
525
-	$ecran_securite_raison = 'nom_sauvegarde manipulee';
525
+    $ecran_securite_raison = 'nom_sauvegarde manipulee';
526 526
 }
527 527
 if (
528
-	isset($_REQUEST['znom_sauvegarde'])
529
-	and strstr((string)$_REQUEST['znom_sauvegarde'], '/')
528
+    isset($_REQUEST['znom_sauvegarde'])
529
+    and strstr((string)$_REQUEST['znom_sauvegarde'], '/')
530 530
 ) {
531
-	$ecran_securite_raison = 'znom_sauvegarde manipulee';
531
+    $ecran_securite_raison = 'znom_sauvegarde manipulee';
532 532
 }
533 533
 
534 534
 
@@ -537,57 +537,57 @@  discard block
 block discarded – undo
537 537
  * on vérifie 'page' pour ne pas bloquer ... drupal
538 538
  */
539 539
 if (
540
-	isset($_REQUEST['op']) and isset($_REQUEST['page'])
541
-	and $_REQUEST['op'] !== preg_replace('/[^\\-\w]/', '', $_REQUEST['op'])
540
+    isset($_REQUEST['op']) and isset($_REQUEST['page'])
541
+    and $_REQUEST['op'] !== preg_replace('/[^\\-\w]/', '', $_REQUEST['op'])
542 542
 ) {
543
-	$ecran_securite_raison = 'op';
543
+    $ecran_securite_raison = 'op';
544 544
 }
545 545
 
546 546
 /*
547 547
  * Forms & Table ne se méfiait pas assez des uploads de fichiers
548 548
  */
549 549
 if (count($_FILES)) {
550
-	foreach ($_FILES as $k => $v) {
551
-		if (
552
-			preg_match(',^fichier_\d+$,', $k)
553
-			and preg_match(',\.php,i', $v['name'])
554
-		) {
555
-			unset($_FILES[$k]);
556
-		}
557
-	}
550
+    foreach ($_FILES as $k => $v) {
551
+        if (
552
+            preg_match(',^fichier_\d+$,', $k)
553
+            and preg_match(',\.php,i', $v['name'])
554
+        ) {
555
+            unset($_FILES[$k]);
556
+        }
557
+    }
558 558
 }
559 559
 /*
560 560
  * et Contact trop laxiste avec une variable externe
561 561
  * on bloque pas le post pour eviter de perdre des donnees mais on unset la variable et c'est tout
562 562
  */
563 563
 if (isset($_REQUEST['pj_enregistrees_nom']) and $_REQUEST['pj_enregistrees_nom']) {
564
-	unset($_REQUEST['pj_enregistrees_nom']);
565
-	unset($_GET['pj_enregistrees_nom']);
566
-	unset($_POST['pj_enregistrees_nom']);
564
+    unset($_REQUEST['pj_enregistrees_nom']);
565
+    unset($_GET['pj_enregistrees_nom']);
566
+    unset($_POST['pj_enregistrees_nom']);
567 567
 }
568 568
 
569 569
 /*
570 570
  * reinstall=oui un peu trop permissif
571 571
  */
572 572
 if (
573
-	isset($_REQUEST['reinstall'])
574
-	and $_REQUEST['reinstall'] == 'oui'
573
+    isset($_REQUEST['reinstall'])
574
+    and $_REQUEST['reinstall'] == 'oui'
575 575
 ) {
576
-	$ecran_securite_raison = 'reinstall=oui';
576
+    $ecran_securite_raison = 'reinstall=oui';
577 577
 }
578 578
 
579 579
 /*
580 580
  * Pas d'action pendant l'install
581 581
  */
582 582
 if (isset($_REQUEST['exec']) and $_REQUEST['exec'] === 'install' and isset($_REQUEST['action'])) {
583
-	$ecran_securite_raison = 'install&action impossibles';
583
+    $ecran_securite_raison = 'install&action impossibles';
584 584
 }
585 585
 
586 586
 /*
587 587
  * Échappement xss referer
588 588
  */
589 589
 if (isset($_SERVER['HTTP_REFERER'])) {
590
-	$_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
590
+    $_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
591 591
 }
592 592
 
593 593
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
  * Echappement HTTP_X_FORWARDED_HOST
596 596
  */
597 597
 if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
598
-	$_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
598
+    $_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
599 599
 }
600 600
 
601 601
 
@@ -603,9 +603,9 @@  discard block
 block discarded – undo
603 603
  * Pas d'erreur dans l'erreur
604 604
  */
605 605
 if (isset($_REQUEST['var_erreur']) and isset($_REQUEST['page']) and $_REQUEST['page'] === 'login') {
606
-	if (strlen($_REQUEST['var_erreur']) !== strcspn($_REQUEST['var_erreur'], '<>')) {
607
-		$ecran_securite_raison = 'var_erreur incorrecte';
608
-	}
606
+    if (strlen($_REQUEST['var_erreur']) !== strcspn($_REQUEST['var_erreur'], '<>')) {
607
+        $ecran_securite_raison = 'var_erreur incorrecte';
608
+    }
609 609
 }
610 610
 
611 611
 
@@ -613,30 +613,30 @@  discard block
 block discarded – undo
613 613
  * Réinjection des clés en html dans l'admin r19561
614 614
  */
615 615
 if (
616
-	(isset($_SERVER['REQUEST_URI']) and strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false)
617
-	or isset($_REQUEST['var_memotri'])
616
+    (isset($_SERVER['REQUEST_URI']) and strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false)
617
+    or isset($_REQUEST['var_memotri'])
618 618
 ) {
619
-	$zzzz = implode("", array_keys($_REQUEST));
620
-	if (strlen($zzzz) != strcspn($zzzz, '<>"\'')) {
621
-		$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
622
-	}
619
+    $zzzz = implode("", array_keys($_REQUEST));
620
+    if (strlen($zzzz) != strcspn($zzzz, '<>"\'')) {
621
+        $ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
622
+    }
623 623
 }
624 624
 
625 625
 /*
626 626
  * Injection par connect
627 627
  */
628 628
 if (
629
-	isset($_REQUEST['connect'])
630
-	// cas qui permettent de sortir d'un commentaire PHP
631
-	and (
632
-		strpos($_REQUEST['connect'], "?") !== false
633
-		or strpos($_REQUEST['connect'], "<") !== false
634
-		or strpos($_REQUEST['connect'], ">") !== false
635
-		or strpos($_REQUEST['connect'], "\n") !== false
636
-		or strpos($_REQUEST['connect'], "\r") !== false
637
-	)
629
+    isset($_REQUEST['connect'])
630
+    // cas qui permettent de sortir d'un commentaire PHP
631
+    and (
632
+        strpos($_REQUEST['connect'], "?") !== false
633
+        or strpos($_REQUEST['connect'], "<") !== false
634
+        or strpos($_REQUEST['connect'], ">") !== false
635
+        or strpos($_REQUEST['connect'], "\n") !== false
636
+        or strpos($_REQUEST['connect'], "\r") !== false
637
+    )
638 638
 ) {
639
-	$ecran_securite_raison = "malformed connect argument";
639
+    $ecran_securite_raison = "malformed connect argument";
640 640
 }
641 641
 
642 642
 
@@ -644,9 +644,9 @@  discard block
 block discarded – undo
644 644
  * _oups donc
645 645
  */
646 646
 if (
647
-	isset($_REQUEST['_oups'])
648
-	and base64_decode($_REQUEST['_oups'], true) === false) {
649
-	$ecran_securite_raison = "malformed _oups argument";
647
+    isset($_REQUEST['_oups'])
648
+    and base64_decode($_REQUEST['_oups'], true) === false) {
649
+    $ecran_securite_raison = "malformed _oups argument";
650 650
 }
651 651
 
652 652
 
@@ -654,23 +654,23 @@  discard block
 block discarded – undo
654 654
  * S'il y a une raison de mourir, mourons
655 655
  */
656 656
 if (isset($ecran_securite_raison)) {
657
-	header("HTTP/1.0 403 Forbidden");
658
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
659
-	header("Cache-Control: no-cache, must-revalidate");
660
-	header("Pragma: no-cache");
661
-	header("Content-Type: text/html");
662
-	header("Connection: close");
663
-	die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
657
+    header("HTTP/1.0 403 Forbidden");
658
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
659
+    header("Cache-Control: no-cache, must-revalidate");
660
+    header("Pragma: no-cache");
661
+    header("Content-Type: text/html");
662
+    header("Connection: close");
663
+    die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
664 664
 }
665 665
 
666 666
 /*
667 667
  * Un filtre filtrer_entites securise
668 668
  */
669 669
 if (!function_exists('filtre_filtrer_entites_dist')) {
670
-	function filtre_filtrer_entites_dist($t) {
671
-		include_spip('inc/texte');
672
-		return interdire_scripts(filtrer_entites($t));
673
-	}
670
+    function filtre_filtrer_entites_dist($t) {
671
+        include_spip('inc/texte');
672
+        return interdire_scripts(filtrer_entites($t));
673
+    }
674 674
 }
675 675
 
676 676
 
@@ -684,35 +684,35 @@  discard block
 block discarded – undo
684 684
  * Bloque les bots quand le load déborde
685 685
  */
686 686
 if (!defined('_ECRAN_SECURITE_LOAD')) {
687
-	define('_ECRAN_SECURITE_LOAD', 4);
687
+    define('_ECRAN_SECURITE_LOAD', 4);
688 688
 }
689 689
 
690 690
 if (
691
-	defined('_ECRAN_SECURITE_LOAD')
692
-	and _ECRAN_SECURITE_LOAD > 0
693
-	and _IS_BOT
694
-	and !_IS_BOT_FRIEND
695
-	and $_SERVER['REQUEST_METHOD'] === 'GET'
696
-	and (
697
-		(function_exists('sys_getloadavg')
698
-			and $load = sys_getloadavg()
699
-			and is_array($load)
700
-			and $load = array_shift($load))
701
-		or
702
-		(@is_readable('/proc/loadavg')
703
-			and $load = file_get_contents('/proc/loadavg')
704
-			and $load = floatval($load))
705
-	)
706
-	and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
707
-	and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
691
+    defined('_ECRAN_SECURITE_LOAD')
692
+    and _ECRAN_SECURITE_LOAD > 0
693
+    and _IS_BOT
694
+    and !_IS_BOT_FRIEND
695
+    and $_SERVER['REQUEST_METHOD'] === 'GET'
696
+    and (
697
+        (function_exists('sys_getloadavg')
698
+            and $load = sys_getloadavg()
699
+            and is_array($load)
700
+            and $load = array_shift($load))
701
+        or
702
+        (@is_readable('/proc/loadavg')
703
+            and $load = file_get_contents('/proc/loadavg')
704
+            and $load = floatval($load))
705
+    )
706
+    and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
707
+    and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
708 708
 ) {
709
-	//https://webmasters.stackexchange.com/questions/65674/should-i-return-a-429-or-503-status-code-to-a-bot
710
-	header("HTTP/1.0 429 Too Many Requests");
711
-	header("Retry-After: 300");
712
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
713
-	header("Cache-Control: no-cache, must-revalidate");
714
-	header("Pragma: no-cache");
715
-	header("Content-Type: text/html");
716
-	header("Connection: close");
717
-	die("<html><title>Status 429: Too Many Requests</title><body><h1>Status 429</h1><p>Too Many Requests (try again soon)</p></body></html>");
709
+    //https://webmasters.stackexchange.com/questions/65674/should-i-return-a-429-or-503-status-code-to-a-bot
710
+    header("HTTP/1.0 429 Too Many Requests");
711
+    header("Retry-After: 300");
712
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
713
+    header("Cache-Control: no-cache, must-revalidate");
714
+    header("Pragma: no-cache");
715
+    header("Content-Type: text/html");
716
+    header("Connection: close");
717
+    die("<html><title>Status 429: Too Many Requests</title><body><h1>Status 429</h1><p>Too Many Requests (try again soon)</p></body></html>");
718 718
 }
Please login to merge, or discard this patch.
ecrire/src/Chiffrer/SpipCles.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -14,171 +14,171 @@
 block discarded – undo
14 14
 
15 15
 /** Gestion des clés d’authentification / chiffrement de SPIP */
16 16
 final class SpipCles {
17
-	private static array $instances = [];
18
-
19
-	private string $file = _DIR_ETC . 'cles.php';
20
-	private Cles $cles;
21
-
22
-	public static function instance(string $file = ''): self {
23
-		if (empty(self::$instances[$file])) {
24
-			self::$instances[$file] = new self($file);
25
-		}
26
-		return self::$instances[$file];
27
-	}
28
-
29
-	/**
30
-	 * Retourne le secret du site (shorthand)
31
-	 * @uses self::getSecretSite()
32
-	 */
33
-	public static function secret_du_site(): ?string {
34
-		return (self::instance())->getSecretSite();
35
-	}
36
-
37
-	private function __construct(string $file = '') {
38
-		if ($file) {
39
-			$this->file = $file;
40
-		}
41
-		$this->cles = new Cles($this->read());
42
-	}
43
-
44
-	/**
45
-	 * Renvoyer le secret du site
46
-	 *
47
-	 * Le secret du site doit rester aussi secret que possible, et est eternel
48
-	 * On ne doit pas l'exporter
49
-	 *
50
-	 * Le secret est partagé entre une clé disque et une clé bdd
51
-	 *
52
-	 * @return string
53
-	 */
54
-	public function getSecretSite(bool $autoInit = true): ?string {
55
-		$key = $this->getKey('secret_du_site', $autoInit);
56
-		$meta = $this->getMetaKey('secret_du_site', $autoInit);
57
-		// conserve la même longeur.
58
-		return $key ^ $meta;
59
-	}
60
-
61
-	/** Renvoyer le secret des authentifications */
62
-	public function getSecretAuth(bool $autoInit = false): ?string {
63
-		return $this->getKey('secret_des_auth', $autoInit);
64
-	}
65
-	public function save(): bool {
66
-		return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
-	}
68
-
69
-	/**
70
-	 * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
-	 *
72
-	 * @param string $withKey Clé de chiffrage de la sauvegarde
73
-	 * @return string Contenu de la sauvegarde chiffrée générée
74
-	 */
75
-	public function backup(
76
-		#[\SensitiveParameter]
77
-		string $withKey
78
-	): string {
79
-		if (count($this->cles)) {
80
-			return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
-		}
82
-		return '';
83
-	}
84
-
85
-	/**
86
-	 * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
-	 * (si la sauvegarde est bien valide)
88
-	 *
89
-	 * @param string $backup Sauvegarde chiffrée (générée par backup())
90
-	 * @param int $id_auteur
91
-	 * @param string $pass
92
-	 * @return void
93
-	 */
94
-	public function restore(
95
-		string $backup,
96
-		#[\SensitiveParameter]
97
-		string $password_clair,
98
-		#[\SensitiveParameter]
99
-		string $password_hash,
100
-		int $id_auteur
101
-	): bool {
102
-		if (empty($backup)) {
103
-			return false;
104
-		}
105
-
106
-		$sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
-		$json = json_decode($sauvegarde, true);
108
-		if (!$json) {
109
-			return false;
110
-		}
111
-
112
-		// cela semble une sauvegarde valide
113
-		$cles_potentielles = array_map('base64_decode', $json);
114
-
115
-		// il faut faire une double verif sur secret_des_auth
116
-		// pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
-		// et par extension tous les passwords
118
-		if (!empty($cles_potentielles['secret_des_auth'])) {
119
-			if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
-				spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
-				unset($cles_potentielles['secret_des_auth']);
122
-			}
123
-		}
124
-
125
-		// on merge les cles pour recuperer les cles manquantes
126
-		$restauration = false;
127
-		foreach ($cles_potentielles as $name => $key) {
128
-			if (!$this->cles->has($name)) {
129
-				$this->cles->set($name, $key);
130
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
-				$restauration = true;
132
-			}
133
-		}
134
-		return $restauration;
135
-	}
136
-
137
-	private function getKey(string $name, bool $autoInit): ?string {
138
-		if ($this->cles->has($name)) {
139
-			return $this->cles->get($name);
140
-		}
141
-		if ($autoInit) {
142
-			$this->cles->generate($name);
143
-			// si l'ecriture de fichier a bien marche on peut utiliser la cle
144
-			if ($this->save()) {
145
-				return $this->cles->get($name);
146
-			}
147
-			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
-			$this->cles->delete($name);
150
-		}
151
-		return null;
152
-	}
153
-
154
-	private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
-		if (!isset($GLOBALS['meta'][$name])) {
156
-			include_spip('base/abstract_sql');
157
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
-		}
159
-		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
-		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
-			return $key;
162
-		}
163
-		if (!$autoInit) {
164
-			return null;
165
-		}
166
-		$key = Chiffrement::keygen();
167
-		ecrire_meta($name, base64_encode($key), 'non');
168
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
-
170
-		return $key;
171
-	}
172
-
173
-	private function read(): array {
174
-		lire_fichier_securise($this->file, $json);
175
-		if (
176
-			$json
177
-			and $json = \json_decode($json, true)
178
-			and is_array($json)
179
-		) {
180
-			return array_map('base64_decode', $json);
181
-		}
182
-		return [];
183
-	}
17
+    private static array $instances = [];
18
+
19
+    private string $file = _DIR_ETC . 'cles.php';
20
+    private Cles $cles;
21
+
22
+    public static function instance(string $file = ''): self {
23
+        if (empty(self::$instances[$file])) {
24
+            self::$instances[$file] = new self($file);
25
+        }
26
+        return self::$instances[$file];
27
+    }
28
+
29
+    /**
30
+     * Retourne le secret du site (shorthand)
31
+     * @uses self::getSecretSite()
32
+     */
33
+    public static function secret_du_site(): ?string {
34
+        return (self::instance())->getSecretSite();
35
+    }
36
+
37
+    private function __construct(string $file = '') {
38
+        if ($file) {
39
+            $this->file = $file;
40
+        }
41
+        $this->cles = new Cles($this->read());
42
+    }
43
+
44
+    /**
45
+     * Renvoyer le secret du site
46
+     *
47
+     * Le secret du site doit rester aussi secret que possible, et est eternel
48
+     * On ne doit pas l'exporter
49
+     *
50
+     * Le secret est partagé entre une clé disque et une clé bdd
51
+     *
52
+     * @return string
53
+     */
54
+    public function getSecretSite(bool $autoInit = true): ?string {
55
+        $key = $this->getKey('secret_du_site', $autoInit);
56
+        $meta = $this->getMetaKey('secret_du_site', $autoInit);
57
+        // conserve la même longeur.
58
+        return $key ^ $meta;
59
+    }
60
+
61
+    /** Renvoyer le secret des authentifications */
62
+    public function getSecretAuth(bool $autoInit = false): ?string {
63
+        return $this->getKey('secret_des_auth', $autoInit);
64
+    }
65
+    public function save(): bool {
66
+        return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
+    }
68
+
69
+    /**
70
+     * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
+     *
72
+     * @param string $withKey Clé de chiffrage de la sauvegarde
73
+     * @return string Contenu de la sauvegarde chiffrée générée
74
+     */
75
+    public function backup(
76
+        #[\SensitiveParameter]
77
+        string $withKey
78
+    ): string {
79
+        if (count($this->cles)) {
80
+            return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
+        }
82
+        return '';
83
+    }
84
+
85
+    /**
86
+     * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
+     * (si la sauvegarde est bien valide)
88
+     *
89
+     * @param string $backup Sauvegarde chiffrée (générée par backup())
90
+     * @param int $id_auteur
91
+     * @param string $pass
92
+     * @return void
93
+     */
94
+    public function restore(
95
+        string $backup,
96
+        #[\SensitiveParameter]
97
+        string $password_clair,
98
+        #[\SensitiveParameter]
99
+        string $password_hash,
100
+        int $id_auteur
101
+    ): bool {
102
+        if (empty($backup)) {
103
+            return false;
104
+        }
105
+
106
+        $sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
+        $json = json_decode($sauvegarde, true);
108
+        if (!$json) {
109
+            return false;
110
+        }
111
+
112
+        // cela semble une sauvegarde valide
113
+        $cles_potentielles = array_map('base64_decode', $json);
114
+
115
+        // il faut faire une double verif sur secret_des_auth
116
+        // pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
+        // et par extension tous les passwords
118
+        if (!empty($cles_potentielles['secret_des_auth'])) {
119
+            if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
+                spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
+                unset($cles_potentielles['secret_des_auth']);
122
+            }
123
+        }
124
+
125
+        // on merge les cles pour recuperer les cles manquantes
126
+        $restauration = false;
127
+        foreach ($cles_potentielles as $name => $key) {
128
+            if (!$this->cles->has($name)) {
129
+                $this->cles->set($name, $key);
130
+                spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
+                $restauration = true;
132
+            }
133
+        }
134
+        return $restauration;
135
+    }
136
+
137
+    private function getKey(string $name, bool $autoInit): ?string {
138
+        if ($this->cles->has($name)) {
139
+            return $this->cles->get($name);
140
+        }
141
+        if ($autoInit) {
142
+            $this->cles->generate($name);
143
+            // si l'ecriture de fichier a bien marche on peut utiliser la cle
144
+            if ($this->save()) {
145
+                return $this->cles->get($name);
146
+            }
147
+            // sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
+            spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
+            $this->cles->delete($name);
150
+        }
151
+        return null;
152
+    }
153
+
154
+    private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
+        if (!isset($GLOBALS['meta'][$name])) {
156
+            include_spip('base/abstract_sql');
157
+            $GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
+        }
159
+        $key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
+        if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
+            return $key;
162
+        }
163
+        if (!$autoInit) {
164
+            return null;
165
+        }
166
+        $key = Chiffrement::keygen();
167
+        ecrire_meta($name, base64_encode($key), 'non');
168
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
+
170
+        return $key;
171
+    }
172
+
173
+    private function read(): array {
174
+        lire_fichier_securise($this->file, $json);
175
+        if (
176
+            $json
177
+            and $json = \json_decode($json, true)
178
+            and is_array($json)
179
+        ) {
180
+            return array_map('base64_decode', $json);
181
+        }
182
+        return [];
183
+    }
184 184
 }
Please login to merge, or discard this patch.
prive/formulaires/configurer_preferences.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  **/
22 22
 
23 23
 if (!defined('_ECRIRE_INC_VERSION')) {
24
-	return;
24
+    return;
25 25
 }
26 26
 
27 27
 /**
@@ -31,27 +31,27 @@  discard block
 block discarded – undo
31 31
  *     Environnement du formulaire
32 32
  **/
33 33
 function formulaires_configurer_preferences_charger_dist() {
34
-	// travailler sur des meta fraiches
35
-	include_spip('inc/meta');
36
-	lire_metas();
34
+    // travailler sur des meta fraiches
35
+    include_spip('inc/meta');
36
+    lire_metas();
37 37
 
38
-	$valeurs = [];
39
-	$valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
-	$valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
-	$valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
38
+    $valeurs = [];
39
+    $valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
+    $valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
+    $valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
42 42
 
43
-	$couleurs = charger_fonction('couleurs', 'inc');
44
-	$les_couleurs = $couleurs();
45
-	foreach ($les_couleurs as $k => $c) {
46
-		$valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
-			. $GLOBALS['spip_lang_left'] . '&'
48
-			. $couleurs($k));
49
-		$valeurs['couleurs'][$k] = $c;
50
-	}
43
+    $couleurs = charger_fonction('couleurs', 'inc');
44
+    $les_couleurs = $couleurs();
45
+    foreach ($les_couleurs as $k => $c) {
46
+        $valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
+            . $GLOBALS['spip_lang_left'] . '&'
48
+            . $couleurs($k));
49
+        $valeurs['couleurs'][$k] = $c;
50
+    }
51 51
 
52
-	$valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
52
+    $valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
53 53
 
54
-	return $valeurs;
54
+    return $valeurs;
55 55
 }
56 56
 
57 57
 /**
@@ -62,33 +62,33 @@  discard block
 block discarded – undo
62 62
  **/
63 63
 function formulaires_configurer_preferences_traiter_dist() {
64 64
 
65
-	if ($couleur = _request('couleur')) {
66
-		$couleurs = charger_fonction('couleurs', 'inc');
67
-		$les_couleurs = $couleurs([], true);
68
-		if (isset($les_couleurs[$couleur])) {
69
-			$GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
-		}
71
-	}
72
-	if ($display = intval(_request('display'))) {
73
-		$GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
-	}
75
-	if (
76
-		$display_navigation = _request('display_navigation')
77
-		and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
-	) {
79
-		$GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
-	}
65
+    if ($couleur = _request('couleur')) {
66
+        $couleurs = charger_fonction('couleurs', 'inc');
67
+        $les_couleurs = $couleurs([], true);
68
+        if (isset($les_couleurs[$couleur])) {
69
+            $GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
+        }
71
+    }
72
+    if ($display = intval(_request('display'))) {
73
+        $GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
+    }
75
+    if (
76
+        $display_navigation = _request('display_navigation')
77
+        and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
+    ) {
79
+        $GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
+    }
81 81
 
82
-	if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
-		include_spip('action/editer_auteur');
84
-		$c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
82
+    if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
+        include_spip('action/editer_auteur');
84
+        $c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
85 85
 
86
-		if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
-			$c['imessage'] = $imessage;
88
-		}
86
+        if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
+            $c['imessage'] = $imessage;
88
+        }
89 89
 
90
-		auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
-	}
90
+        auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
+    }
92 92
 
93
-	return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
93
+    return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
94 94
 }
Please login to merge, or discard this patch.
ecrire/inc/informer.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -11,77 +11,77 @@
 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
 function inc_informer_dist($id, $col, $exclus, $rac, $type, $do = 'aff') {
20
-	include_spip('inc/texte');
21
-	$titre = $descriptif = '';
22
-	if ($type === 'rubrique') {
23
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
-		if ($row) {
25
-			$titre = typo($row['titre']);
26
-			$descriptif = propre($row['descriptif']);
27
-		} else {
28
-			$titre = _T('info_racine_site');
29
-		}
30
-	}
20
+    include_spip('inc/texte');
21
+    $titre = $descriptif = '';
22
+    if ($type === 'rubrique') {
23
+        $row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
+        if ($row) {
25
+            $titre = typo($row['titre']);
26
+            $descriptif = propre($row['descriptif']);
27
+        } else {
28
+            $titre = _T('info_racine_site');
29
+        }
30
+    }
31 31
 
32
-	$res = '';
33
-	if (
34
-		$type === 'rubrique'
35
-		and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
-		and isset($GLOBALS['meta']['image_process'])
37
-	) {
38
-		if ($GLOBALS['meta']['image_process'] !== 'non') {
39
-			$chercher_logo = charger_fonction('chercher_logo', 'inc');
40
-			if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
-				[$fid, $dir, $nom, $format] = $res;
42
-				include_spip('inc/filtres_images_mini');
43
-				$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
-				if ($res) {
45
-					$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
-				}
47
-			}
48
-		}
49
-	}
32
+    $res = '';
33
+    if (
34
+        $type === 'rubrique'
35
+        and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
+        and isset($GLOBALS['meta']['image_process'])
37
+    ) {
38
+        if ($GLOBALS['meta']['image_process'] !== 'non') {
39
+            $chercher_logo = charger_fonction('chercher_logo', 'inc');
40
+            if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
+                [$fid, $dir, $nom, $format] = $res;
42
+                include_spip('inc/filtres_images_mini');
43
+                $res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
+                if ($res) {
45
+                    $res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
+                }
47
+            }
48
+        }
49
+    }
50 50
 
51
-	$rac = spip_htmlentities($rac, ENT_QUOTES);
52
-	$do = spip_htmlentities($do, ENT_QUOTES);
53
-	$id = intval($id);
51
+    $rac = spip_htmlentities($rac, ENT_QUOTES);
52
+    $do = spip_htmlentities($do, ENT_QUOTES);
53
+    $id = intval($id);
54 54
 
55 55
 # ce lien provoque la selection (directe) de la rubrique cliquee
56 56
 # et l'affichage de son titre dans le bandeau
57
-	$titre = strtr(
58
-		str_replace(
59
-			"'",
60
-			'&#8217;',
61
-			str_replace('"', '&#34;', textebrut($titre))
62
-		),
63
-		"\n\r",
64
-		'  '
65
-	);
57
+    $titre = strtr(
58
+        str_replace(
59
+            "'",
60
+            '&#8217;',
61
+            str_replace('"', '&#34;', textebrut($titre))
62
+        ),
63
+        "\n\r",
64
+        '  '
65
+    );
66 66
 
67
-	$js_func = $do . '_selection_titre';
67
+    $js_func = $do . '_selection_titre';
68 68
 
69
-	return "<div style='display: none;'>"
70
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
72
-	. entites_html($titre)
73
-	. '" />'
74
-	. '</div>'
75
-	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
-	. '<div class="informer__item">'
77
-	. (!$res ? '' : $res)
78
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
-	. (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
-	. '</div>'
81
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
-	. "<input type='submit' class='fondo btn submit' value='"
83
-	. _T('bouton_choisir')
84
-	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
-	. '</div>'
86
-	. '</div>';
69
+    return "<div style='display: none;'>"
70
+    . "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
+    . "<input type='text' id='" . $rac . "_sel2' value=\""
72
+    . entites_html($titre)
73
+    . '" />'
74
+    . '</div>'
75
+    . "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
+    . '<div class="informer__item">'
77
+    . (!$res ? '' : $res)
78
+    . "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
+    . (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
+    . '</div>'
81
+    . "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
+    . "<input type='submit' class='fondo btn submit' value='"
83
+    . _T('bouton_choisir')
84
+    . "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
+    . '</div>'
86
+    . '</div>';
87 87
 }
Please login to merge, or discard this patch.
ecrire/inc/commencer_page.php 1 patch
Indentation   +56 added lines, -56 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
 /**
@@ -43,25 +43,25 @@  discard block
 block discarded – undo
43 43
  * @return string Code HTML
44 44
  **/
45 45
 function inc_commencer_page_dist(
46
-	$titre = '',
47
-	$rubrique = 'accueil',
48
-	$sous_rubrique = 'accueil',
49
-	$id_rubrique = '',
50
-	$menu = true,
51
-	$minipres = false,
52
-	$alertes = true
46
+    $titre = '',
47
+    $rubrique = 'accueil',
48
+    $sous_rubrique = 'accueil',
49
+    $id_rubrique = '',
50
+    $menu = true,
51
+    $minipres = false,
52
+    $alertes = true
53 53
 ) {
54 54
 
55
-	include_spip('inc/headers');
55
+    include_spip('inc/headers');
56 56
 
57
-	http_no_cache();
57
+    http_no_cache();
58 58
 
59
-	return init_entete($titre, $id_rubrique, $minipres)
60
-	. init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
-	. "<div id='page'>"
62
-	. auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
-	. ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
-	. '<div class="largeur">';
59
+    return init_entete($titre, $id_rubrique, $minipres)
60
+    . init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
+    . "<div id='page'>"
62
+    . auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
+    . ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
+    . '<div class="largeur">';
65 65
 }
66 66
 
67 67
 /**
@@ -82,21 +82,21 @@  discard block
 block discarded – undo
82 82
  *     Entête du fichier HTML avec le DOCTYPE
83 83
  */
84 84
 function init_entete($titre = '', $dummy = 0, $minipres = false) {
85
-	include_spip('inc/texte');
86
-	if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
-		$nom_site_spip = _T('info_mon_site_spip');
88
-	}
89
-
90
-	$titre = '['
91
-		. $nom_site_spip
92
-		. ']'
93
-		. ($titre ? ' ' . textebrut(typo($titre)) : '');
94
-
95
-	return _DOCTYPE_ECRIRE
96
-	. html_lang_attributes()
97
-	. "<head>\n"
98
-	. init_head($titre, $dummy, $minipres)
99
-	. "</head>\n";
85
+    include_spip('inc/texte');
86
+    if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
+        $nom_site_spip = _T('info_mon_site_spip');
88
+    }
89
+
90
+    $titre = '['
91
+        . $nom_site_spip
92
+        . ']'
93
+        . ($titre ? ' ' . textebrut(typo($titre)) : '');
94
+
95
+    return _DOCTYPE_ECRIRE
96
+    . html_lang_attributes()
97
+    . "<head>\n"
98
+    . init_head($titre, $dummy, $minipres)
99
+    . "</head>\n";
100 100
 }
101 101
 
102 102
 /**
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
  * @return string
111 111
  */
112 112
 function init_head($titre = '', $dummy = 0, $minipres = false) {
113
-	return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
113
+    return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
114 114
 }
115 115
 
116 116
 /**
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
  */
133 133
 function init_body($rubrique = 'accueil', $sous_rubrique = 'accueil', $id_rubrique = '', $menu = true) {
134 134
 
135
-	$res = pipeline('body_prive', "<body class='"
136
-		. init_body_class() . ' ' . _request('exec') . "'"
137
-		. ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
-		. '>');
135
+    $res = pipeline('body_prive', "<body class='"
136
+        . init_body_class() . ' ' . _request('exec') . "'"
137
+        . ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
+        . '>');
139 139
 
140
-	if (!$menu) {
141
-		return $res;
142
-	}
140
+    if (!$menu) {
141
+        return $res;
142
+    }
143 143
 
144 144
 
145
-	$bandeau = charger_fonction('bandeau', 'inc');
145
+    $bandeau = charger_fonction('bandeau', 'inc');
146 146
 
147
-	return $res
148
-	. $bandeau();
147
+    return $res
148
+    . $bandeau();
149 149
 }
150 150
 
151 151
 /**
@@ -157,23 +157,23 @@  discard block
 block discarded – undo
157 157
  * @return string Classes CSS (séparées par des espaces)
158 158
  */
159 159
 function init_body_class() {
160
-	$display_modes = [
161
-		0 => 'icones_img_texte' // défaut.
162
-		/*init*/,
163
-		1 => 'icones_texte',
164
-		2 => 'icones_img_texte',
165
-		3 => 'icones_img'
166
-	];
160
+    $display_modes = [
161
+        0 => 'icones_img_texte' // défaut.
162
+        /*init*/,
163
+        1 => 'icones_texte',
164
+        2 => 'icones_img_texte',
165
+        3 => 'icones_img'
166
+    ];
167 167
 
168
-	$prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
168
+    $prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
169 169
 
170
-	$display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
-	$spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
170
+    $display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
+    $spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
172 172
 
173
-	$couleur = intval($prefs['couleur'] ?? 2);
173
+    $couleur = intval($prefs['couleur'] ?? 2);
174 174
 
175
-	$classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
-	return spip_sanitize_classname($classes);
175
+    $classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
+    return spip_sanitize_classname($classes);
177 177
 }
178 178
 
179 179
 
@@ -184,5 +184,5 @@  discard block
 block discarded – undo
184 184
  * @return string
185 185
  */
186 186
 function auteurs_recemment_connectes($id_auteur) {
187
-	return recuperer_fond('prive/objets/liste/auteurs_enligne');
187
+    return recuperer_fond('prive/objets/liste/auteurs_enligne');
188 188
 }
Please login to merge, or discard this patch.
ecrire/index.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 /** Drapeau indiquant que l'on est dans l'espace privé */
20 20
 define('_ESPACE_PRIVE', true);
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	include 'inc_version.php';
22
+    include 'inc_version.php';
23 23
 }
24 24
 
25 25
 include_spip('inc/cookie');
@@ -35,18 +35,18 @@  discard block
 block discarded – undo
35 35
 // alors il faut blinder les variables d'URL
36 36
 //
37 37
 if (autoriser_sans_cookie($exec, false)) {
38
-	if (!isset($reinstall)) {
39
-		$reinstall = 'non';
40
-	}
41
-	$var_auth = true;
38
+    if (!isset($reinstall)) {
39
+        $reinstall = 'non';
40
+    }
41
+    $var_auth = true;
42 42
 } else {
43
-	// Authentification, redefinissable
44
-	$auth = charger_fonction('auth', 'inc');
45
-	$var_auth = $auth();
46
-	if ($var_auth) {
47
-		echo auth_echec($var_auth);
48
-		exit;
49
-	}
43
+    // Authentification, redefinissable
44
+    $auth = charger_fonction('auth', 'inc');
45
+    $var_auth = $auth();
46
+    if ($var_auth) {
47
+        echo auth_echec($var_auth);
48
+        exit;
49
+    }
50 50
 }
51 51
 
52 52
 // initialiser a la langue par defaut
@@ -57,29 +57,29 @@  discard block
 block discarded – undo
57 57
 
58 58
 
59 59
 if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
60
-	if (!autoriser_sans_cookie($exec)) {
61
-		// Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
-		include_spip('public/aiguiller');
63
-		if (
64
-			// cas des appels actions ?action=xxx
65
-			traiter_appels_actions()
66
-			or
67
-			// cas des hits ajax sur les inclusions ajax
68
-			traiter_appels_inclusions_ajax()
69
-			or
70
-			// cas des formulaires charger/verifier/traiter
71
-			traiter_formulaires_dynamiques()
72
-		) {
73
-			exit;
74
-		} // le hit est fini !
75
-	}
60
+    if (!autoriser_sans_cookie($exec)) {
61
+        // Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
+        include_spip('public/aiguiller');
63
+        if (
64
+            // cas des appels actions ?action=xxx
65
+            traiter_appels_actions()
66
+            or
67
+            // cas des hits ajax sur les inclusions ajax
68
+            traiter_appels_inclusions_ajax()
69
+            or
70
+            // cas des formulaires charger/verifier/traiter
71
+            traiter_formulaires_dynamiques()
72
+        ) {
73
+            exit;
74
+        } // le hit est fini !
75
+    }
76 76
 }
77 77
 // securiser les redirect du back-office
78 78
 if (_request('redirect')) {
79
-	if (!function_exists('securiser_redirect_action')) {
80
-		include_spip('public/aiguiller');
81
-	}
82
-	set_request('redirect', securiser_redirect_action(_request('redirect')));
79
+    if (!function_exists('securiser_redirect_action')) {
80
+        include_spip('public/aiguiller');
81
+    }
82
+    set_request('redirect', securiser_redirect_action(_request('redirect')));
83 83
 }
84 84
 
85 85
 
@@ -89,12 +89,12 @@  discard block
 block discarded – undo
89 89
 
90 90
 // Controle de la version, sauf si on est deja en train de s'en occuper
91 91
 if (
92
-	!$reinstall == 'oui'
93
-	and !_AJAX
94
-	and isset($GLOBALS['meta']['version_installee'])
95
-	and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
92
+    !$reinstall == 'oui'
93
+    and !_AJAX
94
+    and isset($GLOBALS['meta']['version_installee'])
95
+    and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
96 96
 ) {
97
-	$exec = 'demande_mise_a_jour';
97
+    $exec = 'demande_mise_a_jour';
98 98
 }
99 99
 
100 100
 // Quand une action d'administration est en cours (meta "admin"),
@@ -104,39 +104,39 @@  discard block
 block discarded – undo
104 104
 // sinon c'est qu'elle a ete interrompue et il faut la reprendre
105 105
 
106 106
 elseif (isset($GLOBALS['meta']['admin'])) {
107
-	if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
-		[, $var_f, $n] = $l;
109
-	}
110
-	if (
111
-		_AJAX
112
-		or !(
113
-			isset($_COOKIE['spip_admin'])
114
-			or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
-		)
116
-	) {
117
-		spip_log('Quand la meta admin vaut ' .
118
-			$GLOBALS['meta']['admin'] .
119
-			' seul un admin peut se connecter et sans AJAX.' .
120
-			' En cas de probleme, detruire cette meta.');
121
-		die(_T('info_travaux_texte'));
122
-	}
123
-	if ($n) {
124
-		[, $var_f, $n] = $l;
125
-		if (tester_url_ecrire("base_$var_f")) {
126
-			$var_f = "base_$var_f";
127
-		}
128
-		if ($var_f != $exec) {
129
-			spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
-			$exec = $var_f;
131
-			set_request('exec', $exec);
132
-		}
133
-	}
107
+    if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
+        [, $var_f, $n] = $l;
109
+    }
110
+    if (
111
+        _AJAX
112
+        or !(
113
+            isset($_COOKIE['spip_admin'])
114
+            or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
+        )
116
+    ) {
117
+        spip_log('Quand la meta admin vaut ' .
118
+            $GLOBALS['meta']['admin'] .
119
+            ' seul un admin peut se connecter et sans AJAX.' .
120
+            ' En cas de probleme, detruire cette meta.');
121
+        die(_T('info_travaux_texte'));
122
+    }
123
+    if ($n) {
124
+        [, $var_f, $n] = $l;
125
+        if (tester_url_ecrire("base_$var_f")) {
126
+            $var_f = "base_$var_f";
127
+        }
128
+        if ($var_f != $exec) {
129
+            spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
+            $exec = $var_f;
131
+            set_request('exec', $exec);
132
+        }
133
+    }
134 134
 }
135 135
 // si nom pas plausible, prendre le script par defaut
136 136
 // attention aux deux cas 404/403 qui commencent par un 4 !
137 137
 elseif (!preg_match(',^[a-z4_][0-9a-z_-]*$,i', $exec)) {
138
-	$exec = 'accueil';
139
-	set_request('exec', $exec);
138
+    $exec = 'accueil';
139
+    set_request('exec', $exec);
140 140
 }
141 141
 
142 142
 //  si la langue est specifiee par cookie et ne correspond pas
@@ -144,19 +144,19 @@  discard block
 block discarded – undo
144 144
 // on appelle directement la fonction, car un appel d'action peut conduire a une boucle infinie
145 145
 // si le cookie n'est pas pose correctement dans l'action
146 146
 if (
147
-	!$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
-	and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
147
+    !$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
+    and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
149 149
 ) {
150
-	include_spip('action/converser');
151
-	action_converser_post($GLOBALS['visiteur_session']['lang'], true);
150
+    include_spip('action/converser');
151
+    action_converser_post($GLOBALS['visiteur_session']['lang'], true);
152 152
 }
153 153
 
154 154
 if ($var_f = tester_url_ecrire($exec)) {
155
-	$var_f = charger_fonction($var_f);
156
-	$var_f(); // at last
155
+    $var_f = charger_fonction($var_f);
156
+    $var_f(); // at last
157 157
 } else {
158
-	// Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
-	// ce qui permet de laisser la main a un plugin
160
-	$var_f = charger_fonction('404');
161
-	$var_f($exec);
158
+    // Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
+    // ce qui permet de laisser la main a un plugin
160
+    $var_f = charger_fonction('404');
161
+    $var_f($exec);
162 162
 }
Please login to merge, or discard this patch.
ecrire/inc/flock.php 1 patch
Indentation   +407 added lines, -407 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  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('_TEST_FILE_EXISTS')) {
24
-	/** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
-	define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
24
+    /** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
+    define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
26 26
 }
27 27
 
28 28
 #define('_SPIP_LOCK_MODE',0); // ne pas utiliser de lock (deconseille)
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 #define('_SPIP_LOCK_MODE',2); // utiliser le nfslock de spip
31 31
 
32 32
 if (_SPIP_LOCK_MODE == 2) {
33
-	include_spip('inc/nfslock');
33
+    include_spip('inc/nfslock');
34 34
 }
35 35
 
36 36
 $GLOBALS['liste_verrous'] = [];
@@ -53,24 +53,24 @@  discard block
 block discarded – undo
53 53
  *     Ressource sur le fichier ouvert, sinon false.
54 54
  **/
55 55
 function spip_fopen_lock($fichier, $mode, $verrou) {
56
-	if (_SPIP_LOCK_MODE == 1) {
57
-		if ($fl = @fopen($fichier, $mode)) {
58
-			// verrou
59
-			@flock($fl, $verrou);
60
-		}
61
-
62
-		return $fl;
63
-	} elseif (_SPIP_LOCK_MODE == 2) {
64
-		if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
-			$GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
-
67
-			return $fl;
68
-		} else {
69
-			return false;
70
-		}
71
-	}
72
-
73
-	return @fopen($fichier, $mode);
56
+    if (_SPIP_LOCK_MODE == 1) {
57
+        if ($fl = @fopen($fichier, $mode)) {
58
+            // verrou
59
+            @flock($fl, $verrou);
60
+        }
61
+
62
+        return $fl;
63
+    } elseif (_SPIP_LOCK_MODE == 2) {
64
+        if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
+            $GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
+
67
+            return $fl;
68
+        } else {
69
+            return false;
70
+        }
71
+    }
72
+
73
+    return @fopen($fichier, $mode);
74 74
 }
75 75
 
76 76
 /**
@@ -85,14 +85,14 @@  discard block
 block discarded – undo
85 85
  *     true si succès, false sinon.
86 86
  **/
87 87
 function spip_fclose_unlock($handle) {
88
-	if (_SPIP_LOCK_MODE == 1) {
89
-		@flock($handle, LOCK_UN);
90
-	} elseif (_SPIP_LOCK_MODE == 2) {
91
-		spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
-		unset($GLOBALS['liste_verrous'][$handle]);
93
-	}
94
-
95
-	return @fclose($handle);
88
+    if (_SPIP_LOCK_MODE == 1) {
89
+        @flock($handle, LOCK_UN);
90
+    } elseif (_SPIP_LOCK_MODE == 2) {
91
+        spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
+        unset($GLOBALS['liste_verrous'][$handle]);
93
+    }
94
+
95
+    return @fclose($handle);
96 96
 }
97 97
 
98 98
 
@@ -106,23 +106,23 @@  discard block
 block discarded – undo
106 106
  *     Contenu du fichier
107 107
  **/
108 108
 function spip_file_get_contents($fichier) {
109
-	if (substr($fichier, -3) != '.gz') {
110
-		if (function_exists('file_get_contents')) {
111
-			// quand on est sous windows on ne sait pas si file_get_contents marche
112
-			// on essaye : si ca retourne du contenu alors c'est bon
113
-			// sinon on fait un file() pour avoir le coeur net
114
-			$contenu = @file_get_contents($fichier);
115
-			if (!$contenu and _OS_SERVEUR == 'windows') {
116
-				$contenu = @file($fichier);
117
-			}
118
-		} else {
119
-			$contenu = @file($fichier);
120
-		}
121
-	} else {
122
-		$contenu = @gzfile($fichier);
123
-	}
124
-
125
-	return is_array($contenu) ? join('', $contenu) : (string)$contenu;
109
+    if (substr($fichier, -3) != '.gz') {
110
+        if (function_exists('file_get_contents')) {
111
+            // quand on est sous windows on ne sait pas si file_get_contents marche
112
+            // on essaye : si ca retourne du contenu alors c'est bon
113
+            // sinon on fait un file() pour avoir le coeur net
114
+            $contenu = @file_get_contents($fichier);
115
+            if (!$contenu and _OS_SERVEUR == 'windows') {
116
+                $contenu = @file($fichier);
117
+            }
118
+        } else {
119
+            $contenu = @file($fichier);
120
+        }
121
+    } else {
122
+        $contenu = @gzfile($fichier);
123
+    }
124
+
125
+    return is_array($contenu) ? join('', $contenu) : (string)$contenu;
126 126
 }
127 127
 
128 128
 
@@ -147,48 +147,48 @@  discard block
 block discarded – undo
147 147
  *     true si l'opération a réussie, false sinon.
148 148
  **/
149 149
 function lire_fichier($fichier, &$contenu, $options = []) {
150
-	$contenu = '';
151
-	// inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
-	// economisons donc les acces disque, sauf chez free qui rale pour un rien
153
-	if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
-		return false;
155
-	}
156
-
157
-	#spip_timer('lire_fichier');
158
-
159
-	// pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
-	if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
-		// lire le fichier avant tout
162
-		$contenu = spip_file_get_contents($fichier);
163
-
164
-		// le fichier a-t-il ete supprime par le locker ?
165
-		// on ne verifie que si la tentative de lecture a echoue
166
-		// pour discriminer un contenu vide d'un fichier absent
167
-		// et eviter un acces disque
168
-		if (!$contenu and !@file_exists($fichier)) {
169
-			spip_fclose_unlock($fl);
170
-
171
-			return false;
172
-		}
173
-
174
-		// liberer le verrou
175
-		spip_fclose_unlock($fl);
176
-
177
-		// Verifications
178
-		$ok = true;
179
-		if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
-			$ok &= (preg_match(",[?]>\n?$,", $contenu));
181
-		}
182
-
183
-		#spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
-		if (!$ok) {
185
-			spip_log("echec lecture $fichier");
186
-		}
187
-
188
-		return $ok;
189
-	}
190
-
191
-	return false;
150
+    $contenu = '';
151
+    // inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
+    // economisons donc les acces disque, sauf chez free qui rale pour un rien
153
+    if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
+        return false;
155
+    }
156
+
157
+    #spip_timer('lire_fichier');
158
+
159
+    // pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
+    if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
+        // lire le fichier avant tout
162
+        $contenu = spip_file_get_contents($fichier);
163
+
164
+        // le fichier a-t-il ete supprime par le locker ?
165
+        // on ne verifie que si la tentative de lecture a echoue
166
+        // pour discriminer un contenu vide d'un fichier absent
167
+        // et eviter un acces disque
168
+        if (!$contenu and !@file_exists($fichier)) {
169
+            spip_fclose_unlock($fl);
170
+
171
+            return false;
172
+        }
173
+
174
+        // liberer le verrou
175
+        spip_fclose_unlock($fl);
176
+
177
+        // Verifications
178
+        $ok = true;
179
+        if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
+            $ok &= (preg_match(",[?]>\n?$,", $contenu));
181
+        }
182
+
183
+        #spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
+        if (!$ok) {
185
+            spip_log("echec lecture $fichier");
186
+        }
187
+
188
+        return $ok;
189
+    }
190
+
191
+    return false;
192 192
 }
193 193
 
194 194
 
@@ -216,85 +216,85 @@  discard block
 block discarded – undo
216 216
  **/
217 217
 function ecrire_fichier($fichier, $contenu, $ignorer_echec = false, $truncate = true) {
218 218
 
219
-	#spip_timer('ecrire_fichier');
220
-
221
-	// verrouiller le fichier destination
222
-	if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
-		// ecrire les donnees, compressees le cas echeant
224
-		// (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
-		// de le recreer si le locker qui nous precede l'avait supprime...)
226
-		if (substr($fichier, -3) == '.gz') {
227
-			$contenu = gzencode($contenu);
228
-		}
229
-		// si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
-		// pour etre sur d'avoir une operation atomique
231
-		// y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
-		// sauf sous wintruc ou ca ne marche pas
233
-		$ok = false;
234
-		if ($truncate and _OS_SERVEUR != 'windows') {
235
-			if (!function_exists('creer_uniqid')) {
236
-				include_spip('inc/acces');
237
-			}
238
-			$id = creer_uniqid();
239
-			// on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
-			if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
-				$s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
-				$ok = ($s == $a);
243
-				spip_fclose_unlock($fp2);
244
-				spip_fclose_unlock($fp);
245
-				// unlink direct et pas spip_unlink car on avait deja le verrou
246
-				// a priori pas besoin car rename ecrase la cible
247
-				// @unlink($fichier);
248
-				// le rename aussitot, atomique quand on est pas sous windows
249
-				// au pire on arrive en second en cas de concourance, et le rename echoue
250
-				// --> on a la version de l'autre process qui doit etre identique
251
-				@rename("$fichier.$id", $fichier);
252
-				// precaution en cas d'echec du rename
253
-				if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
-					@unlink("$fichier.$id");
255
-				}
256
-				if ($ok) {
257
-					$ok = file_exists($fichier);
258
-				}
259
-			} else // echec mais penser a fermer ..
260
-			{
261
-				spip_fclose_unlock($fp);
262
-			}
263
-		}
264
-		// sinon ou si methode precedente a echoueee
265
-		// on se rabat sur la methode ancienne
266
-		if (!$ok) {
267
-			// ici on est en ajout ou sous windows, cas desespere
268
-			if ($truncate) {
269
-				@ftruncate($fp, 0);
270
-			}
271
-			$s = @fputs($fp, $contenu, $a = strlen($contenu));
272
-
273
-			$ok = ($s == $a);
274
-			spip_fclose_unlock($fp);
275
-		}
276
-
277
-		// liberer le verrou et fermer le fichier
278
-		@chmod($fichier, _SPIP_CHMOD & 0666);
279
-		if ($ok) {
280
-			if (strpos($fichier, '.php') !== false) {
281
-				spip_clear_opcode_cache(realpath($fichier));
282
-			}
283
-
284
-			return $ok;
285
-		}
286
-	}
287
-
288
-	if (!$ignorer_echec) {
289
-		include_spip('inc/autoriser');
290
-		if (autoriser('chargerftp')) {
291
-			raler_fichier($fichier);
292
-		}
293
-		spip_unlink($fichier);
294
-	}
295
-	spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
-
297
-	return false;
219
+    #spip_timer('ecrire_fichier');
220
+
221
+    // verrouiller le fichier destination
222
+    if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
+        // ecrire les donnees, compressees le cas echeant
224
+        // (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
+        // de le recreer si le locker qui nous precede l'avait supprime...)
226
+        if (substr($fichier, -3) == '.gz') {
227
+            $contenu = gzencode($contenu);
228
+        }
229
+        // si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
+        // pour etre sur d'avoir une operation atomique
231
+        // y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
+        // sauf sous wintruc ou ca ne marche pas
233
+        $ok = false;
234
+        if ($truncate and _OS_SERVEUR != 'windows') {
235
+            if (!function_exists('creer_uniqid')) {
236
+                include_spip('inc/acces');
237
+            }
238
+            $id = creer_uniqid();
239
+            // on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
+            if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
+                $s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
+                $ok = ($s == $a);
243
+                spip_fclose_unlock($fp2);
244
+                spip_fclose_unlock($fp);
245
+                // unlink direct et pas spip_unlink car on avait deja le verrou
246
+                // a priori pas besoin car rename ecrase la cible
247
+                // @unlink($fichier);
248
+                // le rename aussitot, atomique quand on est pas sous windows
249
+                // au pire on arrive en second en cas de concourance, et le rename echoue
250
+                // --> on a la version de l'autre process qui doit etre identique
251
+                @rename("$fichier.$id", $fichier);
252
+                // precaution en cas d'echec du rename
253
+                if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
+                    @unlink("$fichier.$id");
255
+                }
256
+                if ($ok) {
257
+                    $ok = file_exists($fichier);
258
+                }
259
+            } else // echec mais penser a fermer ..
260
+            {
261
+                spip_fclose_unlock($fp);
262
+            }
263
+        }
264
+        // sinon ou si methode precedente a echoueee
265
+        // on se rabat sur la methode ancienne
266
+        if (!$ok) {
267
+            // ici on est en ajout ou sous windows, cas desespere
268
+            if ($truncate) {
269
+                @ftruncate($fp, 0);
270
+            }
271
+            $s = @fputs($fp, $contenu, $a = strlen($contenu));
272
+
273
+            $ok = ($s == $a);
274
+            spip_fclose_unlock($fp);
275
+        }
276
+
277
+        // liberer le verrou et fermer le fichier
278
+        @chmod($fichier, _SPIP_CHMOD & 0666);
279
+        if ($ok) {
280
+            if (strpos($fichier, '.php') !== false) {
281
+                spip_clear_opcode_cache(realpath($fichier));
282
+            }
283
+
284
+            return $ok;
285
+        }
286
+    }
287
+
288
+    if (!$ignorer_echec) {
289
+        include_spip('inc/autoriser');
290
+        if (autoriser('chargerftp')) {
291
+            raler_fichier($fichier);
292
+        }
293
+        spip_unlink($fichier);
294
+    }
295
+    spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
+
297
+    return false;
298 298
 }
299 299
 
300 300
 /**
@@ -314,12 +314,12 @@  discard block
 block discarded – undo
314 314
  *     Écriture avec troncation ?
315 315
  */
316 316
 function ecrire_fichier_securise($fichier, $contenu, $ecrire_quand_meme = false, $truncate = true) {
317
-	if (substr($fichier, -4) !== '.php') {
318
-		spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
-	}
320
-	$contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
317
+    if (substr($fichier, -4) !== '.php') {
318
+        spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
+    }
320
+    $contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
321 321
 
322
-	return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
322
+    return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
323 323
 }
324 324
 
325 325
 
@@ -330,25 +330,25 @@  discard block
 block discarded – undo
330 330
  * @return bool
331 331
  */
332 332
 function ecrire_fichier_calcule_si_modifie($fichier, $contenu, $force = false, $use_copy = false) {
333
-	$fichier_tmp = $fichier . '.last';
334
-	if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
-		return false;
336
-	}
337
-	if (
338
-		$force
339
-		or !file_exists($fichier)
340
-		or md5_file($fichier) != md5_file($fichier_tmp)
341
-	) {
342
-		if ($use_copy) {
343
-			@copy($fichier_tmp, $fichier);
344
-		}
345
-		else {
346
-			@rename($fichier_tmp, $fichier);
347
-		}
348
-		// eviter que PHP ne reserve le vieux timestamp
349
-		clearstatcache(true, $fichier);
350
-	}
351
-	return true;
333
+    $fichier_tmp = $fichier . '.last';
334
+    if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
+        return false;
336
+    }
337
+    if (
338
+        $force
339
+        or !file_exists($fichier)
340
+        or md5_file($fichier) != md5_file($fichier_tmp)
341
+    ) {
342
+        if ($use_copy) {
343
+            @copy($fichier_tmp, $fichier);
344
+        }
345
+        else {
346
+            @rename($fichier_tmp, $fichier);
347
+        }
348
+        // eviter que PHP ne reserve le vieux timestamp
349
+        clearstatcache(true, $fichier);
350
+    }
351
+    return true;
352 352
 }
353 353
 
354 354
 
@@ -369,11 +369,11 @@  discard block
 block discarded – undo
369 369
  *     true si l'opération a réussie, false sinon.
370 370
  */
371 371
 function lire_fichier_securise($fichier, &$contenu, $options = []) {
372
-	if ($res = lire_fichier($fichier, $contenu, $options)) {
373
-		$contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
-	}
372
+    if ($res = lire_fichier($fichier, $contenu, $options)) {
373
+        $contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
+    }
375 375
 
376
-	return $res;
376
+    return $res;
377 377
 }
378 378
 
379 379
 /**
@@ -388,25 +388,25 @@  discard block
 block discarded – undo
388 388
  *     Chemin du fichier
389 389
  **/
390 390
 function raler_fichier($fichier) {
391
-	if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
-		spip_initialisation_suite();
393
-	}
394
-	include_spip('inc/minipres');
395
-	$dir = dirname($fichier);
396
-	http_response_code(401);
397
-	echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
-		. _T('texte_inc_meta_1', ['fichier' => $fichier])
399
-		. " <a href='"
400
-		. generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
-		. "'>"
402
-		. _T('texte_inc_meta_2')
403
-		. '</a> '
404
-		. _T(
405
-			'texte_inc_meta_3',
406
-			['repertoire' => joli_repertoire($dir)]
407
-		)
408
-		. "</h4>\n");
409
-	exit;
391
+    if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
+        spip_initialisation_suite();
393
+    }
394
+    include_spip('inc/minipres');
395
+    $dir = dirname($fichier);
396
+    http_response_code(401);
397
+    echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
+        . _T('texte_inc_meta_1', ['fichier' => $fichier])
399
+        . " <a href='"
400
+        . generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
+        . "'>"
402
+        . _T('texte_inc_meta_2')
403
+        . '</a> '
404
+        . _T(
405
+            'texte_inc_meta_3',
406
+            ['repertoire' => joli_repertoire($dir)]
407
+        )
408
+        . "</h4>\n");
409
+    exit;
410 410
 }
411 411
 
412 412
 
@@ -421,14 +421,14 @@  discard block
 block discarded – undo
421 421
  *     - true si récent, false sinon
422 422
  */
423 423
 function jeune_fichier($fichier, $n) {
424
-	if (!file_exists($fichier)) {
425
-		return false;
426
-	}
427
-	if (!$c = @filemtime($fichier)) {
428
-		return false;
429
-	}
430
-
431
-	return (time() - $n <= $c);
424
+    if (!file_exists($fichier)) {
425
+        return false;
426
+    }
427
+    if (!$c = @filemtime($fichier)) {
428
+        return false;
429
+    }
430
+
431
+    return (time() - $n <= $c);
432 432
 }
433 433
 
434 434
 /**
@@ -443,22 +443,22 @@  discard block
 block discarded – undo
443 443
  *     - false si on n'arrive pas poser le verrou ou si la suppression échoue
444 444
  */
445 445
 function supprimer_fichier($fichier, $lock = true) {
446
-	if (!@file_exists($fichier)) {
447
-		return true;
448
-	}
449
-
450
-	if ($lock) {
451
-		// verrouiller le fichier destination
452
-		if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
-			return false;
454
-		}
455
-
456
-		// liberer le verrou
457
-		spip_fclose_unlock($fp);
458
-	}
459
-
460
-	// supprimer
461
-	return @unlink($fichier);
446
+    if (!@file_exists($fichier)) {
447
+        return true;
448
+    }
449
+
450
+    if ($lock) {
451
+        // verrouiller le fichier destination
452
+        if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
+            return false;
454
+        }
455
+
456
+        // liberer le verrou
457
+        spip_fclose_unlock($fp);
458
+    }
459
+
460
+    // supprimer
461
+    return @unlink($fichier);
462 462
 }
463 463
 
464 464
 /**
@@ -468,12 +468,12 @@  discard block
 block discarded – undo
468 468
  *     Chemin du fichier
469 469
  */
470 470
 function spip_unlink($f) {
471
-	if (!is_dir($f)) {
472
-		supprimer_fichier($f, false);
473
-	} else {
474
-		@unlink("$f/.ok");
475
-		@rmdir($f);
476
-	}
471
+    if (!is_dir($f)) {
472
+        supprimer_fichier($f, false);
473
+    } else {
474
+        @unlink("$f/.ok");
475
+        @rmdir($f);
476
+    }
477 477
 }
478 478
 
479 479
 /**
@@ -487,26 +487,26 @@  discard block
 block discarded – undo
487 487
  *   The absolute path of the PHP file to invalidate.
488 488
  */
489 489
 function spip_clear_opcode_cache($filepath) {
490
-	clearstatcache(true, $filepath);
491
-
492
-	// Zend OPcache
493
-	if (function_exists('opcache_invalidate')) {
494
-		$invalidate = @opcache_invalidate($filepath, true);
495
-		// si l'invalidation a echoue lever un flag
496
-		if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
-			define('_spip_attend_invalidation_opcode_cache', true);
498
-		}
499
-	} elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
-		// n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
-		define('_spip_attend_invalidation_opcode_cache', true);
502
-	}
503
-	// APC.
504
-	if (function_exists('apc_delete_file')) {
505
-		// apc_delete_file() throws a PHP warning in case the specified file was
506
-		// not compiled yet.
507
-		// @see http://php.net/apc-delete-file
508
-		@apc_delete_file($filepath);
509
-	}
490
+    clearstatcache(true, $filepath);
491
+
492
+    // Zend OPcache
493
+    if (function_exists('opcache_invalidate')) {
494
+        $invalidate = @opcache_invalidate($filepath, true);
495
+        // si l'invalidation a echoue lever un flag
496
+        if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
+            define('_spip_attend_invalidation_opcode_cache', true);
498
+        }
499
+    } elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
+        // n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
+        define('_spip_attend_invalidation_opcode_cache', true);
502
+    }
503
+    // APC.
504
+    if (function_exists('apc_delete_file')) {
505
+        // apc_delete_file() throws a PHP warning in case the specified file was
506
+        // not compiled yet.
507
+        // @see http://php.net/apc-delete-file
508
+        @apc_delete_file($filepath);
509
+    }
510 510
 }
511 511
 
512 512
 /**
@@ -529,25 +529,25 @@  discard block
 block discarded – undo
529 529
  *
530 530
  */
531 531
 function spip_attend_invalidation_opcode_cache($timestamp = null) {
532
-	if (
533
-		function_exists('opcache_get_configuration')
534
-		and @ini_get('opcache.enable')
535
-		and @ini_get('opcache.validate_timestamps')
536
-		and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
-		and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
-	) {
539
-		$wait = $duree + 1;
540
-		if ($timestamp) {
541
-			$wait -= (time() - $timestamp);
542
-			if ($wait < 0) {
543
-				$wait = 0;
544
-			}
545
-		}
546
-		spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
-		if ($wait) {
548
-			sleep($duree + 1);
549
-		}
550
-	}
532
+    if (
533
+        function_exists('opcache_get_configuration')
534
+        and @ini_get('opcache.enable')
535
+        and @ini_get('opcache.validate_timestamps')
536
+        and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
+        and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
+    ) {
539
+        $wait = $duree + 1;
540
+        if ($timestamp) {
541
+            $wait -= (time() - $timestamp);
542
+            if ($wait < 0) {
543
+                $wait = 0;
544
+            }
545
+        }
546
+        spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
+        if ($wait) {
548
+            sleep($duree + 1);
549
+        }
550
+    }
551 551
 }
552 552
 
553 553
 
@@ -560,26 +560,26 @@  discard block
 block discarded – undo
560 560
  * @return bool Suppression reussie.
561 561
  */
562 562
 function supprimer_repertoire($dir) {
563
-	if (!file_exists($dir)) {
564
-		return true;
565
-	}
566
-	if (!is_dir($dir) || is_link($dir)) {
567
-		return @unlink($dir);
568
-	}
569
-
570
-	foreach (scandir($dir) as $item) {
571
-		if ($item == '.' || $item == '..') {
572
-			continue;
573
-		}
574
-		if (!supprimer_repertoire($dir . '/' . $item)) {
575
-			@chmod($dir . '/' . $item, 0777);
576
-			if (!supprimer_repertoire($dir . '/' . $item)) {
577
-				return false;
578
-			}
579
-		};
580
-	}
581
-
582
-	return @rmdir($dir);
563
+    if (!file_exists($dir)) {
564
+        return true;
565
+    }
566
+    if (!is_dir($dir) || is_link($dir)) {
567
+        return @unlink($dir);
568
+    }
569
+
570
+    foreach (scandir($dir) as $item) {
571
+        if ($item == '.' || $item == '..') {
572
+            continue;
573
+        }
574
+        if (!supprimer_repertoire($dir . '/' . $item)) {
575
+            @chmod($dir . '/' . $item, 0777);
576
+            if (!supprimer_repertoire($dir . '/' . $item)) {
577
+                return false;
578
+            }
579
+        };
580
+    }
581
+
582
+    return @rmdir($dir);
583 583
 }
584 584
 
585 585
 
@@ -608,57 +608,57 @@  discard block
 block discarded – undo
608 608
  *     Chemin du répertoire créé.
609 609
  **/
610 610
 function sous_repertoire($base, $subdir = '', $nobase = false, $tantpis = false) {
611
-	static $dirs = [];
612
-
613
-	$base = str_replace('//', '/', $base);
614
-
615
-	# suppr le dernier caractere si c'est un /
616
-	$base = rtrim($base, '/');
617
-
618
-	if (!strlen($subdir)) {
619
-		$n = strrpos($base, '/');
620
-		if ($n === false) {
621
-			return $nobase ? '' : ($base . '/');
622
-		}
623
-		$subdir = substr($base, $n + 1);
624
-		$base = substr($base, 0, $n + 1);
625
-	} else {
626
-		$base .= '/';
627
-		$subdir = str_replace('/', '', $subdir);
628
-	}
629
-
630
-	$baseaff = $nobase ? '' : $base;
631
-	if (isset($dirs[$base . $subdir])) {
632
-		return $baseaff . $dirs[$base . $subdir];
633
-	}
634
-
635
-	$path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
-
637
-	if (file_exists("$path/.ok")) {
638
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
-	}
640
-
641
-	@mkdir($path, _SPIP_CHMOD);
642
-	@chmod($path, _SPIP_CHMOD);
643
-
644
-	if (is_dir($path) && is_writable($path)) {
645
-		@touch("$path/.ok");
646
-		spip_log("creation $base$subdir/");
647
-
648
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
-	}
650
-
651
-	// en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
-	// l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
-	spip_log("echec creation $base{$subdir}");
654
-	if ($tantpis) {
655
-		return '';
656
-	}
657
-	if (!_DIR_RESTREINT) {
658
-		$base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
-	}
660
-	$base .= $subdir;
661
-	raler_fichier($base . '/.ok');
611
+    static $dirs = [];
612
+
613
+    $base = str_replace('//', '/', $base);
614
+
615
+    # suppr le dernier caractere si c'est un /
616
+    $base = rtrim($base, '/');
617
+
618
+    if (!strlen($subdir)) {
619
+        $n = strrpos($base, '/');
620
+        if ($n === false) {
621
+            return $nobase ? '' : ($base . '/');
622
+        }
623
+        $subdir = substr($base, $n + 1);
624
+        $base = substr($base, 0, $n + 1);
625
+    } else {
626
+        $base .= '/';
627
+        $subdir = str_replace('/', '', $subdir);
628
+    }
629
+
630
+    $baseaff = $nobase ? '' : $base;
631
+    if (isset($dirs[$base . $subdir])) {
632
+        return $baseaff . $dirs[$base . $subdir];
633
+    }
634
+
635
+    $path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
+
637
+    if (file_exists("$path/.ok")) {
638
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
+    }
640
+
641
+    @mkdir($path, _SPIP_CHMOD);
642
+    @chmod($path, _SPIP_CHMOD);
643
+
644
+    if (is_dir($path) && is_writable($path)) {
645
+        @touch("$path/.ok");
646
+        spip_log("creation $base$subdir/");
647
+
648
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
+    }
650
+
651
+    // en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
+    // l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
+    spip_log("echec creation $base{$subdir}");
654
+    if ($tantpis) {
655
+        return '';
656
+    }
657
+    if (!_DIR_RESTREINT) {
658
+        $base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
+    }
660
+    $base .= $subdir;
661
+    raler_fichier($base . '/.ok');
662 662
 }
663 663
 
664 664
 
@@ -691,56 +691,56 @@  discard block
 block discarded – undo
691 691
  *     Chemins des fichiers trouvés.
692 692
  **/
693 693
 function preg_files($dir, $pattern = -1 /* AUTO */, $maxfiles = 10000, $recurs = []) {
694
-	$nbfiles = 0;
695
-	if ($pattern == -1) {
696
-		$pattern = '';
697
-	}
698
-	$fichiers = [];
699
-	// revenir au repertoire racine si on a recu dossier/truc
700
-	// pour regarder dossier/truc/ ne pas oublier le / final
701
-	$dir = preg_replace(',/[^/]*$,', '', $dir);
702
-	if ($dir == '') {
703
-		$dir = '.';
704
-	}
705
-
706
-	if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
-		while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
-			if (
709
-				$f[0] != '.' # ignorer . .. .svn etc
710
-				and $f != 'CVS'
711
-				and $f != 'remove.txt'
712
-				and is_readable($f = "$dir/$f")
713
-			) {
714
-				if (is_file($f)) {
715
-					if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
-						$fichiers[] = $f;
717
-						$nbfiles++;
718
-					}
719
-				} else {
720
-					if (is_dir($f) and is_array($recurs)) {
721
-						$rp = @realpath($f);
722
-						if (!is_string($rp) or !strlen($rp)) {
723
-							$rp = $f;
724
-						} # realpath n'est peut etre pas autorise
725
-						if (!isset($recurs[$rp])) {
726
-							$recurs[$rp] = true;
727
-							$beginning = $fichiers;
728
-							$end = preg_files(
729
-								"$f/",
730
-								$pattern,
731
-								$maxfiles - $nbfiles,
732
-								$recurs
733
-							);
734
-							$fichiers = array_merge((array)$beginning, (array)$end);
735
-							$nbfiles = count($fichiers);
736
-						}
737
-					}
738
-				}
739
-			}
740
-		}
741
-		closedir($d);
742
-	}
743
-	sort($fichiers);
744
-
745
-	return $fichiers;
694
+    $nbfiles = 0;
695
+    if ($pattern == -1) {
696
+        $pattern = '';
697
+    }
698
+    $fichiers = [];
699
+    // revenir au repertoire racine si on a recu dossier/truc
700
+    // pour regarder dossier/truc/ ne pas oublier le / final
701
+    $dir = preg_replace(',/[^/]*$,', '', $dir);
702
+    if ($dir == '') {
703
+        $dir = '.';
704
+    }
705
+
706
+    if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
+        while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
+            if (
709
+                $f[0] != '.' # ignorer . .. .svn etc
710
+                and $f != 'CVS'
711
+                and $f != 'remove.txt'
712
+                and is_readable($f = "$dir/$f")
713
+            ) {
714
+                if (is_file($f)) {
715
+                    if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
+                        $fichiers[] = $f;
717
+                        $nbfiles++;
718
+                    }
719
+                } else {
720
+                    if (is_dir($f) and is_array($recurs)) {
721
+                        $rp = @realpath($f);
722
+                        if (!is_string($rp) or !strlen($rp)) {
723
+                            $rp = $f;
724
+                        } # realpath n'est peut etre pas autorise
725
+                        if (!isset($recurs[$rp])) {
726
+                            $recurs[$rp] = true;
727
+                            $beginning = $fichiers;
728
+                            $end = preg_files(
729
+                                "$f/",
730
+                                $pattern,
731
+                                $maxfiles - $nbfiles,
732
+                                $recurs
733
+                            );
734
+                            $fichiers = array_merge((array)$beginning, (array)$end);
735
+                            $nbfiles = count($fichiers);
736
+                        }
737
+                    }
738
+                }
739
+            }
740
+        }
741
+        closedir($d);
742
+    }
743
+    sort($fichiers);
744
+
745
+    return $fichiers;
746 746
 }
Please login to merge, or discard this patch.