Completed
Push — master ( f2008e...da65df )
by cam
02:08
created
ecrire/inc/rubriques.php 2 patches
Indentation   +621 added lines, -621 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  */
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 
@@ -54,65 +54,65 @@  discard block
 block discarded – undo
54 54
  * @return void
55 55
  **/
56 56
 function calculer_rubriques_if($id_rubrique, $modifs, $infos = [], $postdate = false) {
57
-	$statuts_publies = null;
58
-	$neuf = false;
59
-
60
-	// Compat avec l'ancienne signature
61
-	if (is_string($infos)) {
62
-		$infos = ['statut_ancien' => $infos];
63
-	}
64
-	if (!isset($infos['statut_ancien'])) {
65
-		$infos['statut_ancien'] = '';
66
-	}
67
-
68
-	// On recherche quels statuts tester
69
-	if (
70
-		isset($infos['objet'])
71
-		&& include_spip('inc/filtres')
72
-		&& ($declaration_statut = objet_info($infos['objet'], 'statut'))
73
-		&& is_array($declaration_statut)
74
-	) {
75
-		foreach ($declaration_statut as $champ_statut) {
76
-			if ($champ_statut['champ'] == 'statut') {
77
-				$statuts_publies = array_map('trim', explode(',', $champ_statut['publie']));
78
-				break; // stop on a trouvé le bon champ
79
-			}
80
-		}
81
-	} else {
82
-		$statuts_publies = ['publie'];
83
-	}
84
-
85
-	if (in_array($infos['statut_ancien'], $statuts_publies)) {
86
-		if (
87
-			isset($modifs['statut'])
88
-			|| isset($modifs['id_rubrique'])
89
-			|| $postdate && strtotime($postdate) > time()
90
-		) {
91
-			$neuf |= depublier_branche_rubrique_if($id_rubrique);
92
-		}
93
-		// ne publier que si c'est pas un postdate, ou si la date n'est pas dans le futur
94
-		if ($postdate) {
95
-			calculer_prochain_postdate(true);
96
-			$neuf |= (strtotime($postdate) <= time()); // par securite
97
-		} elseif (isset($modifs['id_rubrique'])) {
98
-			$neuf |= publier_branche_rubrique($modifs['id_rubrique']);
99
-		}
100
-	} elseif (isset($modifs['statut']) && in_array($modifs['statut'], $statuts_publies)) {
101
-		if ($postdate) {
102
-			calculer_prochain_postdate(true);
103
-			$neuf |= (strtotime($postdate) <= time()); // par securite
104
-		} else {
105
-			$neuf |= publier_branche_rubrique($id_rubrique);
106
-		}
107
-	}
108
-
109
-	if ($neuf) {
110
-		// Sauver la date de la derniere mise a jour (pour menu_rubriques)
111
-		ecrire_meta('date_calcul_rubriques', date('U'));
112
-	}
113
-
114
-	$langues = calculer_langues_utilisees();
115
-	ecrire_meta('langues_utilisees', $langues);
57
+    $statuts_publies = null;
58
+    $neuf = false;
59
+
60
+    // Compat avec l'ancienne signature
61
+    if (is_string($infos)) {
62
+        $infos = ['statut_ancien' => $infos];
63
+    }
64
+    if (!isset($infos['statut_ancien'])) {
65
+        $infos['statut_ancien'] = '';
66
+    }
67
+
68
+    // On recherche quels statuts tester
69
+    if (
70
+        isset($infos['objet'])
71
+        && include_spip('inc/filtres')
72
+        && ($declaration_statut = objet_info($infos['objet'], 'statut'))
73
+        && is_array($declaration_statut)
74
+    ) {
75
+        foreach ($declaration_statut as $champ_statut) {
76
+            if ($champ_statut['champ'] == 'statut') {
77
+                $statuts_publies = array_map('trim', explode(',', $champ_statut['publie']));
78
+                break; // stop on a trouvé le bon champ
79
+            }
80
+        }
81
+    } else {
82
+        $statuts_publies = ['publie'];
83
+    }
84
+
85
+    if (in_array($infos['statut_ancien'], $statuts_publies)) {
86
+        if (
87
+            isset($modifs['statut'])
88
+            || isset($modifs['id_rubrique'])
89
+            || $postdate && strtotime($postdate) > time()
90
+        ) {
91
+            $neuf |= depublier_branche_rubrique_if($id_rubrique);
92
+        }
93
+        // ne publier que si c'est pas un postdate, ou si la date n'est pas dans le futur
94
+        if ($postdate) {
95
+            calculer_prochain_postdate(true);
96
+            $neuf |= (strtotime($postdate) <= time()); // par securite
97
+        } elseif (isset($modifs['id_rubrique'])) {
98
+            $neuf |= publier_branche_rubrique($modifs['id_rubrique']);
99
+        }
100
+    } elseif (isset($modifs['statut']) && in_array($modifs['statut'], $statuts_publies)) {
101
+        if ($postdate) {
102
+            calculer_prochain_postdate(true);
103
+            $neuf |= (strtotime($postdate) <= time()); // par securite
104
+        } else {
105
+            $neuf |= publier_branche_rubrique($id_rubrique);
106
+        }
107
+    }
108
+
109
+    if ($neuf) {
110
+        // Sauver la date de la derniere mise a jour (pour menu_rubriques)
111
+        ecrire_meta('date_calcul_rubriques', date('U'));
112
+    }
113
+
114
+    $langues = calculer_langues_utilisees();
115
+    ecrire_meta('langues_utilisees', $langues);
116 116
 }
117 117
 
118 118
 
@@ -130,22 +130,22 @@  discard block
 block discarded – undo
130 130
  *     true si le statut change effectivement
131 131
  */
132 132
 function publier_branche_rubrique($id_rubrique) {
133
-	$id_pred = $id_rubrique;
134
-	while (true) {
135
-		sql_updateq(
136
-			'spip_rubriques',
137
-			['statut' => 'publie', 'date' => date('Y-m-d H:i:s')],
138
-			'id_rubrique=' . intval($id_rubrique)
139
-		);
140
-		$id_parent = sql_getfetsel('id_parent', 'spip_rubriques AS R', 'R.id_rubrique=' . intval($id_rubrique));
141
-		if (!$id_parent) {
142
-			break;
143
-		}
144
-		$id_rubrique = $id_parent;
145
-	}
133
+    $id_pred = $id_rubrique;
134
+    while (true) {
135
+        sql_updateq(
136
+            'spip_rubriques',
137
+            ['statut' => 'publie', 'date' => date('Y-m-d H:i:s')],
138
+            'id_rubrique=' . intval($id_rubrique)
139
+        );
140
+        $id_parent = sql_getfetsel('id_parent', 'spip_rubriques AS R', 'R.id_rubrique=' . intval($id_rubrique));
141
+        if (!$id_parent) {
142
+            break;
143
+        }
144
+        $id_rubrique = $id_parent;
145
+    }
146 146
 
147 147
 #	spip_log(" publier_branche_rubrique($id_rubrique $id_pred");
148
-	return $id_pred != $id_rubrique;
148
+    return $id_pred != $id_rubrique;
149 149
 }
150 150
 
151 151
 /**
@@ -163,20 +163,20 @@  discard block
 block discarded – undo
163 163
  *     true si le statut change effectivement
164 164
  */
165 165
 function depublier_branche_rubrique_if($id_rubrique) {
166
-	$date = date('Y-m-d H:i:s'); // figer la date
167
-
168
-	#	spip_log("depublier_branche_rubrique($id_rubrique ?");
169
-	$id_pred = $id_rubrique;
170
-	while ($id_pred) {
171
-		if (!depublier_rubrique_if($id_pred, $date)) {
172
-			return $id_pred != $id_rubrique;
173
-		}
174
-		// passer au parent si on a depublie
175
-		$r = sql_fetsel('id_parent', 'spip_rubriques', 'id_rubrique=' . intval($id_pred));
176
-		$id_pred = $r['id_parent'];
177
-	}
178
-
179
-	return $id_pred != $id_rubrique;
166
+    $date = date('Y-m-d H:i:s'); // figer la date
167
+
168
+    #	spip_log("depublier_branche_rubrique($id_rubrique ?");
169
+    $id_pred = $id_rubrique;
170
+    while ($id_pred) {
171
+        if (!depublier_rubrique_if($id_pred, $date)) {
172
+            return $id_pred != $id_rubrique;
173
+        }
174
+        // passer au parent si on a depublie
175
+        $r = sql_fetsel('id_parent', 'spip_rubriques', 'id_rubrique=' . intval($id_pred));
176
+        $id_pred = $r['id_parent'];
177
+    }
178
+
179
+    return $id_pred != $id_rubrique;
180 180
 }
181 181
 
182 182
 /**
@@ -193,61 +193,61 @@  discard block
 block discarded – undo
193 193
  *    true si la rubrique a été dépubliée
194 194
  */
195 195
 function depublier_rubrique_if($id_rubrique, $date = null) {
196
-	if (is_null($date)) {
197
-		$date = date('Y-m-d H:i:s');
198
-	}
199
-	$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
200
-		' AND date <= ' . sql_quote($date) : '';
201
-
202
-	if (!$id_rubrique = intval($id_rubrique)) {
203
-		return false;
204
-	}
205
-
206
-	// verifier qu'elle existe et est bien publiee
207
-	$r = sql_fetsel('id_rubrique,statut', 'spip_rubriques', 'id_rubrique=' . intval($id_rubrique));
208
-	if (!$r || $r['statut'] !== 'publie') {
209
-		return false;
210
-	}
211
-
212
-	// On met le nombre de chaque type d'enfants dans un tableau
213
-	// Le type de l'objet est au pluriel
214
-	$compte = [
215
-		'articles' => sql_countsel(
216
-			'spip_articles',
217
-			'id_rubrique=' . intval($id_rubrique) . " AND statut='publie'$postdates"
218
-		),
219
-		'rubriques' => sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique) . " AND statut='publie'"),
220
-		'documents' => sql_countsel(
221
-			'spip_documents AS D JOIN spip_documents_liens AS L ON D.id_document=L.id_document',
222
-			'L.id_objet=' . intval($id_rubrique) . " AND L.objet='rubrique' and D.mode NOT IN('logoon', 'logooff') "
223
-		)
224
-	];
225
-
226
-	// On passe le tableau des comptes dans un pipeline pour que les plugins puissent ajouter (ou retirer) des enfants
227
-	$compte = pipeline(
228
-		'objet_compte_enfants',
229
-		[
230
-			'args' => [
231
-				'objet' => 'rubrique',
232
-				'id_objet' => $id_rubrique,
233
-				'statut' => 'publie',
234
-				'date' => $date
235
-			],
236
-			'data' => $compte
237
-		]
238
-	);
239
-
240
-	// S'il y a au moins un enfant de n'importe quoi, on ne dépublie pas
241
-	foreach ($compte as $objet => $n) {
242
-		if ($n) {
243
-			return false;
244
-		}
245
-	}
246
-
247
-	sql_updateq('spip_rubriques', ['statut' => 'prepa'], 'id_rubrique=' . intval($id_rubrique));
196
+    if (is_null($date)) {
197
+        $date = date('Y-m-d H:i:s');
198
+    }
199
+    $postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
200
+        ' AND date <= ' . sql_quote($date) : '';
201
+
202
+    if (!$id_rubrique = intval($id_rubrique)) {
203
+        return false;
204
+    }
205
+
206
+    // verifier qu'elle existe et est bien publiee
207
+    $r = sql_fetsel('id_rubrique,statut', 'spip_rubriques', 'id_rubrique=' . intval($id_rubrique));
208
+    if (!$r || $r['statut'] !== 'publie') {
209
+        return false;
210
+    }
211
+
212
+    // On met le nombre de chaque type d'enfants dans un tableau
213
+    // Le type de l'objet est au pluriel
214
+    $compte = [
215
+        'articles' => sql_countsel(
216
+            'spip_articles',
217
+            'id_rubrique=' . intval($id_rubrique) . " AND statut='publie'$postdates"
218
+        ),
219
+        'rubriques' => sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique) . " AND statut='publie'"),
220
+        'documents' => sql_countsel(
221
+            'spip_documents AS D JOIN spip_documents_liens AS L ON D.id_document=L.id_document',
222
+            'L.id_objet=' . intval($id_rubrique) . " AND L.objet='rubrique' and D.mode NOT IN('logoon', 'logooff') "
223
+        )
224
+    ];
225
+
226
+    // On passe le tableau des comptes dans un pipeline pour que les plugins puissent ajouter (ou retirer) des enfants
227
+    $compte = pipeline(
228
+        'objet_compte_enfants',
229
+        [
230
+            'args' => [
231
+                'objet' => 'rubrique',
232
+                'id_objet' => $id_rubrique,
233
+                'statut' => 'publie',
234
+                'date' => $date
235
+            ],
236
+            'data' => $compte
237
+        ]
238
+    );
239
+
240
+    // S'il y a au moins un enfant de n'importe quoi, on ne dépublie pas
241
+    foreach ($compte as $objet => $n) {
242
+        if ($n) {
243
+            return false;
244
+        }
245
+    }
246
+
247
+    sql_updateq('spip_rubriques', ['statut' => 'prepa'], 'id_rubrique=' . intval($id_rubrique));
248 248
 
249 249
 #		spip_log("depublier_rubrique $id_pred");
250
-	return true;
250
+    return true;
251 251
 }
252 252
 
253 253
 
@@ -270,18 +270,18 @@  discard block
 block discarded – undo
270 270
  **/
271 271
 function calculer_rubriques() {
272 272
 
273
-	calculer_rubriques_publiees();
273
+    calculer_rubriques_publiees();
274 274
 
275
-	// Apres chaque (de)publication
276
-	// recalculer les langues utilisees sur le site
277
-	$langues = calculer_langues_utilisees();
278
-	ecrire_meta('langues_utilisees', $langues);
275
+    // Apres chaque (de)publication
276
+    // recalculer les langues utilisees sur le site
277
+    $langues = calculer_langues_utilisees();
278
+    ecrire_meta('langues_utilisees', $langues);
279 279
 
280
-	// Sauver la date de la derniere mise a jour (pour menu_rubriques)
281
-	ecrire_meta('date_calcul_rubriques', date('U'));
280
+    // Sauver la date de la derniere mise a jour (pour menu_rubriques)
281
+    ecrire_meta('date_calcul_rubriques', date('U'));
282 282
 
283
-	// on calcule la date du prochain article post-date
284
-	calculer_prochain_postdate();
283
+    // on calcule la date du prochain article post-date
284
+    calculer_prochain_postdate();
285 285
 }
286 286
 
287 287
 
@@ -298,61 +298,61 @@  discard block
 block discarded – undo
298 298
  **/
299 299
 function calculer_rubriques_publiees() {
300 300
 
301
-	// Mettre les compteurs a zero
302
-	sql_updateq('spip_rubriques', ['date_tmp' => '0000-00-00 00:00:00', 'statut_tmp' => 'prepa']);
303
-
304
-	//
305
-	// Publier et dater les rubriques qui ont un article publie
306
-	//
307
-
308
-	// Afficher les articles post-dates ?
309
-	$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
310
-		'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
311
-
312
-	$r = sql_select(
313
-		'R.id_rubrique AS id, max(A.date) AS date_h',
314
-		'spip_rubriques AS R JOIN spip_articles AS A ON R.id_rubrique = A.id_rubrique',
315
-		"A.date>R.date_tmp AND A.statut='publie' $postdates ",
316
-		'R.id_rubrique'
317
-	);
318
-	while ($row = sql_fetch($r)) {
319
-		sql_updateq(
320
-			'spip_rubriques',
321
-			['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
322
-			'id_rubrique=' . intval($row['id'])
323
-		);
324
-	}
325
-
326
-	// point d'entree pour permettre a des plugins de gerer le statut
327
-	// autrement (par ex: toute rubrique est publiee des sa creation)
328
-	// Ce pipeline fait ce qu'il veut, mais s'il touche aux statuts/dates
329
-	// c'est statut_tmp/date_tmp qu'il doit modifier
330
-	// [C'est un trigger... a renommer en trig_calculer_rubriques ?]
331
-	pipeline('calculer_rubriques', null);
332
-
333
-
334
-	// Les rubriques qui ont une rubrique fille plus recente
335
-	// on tourne tant que les donnees remontent vers la racine.
336
-	do {
337
-		$continuer = false;
338
-		$r = sql_select(
339
-			'R.id_rubrique AS id, max(SR.date_tmp) AS date_h',
340
-			'spip_rubriques AS R JOIN spip_rubriques AS SR ON R.id_rubrique = SR.id_parent',
341
-			"(SR.date_tmp>R.date_tmp OR R.statut_tmp<>'publie') AND SR.statut_tmp='publie' ",
342
-			'R.id_rubrique'
343
-		);
344
-		while ($row = sql_fetch($r)) {
345
-			sql_updateq(
346
-				'spip_rubriques',
347
-				['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
348
-				'id_rubrique=' . intval($row['id'])
349
-			);
350
-			$continuer = true;
351
-		}
352
-	} while ($continuer);
353
-
354
-	// Enregistrement des modifs
355
-	sql_update('spip_rubriques', ['date' => 'date_tmp', 'statut' => 'statut_tmp']);
301
+    // Mettre les compteurs a zero
302
+    sql_updateq('spip_rubriques', ['date_tmp' => '0000-00-00 00:00:00', 'statut_tmp' => 'prepa']);
303
+
304
+    //
305
+    // Publier et dater les rubriques qui ont un article publie
306
+    //
307
+
308
+    // Afficher les articles post-dates ?
309
+    $postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
310
+        'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
311
+
312
+    $r = sql_select(
313
+        'R.id_rubrique AS id, max(A.date) AS date_h',
314
+        'spip_rubriques AS R JOIN spip_articles AS A ON R.id_rubrique = A.id_rubrique',
315
+        "A.date>R.date_tmp AND A.statut='publie' $postdates ",
316
+        'R.id_rubrique'
317
+    );
318
+    while ($row = sql_fetch($r)) {
319
+        sql_updateq(
320
+            'spip_rubriques',
321
+            ['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
322
+            'id_rubrique=' . intval($row['id'])
323
+        );
324
+    }
325
+
326
+    // point d'entree pour permettre a des plugins de gerer le statut
327
+    // autrement (par ex: toute rubrique est publiee des sa creation)
328
+    // Ce pipeline fait ce qu'il veut, mais s'il touche aux statuts/dates
329
+    // c'est statut_tmp/date_tmp qu'il doit modifier
330
+    // [C'est un trigger... a renommer en trig_calculer_rubriques ?]
331
+    pipeline('calculer_rubriques', null);
332
+
333
+
334
+    // Les rubriques qui ont une rubrique fille plus recente
335
+    // on tourne tant que les donnees remontent vers la racine.
336
+    do {
337
+        $continuer = false;
338
+        $r = sql_select(
339
+            'R.id_rubrique AS id, max(SR.date_tmp) AS date_h',
340
+            'spip_rubriques AS R JOIN spip_rubriques AS SR ON R.id_rubrique = SR.id_parent',
341
+            "(SR.date_tmp>R.date_tmp OR R.statut_tmp<>'publie') AND SR.statut_tmp='publie' ",
342
+            'R.id_rubrique'
343
+        );
344
+        while ($row = sql_fetch($r)) {
345
+            sql_updateq(
346
+                'spip_rubriques',
347
+                ['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
348
+                'id_rubrique=' . intval($row['id'])
349
+            );
350
+            $continuer = true;
351
+        }
352
+    } while ($continuer);
353
+
354
+    // Enregistrement des modifs
355
+    sql_update('spip_rubriques', ['date' => 'date_tmp', 'statut' => 'statut_tmp']);
356 356
 }
357 357
 
358 358
 /**
@@ -367,123 +367,123 @@  discard block
 block discarded – undo
367 367
  * @return void
368 368
  **/
369 369
 function propager_les_secteurs() {
370
-	// Profondeur 0
371
-	// Toutes les rubriques racines sont de profondeur 0
372
-	// et fixer les id_secteur des rubriques racines
373
-	sql_update('spip_rubriques', ['id_secteur' => 'id_rubrique', 'profondeur' => 0], 'id_parent=0');
374
-	// Toute rubrique non racine est de profondeur >0
375
-	sql_updateq('spip_rubriques', ['profondeur' => 1], 'id_parent<>0 AND profondeur=0');
376
-
377
-	// securite : pas plus d'iteration que de rubriques dans la base
378
-	$maxiter = sql_countsel('spip_rubriques');
379
-
380
-	// reparer les rubriques qui n'ont pas l'id_secteur de leur parent
381
-	// on fait profondeur par profondeur
382
-
383
-	$prof = 0;
384
-	do {
385
-		$continuer = false;
386
-
387
-		// Par recursivite : si toutes les rubriques de profondeur $prof sont bonnes
388
-		// on fixe le profondeur $prof+1
389
-
390
-		// Toutes les rubriques dont le parent est de profondeur $prof ont une profondeur $prof+1
391
-		// on teste A.profondeur > $prof+1 car :
392
-		// - toutes les rubriques de profondeur 0 à $prof sont bonnes
393
-		// - si A.profondeur = $prof+1 c'est bon
394
-		// - cela nous protege de la boucle infinie en cas de reference circulaire dans les rubriques
395
-		$maxiter2 = $maxiter;
396
-		while (
397
-			$maxiter2--
398
-			&& ($rows = sql_allfetsel(
399
-				'A.id_rubrique AS id, R.id_secteur AS id_secteur, R.profondeur+1 as profondeur',
400
-				'spip_rubriques AS A JOIN spip_rubriques AS R ON A.id_parent = R.id_rubrique',
401
-				'R.profondeur=' . intval($prof) . ' AND (A.id_secteur <> R.id_secteur OR A.profondeur > R.profondeur+1)',
402
-				'',
403
-				'R.id_secteur',
404
-				'0,100'
405
-			))
406
-		) {
407
-			$id_secteur = null;
408
-			$ids = [];
409
-			while ($row = array_shift($rows)) {
410
-				if ($row['id_secteur'] !== $id_secteur) {
411
-					if (count($ids)) {
412
-						sql_updateq(
413
-							'spip_rubriques',
414
-							['id_secteur' => $id_secteur, 'profondeur' => $prof + 1],
415
-							sql_in('id_rubrique', $ids)
416
-						);
417
-					}
418
-					$id_secteur = $row['id_secteur'];
419
-					$ids = [];
420
-				}
421
-				$ids[] = $row['id'];
422
-			}
423
-			if (count($ids)) {
424
-				sql_updateq(
425
-					'spip_rubriques',
426
-					['id_secteur' => $id_secteur, 'profondeur' => $prof + 1],
427
-					sql_in('id_rubrique', $ids)
428
-				);
429
-			}
430
-		}
431
-
432
-
433
-		// Toutes les rubriques de profondeur $prof+1 qui n'ont pas un parent de profondeur $prof sont decalees
434
-		$maxiter2 = $maxiter;
435
-		while (
436
-			$maxiter2--
437
-			&& ($rows = sql_allfetsel(
438
-				'id_rubrique as id',
439
-				'spip_rubriques',
440
-				'profondeur=' . intval($prof + 1) . ' AND id_parent NOT IN (' . sql_get_select(
441
-					'zzz.id_rubrique',
442
-					'spip_rubriques AS zzz',
443
-					'zzz.profondeur=' . intval($prof)
444
-				) . ')',
445
-				'',
446
-				'',
447
-				'0,100'
448
-			))
449
-		) {
450
-			$rows = array_column($rows, 'id');
451
-			sql_updateq('spip_rubriques', ['profondeur' => $prof + 2], sql_in('id_rubrique', $rows));
452
-		}
453
-
454
-		// ici on a fini de valider $prof+1, toutes les rubriques de prondeur 0 a $prof+1 sont OK
455
-		// si pas de rubrique a profondeur $prof+1 pas la peine de continuer
456
-		// si il reste des rubriques non vues, c'est une branche morte ou reference circulaire (base foireuse)
457
-		// on arrete les frais
458
-		if (sql_countsel('spip_rubriques', 'profondeur=' . intval($prof + 1))) {
459
-			$prof++;
460
-			$continuer = true;
461
-		}
462
-	} while ($continuer && $maxiter--);
463
-
464
-	// loger si la table des rubriques semble foireuse
465
-	// et mettre un id_secteur=0 sur ces rubriques pour eviter toute selection par les boucles
466
-	if (sql_countsel('spip_rubriques', 'profondeur>' . intval($prof + 1))) {
467
-		spip_log(
468
-			'Les rubriques de profondeur>' . ($prof + 1) . ' semblent suspectes (branches morte ou reference circulaire dans les parents)',
469
-			_LOG_CRITIQUE
470
-		);
471
-		sql_update('spip_rubriques', ['id_secteur' => 0], 'profondeur>' . intval($prof + 1));
472
-	}
473
-
474
-	// reparer les articles
475
-	$r = sql_select(
476
-		'A.id_article AS id, R.id_secteur AS secteur',
477
-		'spip_articles AS A, spip_rubriques AS R',
478
-		'A.id_rubrique = R.id_rubrique AND A.id_secteur <> R.id_secteur'
479
-	);
480
-
481
-	while ($row = sql_fetch($r)) {
482
-		sql_update('spip_articles', ['id_secteur' => $row['secteur']], 'id_article=' . intval($row['id']));
483
-	}
484
-
485
-	// avertir les plugins qui peuvent faire leur mises a jour egalement
486
-	pipeline('trig_propager_les_secteurs', '');
370
+    // Profondeur 0
371
+    // Toutes les rubriques racines sont de profondeur 0
372
+    // et fixer les id_secteur des rubriques racines
373
+    sql_update('spip_rubriques', ['id_secteur' => 'id_rubrique', 'profondeur' => 0], 'id_parent=0');
374
+    // Toute rubrique non racine est de profondeur >0
375
+    sql_updateq('spip_rubriques', ['profondeur' => 1], 'id_parent<>0 AND profondeur=0');
376
+
377
+    // securite : pas plus d'iteration que de rubriques dans la base
378
+    $maxiter = sql_countsel('spip_rubriques');
379
+
380
+    // reparer les rubriques qui n'ont pas l'id_secteur de leur parent
381
+    // on fait profondeur par profondeur
382
+
383
+    $prof = 0;
384
+    do {
385
+        $continuer = false;
386
+
387
+        // Par recursivite : si toutes les rubriques de profondeur $prof sont bonnes
388
+        // on fixe le profondeur $prof+1
389
+
390
+        // Toutes les rubriques dont le parent est de profondeur $prof ont une profondeur $prof+1
391
+        // on teste A.profondeur > $prof+1 car :
392
+        // - toutes les rubriques de profondeur 0 à $prof sont bonnes
393
+        // - si A.profondeur = $prof+1 c'est bon
394
+        // - cela nous protege de la boucle infinie en cas de reference circulaire dans les rubriques
395
+        $maxiter2 = $maxiter;
396
+        while (
397
+            $maxiter2--
398
+            && ($rows = sql_allfetsel(
399
+                'A.id_rubrique AS id, R.id_secteur AS id_secteur, R.profondeur+1 as profondeur',
400
+                'spip_rubriques AS A JOIN spip_rubriques AS R ON A.id_parent = R.id_rubrique',
401
+                'R.profondeur=' . intval($prof) . ' AND (A.id_secteur <> R.id_secteur OR A.profondeur > R.profondeur+1)',
402
+                '',
403
+                'R.id_secteur',
404
+                '0,100'
405
+            ))
406
+        ) {
407
+            $id_secteur = null;
408
+            $ids = [];
409
+            while ($row = array_shift($rows)) {
410
+                if ($row['id_secteur'] !== $id_secteur) {
411
+                    if (count($ids)) {
412
+                        sql_updateq(
413
+                            'spip_rubriques',
414
+                            ['id_secteur' => $id_secteur, 'profondeur' => $prof + 1],
415
+                            sql_in('id_rubrique', $ids)
416
+                        );
417
+                    }
418
+                    $id_secteur = $row['id_secteur'];
419
+                    $ids = [];
420
+                }
421
+                $ids[] = $row['id'];
422
+            }
423
+            if (count($ids)) {
424
+                sql_updateq(
425
+                    'spip_rubriques',
426
+                    ['id_secteur' => $id_secteur, 'profondeur' => $prof + 1],
427
+                    sql_in('id_rubrique', $ids)
428
+                );
429
+            }
430
+        }
431
+
432
+
433
+        // Toutes les rubriques de profondeur $prof+1 qui n'ont pas un parent de profondeur $prof sont decalees
434
+        $maxiter2 = $maxiter;
435
+        while (
436
+            $maxiter2--
437
+            && ($rows = sql_allfetsel(
438
+                'id_rubrique as id',
439
+                'spip_rubriques',
440
+                'profondeur=' . intval($prof + 1) . ' AND id_parent NOT IN (' . sql_get_select(
441
+                    'zzz.id_rubrique',
442
+                    'spip_rubriques AS zzz',
443
+                    'zzz.profondeur=' . intval($prof)
444
+                ) . ')',
445
+                '',
446
+                '',
447
+                '0,100'
448
+            ))
449
+        ) {
450
+            $rows = array_column($rows, 'id');
451
+            sql_updateq('spip_rubriques', ['profondeur' => $prof + 2], sql_in('id_rubrique', $rows));
452
+        }
453
+
454
+        // ici on a fini de valider $prof+1, toutes les rubriques de prondeur 0 a $prof+1 sont OK
455
+        // si pas de rubrique a profondeur $prof+1 pas la peine de continuer
456
+        // si il reste des rubriques non vues, c'est une branche morte ou reference circulaire (base foireuse)
457
+        // on arrete les frais
458
+        if (sql_countsel('spip_rubriques', 'profondeur=' . intval($prof + 1))) {
459
+            $prof++;
460
+            $continuer = true;
461
+        }
462
+    } while ($continuer && $maxiter--);
463
+
464
+    // loger si la table des rubriques semble foireuse
465
+    // et mettre un id_secteur=0 sur ces rubriques pour eviter toute selection par les boucles
466
+    if (sql_countsel('spip_rubriques', 'profondeur>' . intval($prof + 1))) {
467
+        spip_log(
468
+            'Les rubriques de profondeur>' . ($prof + 1) . ' semblent suspectes (branches morte ou reference circulaire dans les parents)',
469
+            _LOG_CRITIQUE
470
+        );
471
+        sql_update('spip_rubriques', ['id_secteur' => 0], 'profondeur>' . intval($prof + 1));
472
+    }
473
+
474
+    // reparer les articles
475
+    $r = sql_select(
476
+        'A.id_article AS id, R.id_secteur AS secteur',
477
+        'spip_articles AS A, spip_rubriques AS R',
478
+        'A.id_rubrique = R.id_rubrique AND A.id_secteur <> R.id_secteur'
479
+    );
480
+
481
+    while ($row = sql_fetch($r)) {
482
+        sql_update('spip_articles', ['id_secteur' => $row['secteur']], 'id_article=' . intval($row['id']));
483
+    }
484
+
485
+    // avertir les plugins qui peuvent faire leur mises a jour egalement
486
+    pipeline('trig_propager_les_secteurs', '');
487 487
 }
488 488
 
489 489
 
@@ -498,23 +498,23 @@  discard block
 block discarded – undo
498 498
  *     true si un changement a eu lieu
499 499
  **/
500 500
 function calculer_langues_rubriques_etape() {
501
-	$s = sql_select(
502
-		'A.id_rubrique AS id_rubrique, R.lang AS lang',
503
-		'spip_rubriques AS A, spip_rubriques AS R',
504
-		"A.id_parent = R.id_rubrique AND A.langue_choisie != 'oui' AND R.lang<>'' AND R.lang<>A.lang"
505
-	);
506
-
507
-	$t = false;
508
-	while ($row = sql_fetch($s)) {
509
-		$id_rubrique = $row['id_rubrique'];
510
-		$t = sql_updateq(
511
-			'spip_rubriques',
512
-			['lang' => $row['lang'], 'langue_choisie' => 'non'],
513
-			'id_rubrique=' . intval($id_rubrique)
514
-		);
515
-	}
516
-
517
-	return $t;
501
+    $s = sql_select(
502
+        'A.id_rubrique AS id_rubrique, R.lang AS lang',
503
+        'spip_rubriques AS A, spip_rubriques AS R',
504
+        "A.id_parent = R.id_rubrique AND A.langue_choisie != 'oui' AND R.lang<>'' AND R.lang<>A.lang"
505
+    );
506
+
507
+    $t = false;
508
+    while ($row = sql_fetch($s)) {
509
+        $id_rubrique = $row['id_rubrique'];
510
+        $t = sql_updateq(
511
+            'spip_rubriques',
512
+            ['lang' => $row['lang'], 'langue_choisie' => 'non'],
513
+            'id_rubrique=' . intval($id_rubrique)
514
+        );
515
+    }
516
+
517
+    return $t;
518 518
 }
519 519
 
520 520
 /**
@@ -534,38 +534,38 @@  discard block
 block discarded – undo
534 534
  **/
535 535
 function calculer_langues_rubriques() {
536 536
 
537
-	// rubriques (recursivite)
538
-	sql_updateq(
539
-		'spip_rubriques',
540
-		['lang' => $GLOBALS['meta']['langue_site'], 'langue_choisie' => 'non'],
541
-		"id_parent=0 AND langue_choisie != 'oui'"
542
-	);
543
-	while (calculer_langues_rubriques_etape()) {
544
-		;
545
-	}
546
-
547
-	// articles
548
-	$s = sql_select(
549
-		'A.id_article AS id_article, R.lang AS lang',
550
-		'spip_articles AS A, spip_rubriques AS R',
551
-		"A.id_rubrique = R.id_rubrique AND A.langue_choisie != 'oui' AND (length(A.lang)=0 OR length(R.lang)>0) AND R.lang<>A.lang"
552
-	);
553
-	while ($row = sql_fetch($s)) {
554
-		$id_article = $row['id_article'];
555
-		sql_updateq(
556
-			'spip_articles',
557
-			['lang' => $row['lang'], 'langue_choisie' => 'non'],
558
-			'id_article=' . intval($id_article)
559
-		);
560
-	}
561
-
562
-	if ($GLOBALS['meta']['multi_rubriques'] == 'oui') {
563
-		$langues = calculer_langues_utilisees();
564
-		ecrire_meta('langues_utilisees', $langues);
565
-	}
566
-
567
-	// avertir les plugins qui peuvent faire leur mises a jour egalement
568
-	pipeline('trig_calculer_langues_rubriques', '');
537
+    // rubriques (recursivite)
538
+    sql_updateq(
539
+        'spip_rubriques',
540
+        ['lang' => $GLOBALS['meta']['langue_site'], 'langue_choisie' => 'non'],
541
+        "id_parent=0 AND langue_choisie != 'oui'"
542
+    );
543
+    while (calculer_langues_rubriques_etape()) {
544
+        ;
545
+    }
546
+
547
+    // articles
548
+    $s = sql_select(
549
+        'A.id_article AS id_article, R.lang AS lang',
550
+        'spip_articles AS A, spip_rubriques AS R',
551
+        "A.id_rubrique = R.id_rubrique AND A.langue_choisie != 'oui' AND (length(A.lang)=0 OR length(R.lang)>0) AND R.lang<>A.lang"
552
+    );
553
+    while ($row = sql_fetch($s)) {
554
+        $id_article = $row['id_article'];
555
+        sql_updateq(
556
+            'spip_articles',
557
+            ['lang' => $row['lang'], 'langue_choisie' => 'non'],
558
+            'id_article=' . intval($id_article)
559
+        );
560
+    }
561
+
562
+    if ($GLOBALS['meta']['multi_rubriques'] == 'oui') {
563
+        $langues = calculer_langues_utilisees();
564
+        ecrire_meta('langues_utilisees', $langues);
565
+    }
566
+
567
+    // avertir les plugins qui peuvent faire leur mises a jour egalement
568
+    pipeline('trig_calculer_langues_rubriques', '');
569 569
 }
570 570
 
571 571
 
@@ -582,80 +582,80 @@  discard block
 block discarded – undo
582 582
  *    Liste des langues utilisées séparées par des virgules
583 583
  **/
584 584
 function calculer_langues_utilisees($serveur = '') {
585
-	include_spip('public/interfaces');
586
-	include_spip('public/compiler');
587
-	include_spip('public/composer');
588
-	include_spip('public/phraser_html');
589
-	$langues = [];
590
-
591
-	$langues[$GLOBALS['meta']['langue_site']] = 1;
592
-
593
-	include_spip('base/objets');
594
-	$tables = lister_tables_objets_sql();
595
-	$trouver_table = charger_fonction('trouver_table', 'base');
596
-
597
-	foreach (array_keys($tables) as $t) {
598
-		$desc = $trouver_table($t, $serveur);
599
-		// c'est une table avec des langues
600
-		if (
601
-			$desc['exist']
602
-			&& isset($desc['field']['lang'])
603
-			&& isset($desc['field']['langue_choisie'])
604
-		) {
605
-			$boucle = new Boucle();
606
-			$boucle->show = $desc;
607
-			$boucle->nom = 'calculer_langues_utilisees';
608
-			$boucle->id_boucle = $desc['table_objet'];
609
-			$boucle->id_table = $desc['table_objet'];
610
-			$boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
611
-			$boucle->sql_serveur = $serveur;
612
-			$boucle->select[] = 'DISTINCT lang';
613
-			$boucle->from[$desc['table_objet']] = $t;
614
-			$boucle->separateur[] = ',';
615
-			$boucle->return = '$Pile[$SP][\'lang\']';
616
-			$boucle->iterateur = 'sql';
617
-
618
-			$boucle->descr['nom'] = 'calculer_langues_utilisees'; // eviter notice php
619
-			$boucle->descr['sourcefile'] = 'internal';
620
-			$boucle->descr['gram'] = 'html';
621
-
622
-			$boucle = pipeline('pre_boucle', $boucle);
623
-
624
-			if (
625
-				isset($desc['statut'])
626
-				&& $desc['statut']
627
-			) {
628
-				$boucles = [
629
-					'calculer_langues_utilisees' => $boucle,
630
-				];
631
-				// generer un nom de fonction "anonyme" unique
632
-				do {
633
-					$functionname = 'f_calculer_langues_utilisees_' . $boucle->id_table . '_' . time() . '_' . random_int(0, mt_getrandmax());
634
-				} while (function_exists($functionname));
635
-				$code = calculer_boucle('calculer_langues_utilisees', $boucles);
636
-				$code = '$SP=0; $command=array();$command["connect"] = $connect = "' . $serveur . '"; $Pile=array(0=>array());' . "\n" . $code;
637
-				$code = 'function ' . $functionname . '(){' . $code . '};$res = ' . $functionname . '();';
638
-				$res = '';
639
-				eval($code);
640
-				$res = explode(',', $res);
641
-				foreach ($res as $lang) {
642
-					$langues[$lang] = 1;
643
-				}
644
-			} else {
645
-				$res = sql_select(implode(',', $boucle->select), $boucle->from);
646
-				while ($row = sql_fetch($res)) {
647
-					$langues[$row['lang']] = 1;
648
-				}
649
-			}
650
-		}
651
-	}
652
-
653
-	$langues = array_filter(array_keys($langues));
654
-	sort($langues);
655
-	$langues = join(',', $langues);
656
-	spip_log("langues utilisees: $langues");
657
-
658
-	return $langues;
585
+    include_spip('public/interfaces');
586
+    include_spip('public/compiler');
587
+    include_spip('public/composer');
588
+    include_spip('public/phraser_html');
589
+    $langues = [];
590
+
591
+    $langues[$GLOBALS['meta']['langue_site']] = 1;
592
+
593
+    include_spip('base/objets');
594
+    $tables = lister_tables_objets_sql();
595
+    $trouver_table = charger_fonction('trouver_table', 'base');
596
+
597
+    foreach (array_keys($tables) as $t) {
598
+        $desc = $trouver_table($t, $serveur);
599
+        // c'est une table avec des langues
600
+        if (
601
+            $desc['exist']
602
+            && isset($desc['field']['lang'])
603
+            && isset($desc['field']['langue_choisie'])
604
+        ) {
605
+            $boucle = new Boucle();
606
+            $boucle->show = $desc;
607
+            $boucle->nom = 'calculer_langues_utilisees';
608
+            $boucle->id_boucle = $desc['table_objet'];
609
+            $boucle->id_table = $desc['table_objet'];
610
+            $boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
611
+            $boucle->sql_serveur = $serveur;
612
+            $boucle->select[] = 'DISTINCT lang';
613
+            $boucle->from[$desc['table_objet']] = $t;
614
+            $boucle->separateur[] = ',';
615
+            $boucle->return = '$Pile[$SP][\'lang\']';
616
+            $boucle->iterateur = 'sql';
617
+
618
+            $boucle->descr['nom'] = 'calculer_langues_utilisees'; // eviter notice php
619
+            $boucle->descr['sourcefile'] = 'internal';
620
+            $boucle->descr['gram'] = 'html';
621
+
622
+            $boucle = pipeline('pre_boucle', $boucle);
623
+
624
+            if (
625
+                isset($desc['statut'])
626
+                && $desc['statut']
627
+            ) {
628
+                $boucles = [
629
+                    'calculer_langues_utilisees' => $boucle,
630
+                ];
631
+                // generer un nom de fonction "anonyme" unique
632
+                do {
633
+                    $functionname = 'f_calculer_langues_utilisees_' . $boucle->id_table . '_' . time() . '_' . random_int(0, mt_getrandmax());
634
+                } while (function_exists($functionname));
635
+                $code = calculer_boucle('calculer_langues_utilisees', $boucles);
636
+                $code = '$SP=0; $command=array();$command["connect"] = $connect = "' . $serveur . '"; $Pile=array(0=>array());' . "\n" . $code;
637
+                $code = 'function ' . $functionname . '(){' . $code . '};$res = ' . $functionname . '();';
638
+                $res = '';
639
+                eval($code);
640
+                $res = explode(',', $res);
641
+                foreach ($res as $lang) {
642
+                    $langues[$lang] = 1;
643
+                }
644
+            } else {
645
+                $res = sql_select(implode(',', $boucle->select), $boucle->from);
646
+                while ($row = sql_fetch($res)) {
647
+                    $langues[$row['lang']] = 1;
648
+                }
649
+            }
650
+        }
651
+    }
652
+
653
+    $langues = array_filter(array_keys($langues));
654
+    sort($langues);
655
+    $langues = join(',', $langues);
656
+    spip_log("langues utilisees: $langues");
657
+
658
+    return $langues;
659 659
 }
660 660
 
661 661
 /**
@@ -672,9 +672,9 @@  discard block
 block discarded – undo
672 672
  *     incluant les rubriques noeuds et toutes leurs descendances
673 673
  */
674 674
 function calcul_branche_in($id) {
675
-	$calcul_branche_in = charger_fonction('calcul_branche_in', 'inc');
675
+    $calcul_branche_in = charger_fonction('calcul_branche_in', 'inc');
676 676
 
677
-	return $calcul_branche_in($id);
677
+    return $calcul_branche_in($id);
678 678
 }
679 679
 
680 680
 /**
@@ -692,9 +692,9 @@  discard block
 block discarded – undo
692 692
  *     incluant les rubriques transmises et toutes leurs parentées
693 693
  */
694 694
 function calcul_hierarchie_in($id, $tout = true) {
695
-	$calcul_hierarchie_in = charger_fonction('calcul_hierarchie_in', 'inc');
695
+    $calcul_hierarchie_in = charger_fonction('calcul_hierarchie_in', 'inc');
696 696
 
697
-	return $calcul_hierarchie_in($id, $tout);
697
+    return $calcul_hierarchie_in($id, $tout);
698 698
 }
699 699
 
700 700
 
@@ -715,40 +715,40 @@  discard block
 block discarded – undo
715 715
  *     incluant les rubriques noeuds et toutes leurs descendances
716 716
  */
717 717
 function inc_calcul_branche_in_dist($id) {
718
-	static $b = [];
719
-
720
-	// normaliser $id qui a pu arriver comme un array, comme un entier, ou comme une chaine NN,NN,NN
721
-	if (!is_array($id)) {
722
-		$id = explode(',', $id);
723
-	}
724
-	$id = join(',', array_map('intval', $id));
725
-	if (isset($b[$id])) {
726
-		return $b[$id];
727
-	}
728
-
729
-	// Notre branche commence par la rubrique de depart
730
-	$branche = $r = $id;
731
-
732
-	// On ajoute une generation (les filles de la generation precedente)
733
-	// jusqu'a epuisement, en se protegeant des references circulaires
734
-	$maxiter = 10000;
735
-	while (
736
-		$maxiter-- && ($filles = sql_allfetsel(
737
-			'id_rubrique',
738
-			'spip_rubriques',
739
-			sql_in('id_parent', $r) . ' AND ' . sql_in('id_rubrique', $r, 'NOT')
740
-		))
741
-	) {
742
-		$r = join(',', array_column($filles, 'id_rubrique'));
743
-		$branche .= ',' . $r;
744
-	}
745
-
746
-	# securite pour ne pas plomber la conso memoire sur les sites prolifiques
747
-	if (strlen($branche) < 10000) {
748
-		$b[$id] = $branche;
749
-	}
750
-
751
-	return $branche;
718
+    static $b = [];
719
+
720
+    // normaliser $id qui a pu arriver comme un array, comme un entier, ou comme une chaine NN,NN,NN
721
+    if (!is_array($id)) {
722
+        $id = explode(',', $id);
723
+    }
724
+    $id = join(',', array_map('intval', $id));
725
+    if (isset($b[$id])) {
726
+        return $b[$id];
727
+    }
728
+
729
+    // Notre branche commence par la rubrique de depart
730
+    $branche = $r = $id;
731
+
732
+    // On ajoute une generation (les filles de la generation precedente)
733
+    // jusqu'a epuisement, en se protegeant des references circulaires
734
+    $maxiter = 10000;
735
+    while (
736
+        $maxiter-- && ($filles = sql_allfetsel(
737
+            'id_rubrique',
738
+            'spip_rubriques',
739
+            sql_in('id_parent', $r) . ' AND ' . sql_in('id_rubrique', $r, 'NOT')
740
+        ))
741
+    ) {
742
+        $r = join(',', array_column($filles, 'id_rubrique'));
743
+        $branche .= ',' . $r;
744
+    }
745
+
746
+    # securite pour ne pas plomber la conso memoire sur les sites prolifiques
747
+    if (strlen($branche) < 10000) {
748
+        $b[$id] = $branche;
749
+    }
750
+
751
+    return $branche;
752 752
 }
753 753
 
754 754
 
@@ -770,45 +770,45 @@  discard block
 block discarded – undo
770 770
  *     incluant les rubriques transmises et toutes leurs parentées
771 771
  */
772 772
 function inc_calcul_hierarchie_in_dist($id, $tout = true) {
773
-	static $b = [];
774
-
775
-	// normaliser $id qui a pu arriver comme un array, comme un entier, ou comme une chaine NN,NN,NN
776
-	if (!is_array($id)) {
777
-		$id = explode(',', $id);
778
-	}
779
-	$id = join(',', array_map('intval', $id));
780
-
781
-	if (isset($b[$id])) {
782
-		// Notre branche commence par la rubrique de depart si $tout=true
783
-		return $tout ? (strlen($b[$id]) ? $b[$id] . ",$id" : $id) : $b[$id];
784
-	}
785
-
786
-	$hier = '';
787
-
788
-	// On ajoute une generation (les filles de la generation precedente)
789
-	// jusqu'a epuisement, en se protegeant des references circulaires
790
-	$ids_nouveaux_parents = $id;
791
-	$maxiter = 10000;
792
-	while (
793
-		$maxiter-- && ($parents = sql_allfetsel(
794
-			'id_parent',
795
-			'spip_rubriques',
796
-			sql_in('id_rubrique', $ids_nouveaux_parents) . ' AND ' . sql_in('id_parent', $hier, 'NOT')
797
-		))
798
-	) {
799
-		$ids_nouveaux_parents = join(',', array_column($parents, 'id_parent'));
800
-		$hier = $ids_nouveaux_parents . (strlen($hier) ? ',' . $hier : '');
801
-	}
802
-
803
-	# securite pour ne pas plomber la conso memoire sur les sites prolifiques
804
-	if (strlen($hier) < 10000) {
805
-		$b[$id] = $hier;
806
-	}
807
-
808
-	// Notre branche commence par la rubrique de depart si $tout=true
809
-	$hier = $tout ? (strlen($hier) ? "$hier,$id" : $id) : $hier;
810
-
811
-	return $hier;
773
+    static $b = [];
774
+
775
+    // normaliser $id qui a pu arriver comme un array, comme un entier, ou comme une chaine NN,NN,NN
776
+    if (!is_array($id)) {
777
+        $id = explode(',', $id);
778
+    }
779
+    $id = join(',', array_map('intval', $id));
780
+
781
+    if (isset($b[$id])) {
782
+        // Notre branche commence par la rubrique de depart si $tout=true
783
+        return $tout ? (strlen($b[$id]) ? $b[$id] . ",$id" : $id) : $b[$id];
784
+    }
785
+
786
+    $hier = '';
787
+
788
+    // On ajoute une generation (les filles de la generation precedente)
789
+    // jusqu'a epuisement, en se protegeant des references circulaires
790
+    $ids_nouveaux_parents = $id;
791
+    $maxiter = 10000;
792
+    while (
793
+        $maxiter-- && ($parents = sql_allfetsel(
794
+            'id_parent',
795
+            'spip_rubriques',
796
+            sql_in('id_rubrique', $ids_nouveaux_parents) . ' AND ' . sql_in('id_parent', $hier, 'NOT')
797
+        ))
798
+    ) {
799
+        $ids_nouveaux_parents = join(',', array_column($parents, 'id_parent'));
800
+        $hier = $ids_nouveaux_parents . (strlen($hier) ? ',' . $hier : '');
801
+    }
802
+
803
+    # securite pour ne pas plomber la conso memoire sur les sites prolifiques
804
+    if (strlen($hier) < 10000) {
805
+        $b[$id] = $hier;
806
+    }
807
+
808
+    // Notre branche commence par la rubrique de depart si $tout=true
809
+    $hier = $tout ? (strlen($hier) ? "$hier,$id" : $id) : $hier;
810
+
811
+    return $hier;
812 812
 }
813 813
 
814 814
 
@@ -826,47 +826,47 @@  discard block
 block discarded – undo
826 826
  * @return void
827 827
  **/
828 828
 function calculer_prochain_postdate($check = false) {
829
-	include_spip('base/abstract_sql');
830
-	if ($check) {
831
-		$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
832
-			'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
833
-
834
-		$r = sql_select(
835
-			'DISTINCT A.id_rubrique AS id',
836
-			'spip_articles AS A LEFT JOIN spip_rubriques AS R ON A.id_rubrique=R.id_rubrique',
837
-			"R.statut != 'publie' AND A.statut='publie'$postdates"
838
-		);
839
-		while ($row = sql_fetch($r)) {
840
-			publier_branche_rubrique($row['id']);
841
-		}
842
-
843
-		pipeline('trig_calculer_prochain_postdate', '');
844
-	}
845
-
846
-	$t = sql_fetsel(
847
-		'date',
848
-		'spip_articles',
849
-		"statut='publie' AND date > " . sql_quote(date('Y-m-d H:i:s')),
850
-		'',
851
-		'date',
852
-		'1'
853
-	);
854
-
855
-	if ($t) {
856
-		$t = $t['date'];
857
-		if (
858
-			!isset($GLOBALS['meta']['date_prochain_postdate'])
859
-			|| $t <> $GLOBALS['meta']['date_prochain_postdate']
860
-		) {
861
-			ecrire_meta('date_prochain_postdate', strtotime($t));
862
-			ecrire_meta('derniere_modif', time());
863
-		}
864
-	} else {
865
-		effacer_meta('date_prochain_postdate');
866
-		ecrire_meta('derniere_modif', time());
867
-	}
868
-
869
-	spip_log("prochain postdate: $t");
829
+    include_spip('base/abstract_sql');
830
+    if ($check) {
831
+        $postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
832
+            'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
833
+
834
+        $r = sql_select(
835
+            'DISTINCT A.id_rubrique AS id',
836
+            'spip_articles AS A LEFT JOIN spip_rubriques AS R ON A.id_rubrique=R.id_rubrique',
837
+            "R.statut != 'publie' AND A.statut='publie'$postdates"
838
+        );
839
+        while ($row = sql_fetch($r)) {
840
+            publier_branche_rubrique($row['id']);
841
+        }
842
+
843
+        pipeline('trig_calculer_prochain_postdate', '');
844
+    }
845
+
846
+    $t = sql_fetsel(
847
+        'date',
848
+        'spip_articles',
849
+        "statut='publie' AND date > " . sql_quote(date('Y-m-d H:i:s')),
850
+        '',
851
+        'date',
852
+        '1'
853
+    );
854
+
855
+    if ($t) {
856
+        $t = $t['date'];
857
+        if (
858
+            !isset($GLOBALS['meta']['date_prochain_postdate'])
859
+            || $t <> $GLOBALS['meta']['date_prochain_postdate']
860
+        ) {
861
+            ecrire_meta('date_prochain_postdate', strtotime($t));
862
+            ecrire_meta('derniere_modif', time());
863
+        }
864
+    } else {
865
+        effacer_meta('date_prochain_postdate');
866
+        ecrire_meta('derniere_modif', time());
867
+    }
868
+
869
+    spip_log("prochain postdate: $t");
870 870
 }
871 871
 
872 872
 /**
@@ -891,62 +891,62 @@  discard block
 block discarded – undo
891 891
  */
892 892
 function creer_rubrique_nommee($titre, $id_parent = 0, $serveur = '') {
893 893
 
894
-	// eclater l'arborescence demandee
895
-	// echapper les </multi> et autres balises fermantes html
896
-	$titre = preg_replace(',</([a-z][^>]*)>,ims', "<@\\1>", $titre);
897
-	$arbo = explode('/', preg_replace(',^/,', '', $titre));
898
-	include_spip('base/abstract_sql');
899
-	foreach ($arbo as $titre) {
900
-		// retablir les </multi> et autres balises fermantes html
901
-		$titre = preg_replace(',<@([a-z][^>]*)>,ims', "</\\1>", $titre);
902
-		$r = sql_getfetsel(
903
-			'id_rubrique',
904
-			'spip_rubriques',
905
-			'titre = ' . sql_quote($titre) . ' AND id_parent=' . intval($id_parent),
906
-			$groupby = [],
907
-			$orderby = [],
908
-			$limit = '',
909
-			$having = [],
910
-			$serveur
911
-		);
912
-		if ($r !== null) {
913
-			$id_parent = $r;
914
-		} else {
915
-			$id_rubrique = sql_insertq('spip_rubriques', [
916
-					'titre' => $titre,
917
-					'id_parent' => $id_parent,
918
-					'statut' => 'prepa'
919
-				], $desc = [], $serveur);
920
-			if ($id_parent > 0) {
921
-				$data = sql_fetsel(
922
-					'id_secteur,lang',
923
-					'spip_rubriques',
924
-					"id_rubrique=$id_parent",
925
-					$groupby = [],
926
-					$orderby = [],
927
-					$limit = '',
928
-					$having = [],
929
-					$serveur
930
-				);
931
-				$id_secteur = $data['id_secteur'];
932
-				$lang = $data['lang'];
933
-			} else {
934
-				$id_secteur = $id_rubrique;
935
-				$lang = $GLOBALS['meta']['langue_site'];
936
-			}
937
-
938
-			sql_updateq(
939
-				'spip_rubriques',
940
-				['id_secteur' => $id_secteur, 'lang' => $lang],
941
-				'id_rubrique=' . intval($id_rubrique),
942
-				[],
943
-				$serveur
944
-			);
945
-
946
-			// pour la recursion
947
-			$id_parent = $id_rubrique;
948
-		}
949
-	}
950
-
951
-	return intval($id_parent);
894
+    // eclater l'arborescence demandee
895
+    // echapper les </multi> et autres balises fermantes html
896
+    $titre = preg_replace(',</([a-z][^>]*)>,ims', "<@\\1>", $titre);
897
+    $arbo = explode('/', preg_replace(',^/,', '', $titre));
898
+    include_spip('base/abstract_sql');
899
+    foreach ($arbo as $titre) {
900
+        // retablir les </multi> et autres balises fermantes html
901
+        $titre = preg_replace(',<@([a-z][^>]*)>,ims', "</\\1>", $titre);
902
+        $r = sql_getfetsel(
903
+            'id_rubrique',
904
+            'spip_rubriques',
905
+            'titre = ' . sql_quote($titre) . ' AND id_parent=' . intval($id_parent),
906
+            $groupby = [],
907
+            $orderby = [],
908
+            $limit = '',
909
+            $having = [],
910
+            $serveur
911
+        );
912
+        if ($r !== null) {
913
+            $id_parent = $r;
914
+        } else {
915
+            $id_rubrique = sql_insertq('spip_rubriques', [
916
+                    'titre' => $titre,
917
+                    'id_parent' => $id_parent,
918
+                    'statut' => 'prepa'
919
+                ], $desc = [], $serveur);
920
+            if ($id_parent > 0) {
921
+                $data = sql_fetsel(
922
+                    'id_secteur,lang',
923
+                    'spip_rubriques',
924
+                    "id_rubrique=$id_parent",
925
+                    $groupby = [],
926
+                    $orderby = [],
927
+                    $limit = '',
928
+                    $having = [],
929
+                    $serveur
930
+                );
931
+                $id_secteur = $data['id_secteur'];
932
+                $lang = $data['lang'];
933
+            } else {
934
+                $id_secteur = $id_rubrique;
935
+                $lang = $GLOBALS['meta']['langue_site'];
936
+            }
937
+
938
+            sql_updateq(
939
+                'spip_rubriques',
940
+                ['id_secteur' => $id_secteur, 'lang' => $lang],
941
+                'id_rubrique=' . intval($id_rubrique),
942
+                [],
943
+                $serveur
944
+            );
945
+
946
+            // pour la recursion
947
+            $id_parent = $id_rubrique;
948
+        }
949
+    }
950
+
951
+    return intval($id_parent);
952 952
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 		sql_updateq(
136 136
 			'spip_rubriques',
137 137
 			['statut' => 'publie', 'date' => date('Y-m-d H:i:s')],
138
-			'id_rubrique=' . intval($id_rubrique)
138
+			'id_rubrique='.intval($id_rubrique)
139 139
 		);
140
-		$id_parent = sql_getfetsel('id_parent', 'spip_rubriques AS R', 'R.id_rubrique=' . intval($id_rubrique));
140
+		$id_parent = sql_getfetsel('id_parent', 'spip_rubriques AS R', 'R.id_rubrique='.intval($id_rubrique));
141 141
 		if (!$id_parent) {
142 142
 			break;
143 143
 		}
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 			return $id_pred != $id_rubrique;
173 173
 		}
174 174
 		// passer au parent si on a depublie
175
-		$r = sql_fetsel('id_parent', 'spip_rubriques', 'id_rubrique=' . intval($id_pred));
175
+		$r = sql_fetsel('id_parent', 'spip_rubriques', 'id_rubrique='.intval($id_pred));
176 176
 		$id_pred = $r['id_parent'];
177 177
 	}
178 178
 
@@ -197,14 +197,14 @@  discard block
 block discarded – undo
197 197
 		$date = date('Y-m-d H:i:s');
198 198
 	}
199 199
 	$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
200
-		' AND date <= ' . sql_quote($date) : '';
200
+		' AND date <= '.sql_quote($date) : '';
201 201
 
202 202
 	if (!$id_rubrique = intval($id_rubrique)) {
203 203
 		return false;
204 204
 	}
205 205
 
206 206
 	// verifier qu'elle existe et est bien publiee
207
-	$r = sql_fetsel('id_rubrique,statut', 'spip_rubriques', 'id_rubrique=' . intval($id_rubrique));
207
+	$r = sql_fetsel('id_rubrique,statut', 'spip_rubriques', 'id_rubrique='.intval($id_rubrique));
208 208
 	if (!$r || $r['statut'] !== 'publie') {
209 209
 		return false;
210 210
 	}
@@ -214,12 +214,12 @@  discard block
 block discarded – undo
214 214
 	$compte = [
215 215
 		'articles' => sql_countsel(
216 216
 			'spip_articles',
217
-			'id_rubrique=' . intval($id_rubrique) . " AND statut='publie'$postdates"
217
+			'id_rubrique='.intval($id_rubrique)." AND statut='publie'$postdates"
218 218
 		),
219
-		'rubriques' => sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique) . " AND statut='publie'"),
219
+		'rubriques' => sql_countsel('spip_rubriques', 'id_parent='.intval($id_rubrique)." AND statut='publie'"),
220 220
 		'documents' => sql_countsel(
221 221
 			'spip_documents AS D JOIN spip_documents_liens AS L ON D.id_document=L.id_document',
222
-			'L.id_objet=' . intval($id_rubrique) . " AND L.objet='rubrique' and D.mode NOT IN('logoon', 'logooff') "
222
+			'L.id_objet='.intval($id_rubrique)." AND L.objet='rubrique' and D.mode NOT IN('logoon', 'logooff') "
223 223
 		)
224 224
 	];
225 225
 
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 		}
245 245
 	}
246 246
 
247
-	sql_updateq('spip_rubriques', ['statut' => 'prepa'], 'id_rubrique=' . intval($id_rubrique));
247
+	sql_updateq('spip_rubriques', ['statut' => 'prepa'], 'id_rubrique='.intval($id_rubrique));
248 248
 
249 249
 #		spip_log("depublier_rubrique $id_pred");
250 250
 	return true;
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 
308 308
 	// Afficher les articles post-dates ?
309 309
 	$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
310
-		'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
310
+		'AND A.date <= '.sql_quote(date('Y-m-d H:i:s')) : '';
311 311
 
312 312
 	$r = sql_select(
313 313
 		'R.id_rubrique AS id, max(A.date) AS date_h',
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 		sql_updateq(
320 320
 			'spip_rubriques',
321 321
 			['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
322
-			'id_rubrique=' . intval($row['id'])
322
+			'id_rubrique='.intval($row['id'])
323 323
 		);
324 324
 	}
325 325
 
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 			sql_updateq(
346 346
 				'spip_rubriques',
347 347
 				['statut_tmp' => 'publie', 'date_tmp' => $row['date_h']],
348
-				'id_rubrique=' . intval($row['id'])
348
+				'id_rubrique='.intval($row['id'])
349 349
 			);
350 350
 			$continuer = true;
351 351
 		}
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 			&& ($rows = sql_allfetsel(
399 399
 				'A.id_rubrique AS id, R.id_secteur AS id_secteur, R.profondeur+1 as profondeur',
400 400
 				'spip_rubriques AS A JOIN spip_rubriques AS R ON A.id_parent = R.id_rubrique',
401
-				'R.profondeur=' . intval($prof) . ' AND (A.id_secteur <> R.id_secteur OR A.profondeur > R.profondeur+1)',
401
+				'R.profondeur='.intval($prof).' AND (A.id_secteur <> R.id_secteur OR A.profondeur > R.profondeur+1)',
402 402
 				'',
403 403
 				'R.id_secteur',
404 404
 				'0,100'
@@ -437,11 +437,11 @@  discard block
 block discarded – undo
437 437
 			&& ($rows = sql_allfetsel(
438 438
 				'id_rubrique as id',
439 439
 				'spip_rubriques',
440
-				'profondeur=' . intval($prof + 1) . ' AND id_parent NOT IN (' . sql_get_select(
440
+				'profondeur='.intval($prof + 1).' AND id_parent NOT IN ('.sql_get_select(
441 441
 					'zzz.id_rubrique',
442 442
 					'spip_rubriques AS zzz',
443
-					'zzz.profondeur=' . intval($prof)
444
-				) . ')',
443
+					'zzz.profondeur='.intval($prof)
444
+				).')',
445 445
 				'',
446 446
 				'',
447 447
 				'0,100'
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 		// si pas de rubrique a profondeur $prof+1 pas la peine de continuer
456 456
 		// si il reste des rubriques non vues, c'est une branche morte ou reference circulaire (base foireuse)
457 457
 		// on arrete les frais
458
-		if (sql_countsel('spip_rubriques', 'profondeur=' . intval($prof + 1))) {
458
+		if (sql_countsel('spip_rubriques', 'profondeur='.intval($prof + 1))) {
459 459
 			$prof++;
460 460
 			$continuer = true;
461 461
 		}
@@ -463,12 +463,12 @@  discard block
 block discarded – undo
463 463
 
464 464
 	// loger si la table des rubriques semble foireuse
465 465
 	// et mettre un id_secteur=0 sur ces rubriques pour eviter toute selection par les boucles
466
-	if (sql_countsel('spip_rubriques', 'profondeur>' . intval($prof + 1))) {
466
+	if (sql_countsel('spip_rubriques', 'profondeur>'.intval($prof + 1))) {
467 467
 		spip_log(
468
-			'Les rubriques de profondeur>' . ($prof + 1) . ' semblent suspectes (branches morte ou reference circulaire dans les parents)',
468
+			'Les rubriques de profondeur>'.($prof + 1).' semblent suspectes (branches morte ou reference circulaire dans les parents)',
469 469
 			_LOG_CRITIQUE
470 470
 		);
471
-		sql_update('spip_rubriques', ['id_secteur' => 0], 'profondeur>' . intval($prof + 1));
471
+		sql_update('spip_rubriques', ['id_secteur' => 0], 'profondeur>'.intval($prof + 1));
472 472
 	}
473 473
 
474 474
 	// reparer les articles
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 	);
480 480
 
481 481
 	while ($row = sql_fetch($r)) {
482
-		sql_update('spip_articles', ['id_secteur' => $row['secteur']], 'id_article=' . intval($row['id']));
482
+		sql_update('spip_articles', ['id_secteur' => $row['secteur']], 'id_article='.intval($row['id']));
483 483
 	}
484 484
 
485 485
 	// avertir les plugins qui peuvent faire leur mises a jour egalement
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		$t = sql_updateq(
511 511
 			'spip_rubriques',
512 512
 			['lang' => $row['lang'], 'langue_choisie' => 'non'],
513
-			'id_rubrique=' . intval($id_rubrique)
513
+			'id_rubrique='.intval($id_rubrique)
514 514
 		);
515 515
 	}
516 516
 
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 		sql_updateq(
556 556
 			'spip_articles',
557 557
 			['lang' => $row['lang'], 'langue_choisie' => 'non'],
558
-			'id_article=' . intval($id_article)
558
+			'id_article='.intval($id_article)
559 559
 		);
560 560
 	}
561 561
 
@@ -630,11 +630,11 @@  discard block
 block discarded – undo
630 630
 				];
631 631
 				// generer un nom de fonction "anonyme" unique
632 632
 				do {
633
-					$functionname = 'f_calculer_langues_utilisees_' . $boucle->id_table . '_' . time() . '_' . random_int(0, mt_getrandmax());
633
+					$functionname = 'f_calculer_langues_utilisees_'.$boucle->id_table.'_'.time().'_'.random_int(0, mt_getrandmax());
634 634
 				} while (function_exists($functionname));
635 635
 				$code = calculer_boucle('calculer_langues_utilisees', $boucles);
636
-				$code = '$SP=0; $command=array();$command["connect"] = $connect = "' . $serveur . '"; $Pile=array(0=>array());' . "\n" . $code;
637
-				$code = 'function ' . $functionname . '(){' . $code . '};$res = ' . $functionname . '();';
636
+				$code = '$SP=0; $command=array();$command["connect"] = $connect = "'.$serveur.'"; $Pile=array(0=>array());'."\n".$code;
637
+				$code = 'function '.$functionname.'(){'.$code.'};$res = '.$functionname.'();';
638 638
 				$res = '';
639 639
 				eval($code);
640 640
 				$res = explode(',', $res);
@@ -736,11 +736,11 @@  discard block
 block discarded – undo
736 736
 		$maxiter-- && ($filles = sql_allfetsel(
737 737
 			'id_rubrique',
738 738
 			'spip_rubriques',
739
-			sql_in('id_parent', $r) . ' AND ' . sql_in('id_rubrique', $r, 'NOT')
739
+			sql_in('id_parent', $r).' AND '.sql_in('id_rubrique', $r, 'NOT')
740 740
 		))
741 741
 	) {
742 742
 		$r = join(',', array_column($filles, 'id_rubrique'));
743
-		$branche .= ',' . $r;
743
+		$branche .= ','.$r;
744 744
 	}
745 745
 
746 746
 	# securite pour ne pas plomber la conso memoire sur les sites prolifiques
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 
781 781
 	if (isset($b[$id])) {
782 782
 		// Notre branche commence par la rubrique de depart si $tout=true
783
-		return $tout ? (strlen($b[$id]) ? $b[$id] . ",$id" : $id) : $b[$id];
783
+		return $tout ? (strlen($b[$id]) ? $b[$id].",$id" : $id) : $b[$id];
784 784
 	}
785 785
 
786 786
 	$hier = '';
@@ -793,11 +793,11 @@  discard block
 block discarded – undo
793 793
 		$maxiter-- && ($parents = sql_allfetsel(
794 794
 			'id_parent',
795 795
 			'spip_rubriques',
796
-			sql_in('id_rubrique', $ids_nouveaux_parents) . ' AND ' . sql_in('id_parent', $hier, 'NOT')
796
+			sql_in('id_rubrique', $ids_nouveaux_parents).' AND '.sql_in('id_parent', $hier, 'NOT')
797 797
 		))
798 798
 	) {
799 799
 		$ids_nouveaux_parents = join(',', array_column($parents, 'id_parent'));
800
-		$hier = $ids_nouveaux_parents . (strlen($hier) ? ',' . $hier : '');
800
+		$hier = $ids_nouveaux_parents.(strlen($hier) ? ','.$hier : '');
801 801
 	}
802 802
 
803 803
 	# securite pour ne pas plomber la conso memoire sur les sites prolifiques
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
 	include_spip('base/abstract_sql');
830 830
 	if ($check) {
831 831
 		$postdates = ($GLOBALS['meta']['post_dates'] == 'non') ?
832
-			'AND A.date <= ' . sql_quote(date('Y-m-d H:i:s')) : '';
832
+			'AND A.date <= '.sql_quote(date('Y-m-d H:i:s')) : '';
833 833
 
834 834
 		$r = sql_select(
835 835
 			'DISTINCT A.id_rubrique AS id',
@@ -846,7 +846,7 @@  discard block
 block discarded – undo
846 846
 	$t = sql_fetsel(
847 847
 		'date',
848 848
 		'spip_articles',
849
-		"statut='publie' AND date > " . sql_quote(date('Y-m-d H:i:s')),
849
+		"statut='publie' AND date > ".sql_quote(date('Y-m-d H:i:s')),
850 850
 		'',
851 851
 		'date',
852 852
 		'1'
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 		$r = sql_getfetsel(
903 903
 			'id_rubrique',
904 904
 			'spip_rubriques',
905
-			'titre = ' . sql_quote($titre) . ' AND id_parent=' . intval($id_parent),
905
+			'titre = '.sql_quote($titre).' AND id_parent='.intval($id_parent),
906 906
 			$groupby = [],
907 907
 			$orderby = [],
908 908
 			$limit = '',
@@ -938,7 +938,7 @@  discard block
 block discarded – undo
938 938
 			sql_updateq(
939 939
 				'spip_rubriques',
940 940
 				['id_secteur' => $id_secteur, 'lang' => $lang],
941
-				'id_rubrique=' . intval($id_rubrique),
941
+				'id_rubrique='.intval($id_rubrique),
942 942
 				[],
943 943
 				$serveur
944 944
 			);
Please login to merge, or discard this patch.
ecrire/inc/texte_mini.php 3 patches
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -49,13 +49,13 @@  discard block
 block discarded – undo
49 49
 	// celle du texte) et public (spip_lang est la langue du texte)
50 50
 	$dir = _DIR_RESTREINT ? lang_dir() : lang_dir($GLOBALS['spip_lang']);
51 51
 
52
-	$p = 'puce' . (test_espace_prive() ? '_prive' : '');
52
+	$p = 'puce'.(test_espace_prive() ? '_prive' : '');
53 53
 	if ($dir == 'rtl') {
54 54
 		$p .= '_rtl';
55 55
 	}
56 56
 
57 57
 	if (!isset($GLOBALS[$p])) {
58
-		$GLOBALS[$p] = '<span class="spip-puce ' . $dir . '"><b>–</b></span>';
58
+		$GLOBALS[$p] = '<span class="spip-puce '.$dir.'"><b>–</b></span>';
59 59
 	}
60 60
 
61 61
 	return $GLOBALS[$p];
@@ -67,13 +67,13 @@  discard block
 block discarded – undo
67 67
 function spip_balisage_code(string $corps, bool $bloc = false, string $attributs = '', string $langage = ''): string {
68 68
 
69 69
 	$echap = spip_htmlspecialchars($corps); // il ne faut pas passer dans entites_html, ne pas transformer les &#xxx; du code !
70
-	$class = 'spip_code ' . ($bloc ? 'spip_code_block' : 'spip_code_inline');
70
+	$class = 'spip_code '.($bloc ? 'spip_code_block' : 'spip_code_inline');
71 71
 	if ($attributs) {
72
-		$attributs = ' ' . trim($attributs);
72
+		$attributs = ' '.trim($attributs);
73 73
 	}
74 74
 	if ($langage) {
75 75
 		$class .= " language-$langage";
76
-		$attributs .= ' data-language="' . $langage . '"';
76
+		$attributs .= ' data-language="'.$langage.'"';
77 77
 	}
78 78
 	if ($bloc) {
79 79
 		$html = '<div class="precode">'
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	} else {
87 87
 		$echap = str_replace("\t", '&nbsp; &nbsp; &nbsp; &nbsp; ', $echap);
88 88
 		$echap = str_replace('  ', ' &nbsp;', $echap);
89
-		$html = "<code class=\"$class\" dir=\"ltr\"$attributs>" . $echap . '</code>';
89
+		$html = "<code class=\"$class\" dir=\"ltr\"$attributs>".$echap.'</code>';
90 90
 	}
91 91
 
92 92
 	return $html;
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 // XHTML - Preserver les balises-bloc : on liste ici tous les elements
97 97
 // dont on souhaite qu'ils provoquent un saut de paragraphe
98 98
 defined('_BALISES_BLOCS') || define('_BALISES_BLOCS', implode('|', CollecteurHtmlTag::$listeBalisesBloc));
99
-defined('_BALISES_BLOCS_REGEXP') || define('_BALISES_BLOCS_REGEXP', ',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS');
99
+defined('_BALISES_BLOCS_REGEXP') || define('_BALISES_BLOCS_REGEXP', ',</?('._BALISES_BLOCS.')[>[:space:]],iS');
100 100
 
101 101
 /**
102 102
  * Echapper les elements perilleux en les passant en base64
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 		return '';
117 117
 	}
118 118
 
119
-	return CollecteurHtmlTag::echappementHtmlBase64((string)$rempl, (string)$source, in_array($mode, ['div', 'span']) ? $mode === 'div' : null);
119
+	return CollecteurHtmlTag::echappementHtmlBase64((string) $rempl, (string) $source, in_array($mode, ['div', 'span']) ? $mode === 'div' : null);
120 120
 }
121 121
 
122 122
 
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 		$collections = $collecteurCode->collecter($pre);
137 137
 		$collections = array_reverse($collections);
138 138
 		foreach ($collections as $c) {
139
-			$code = $c['opening'] . spip_htmlspecialchars($c['innerHtml']) . $c['closing'];
139
+			$code = $c['opening'].spip_htmlspecialchars($c['innerHtml']).$c['closing'];
140 140
 			$pre = substr_replace($pre, $code, $c['pos'], $c['length']);
141 141
 		}
142 142
 	}
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	return $regs['raw'];
192 192
 }
193 193
 
194
-defined('_PROTEGE_BLOCS') || define('_PROTEGE_BLOCS', ',<(' . implode('|', CollecteurHtmlTag::$listeBalisesAProteger) . ')(\b[^>]*)?>(.*)</\1>,UimsS');
194
+defined('_PROTEGE_BLOCS') || define('_PROTEGE_BLOCS', ',<('.implode('|', CollecteurHtmlTag::$listeBalisesAProteger).')(\b[^>]*)?>(.*)</\1>,UimsS');
195 195
 
196 196
 /**
197 197
  * pour $source voir commentaire infra (echappe_retour)
@@ -242,11 +242,11 @@  discard block
 block discarded – undo
242 242
 		$callback_secure_prefix = ($callback_options['secure_prefix'] ?? '');
243 243
 		foreach ($html_tags ?: CollecteurHtmlTag::$listeBalisesAProteger as $tag) {
244 244
 			if (
245
-				function_exists($f = $callback_prefix . $callback_secure_prefix . 'traiter_echap_' . $tag)
246
-				|| function_exists($f = $f . '_dist')
245
+				function_exists($f = $callback_prefix.$callback_secure_prefix.'traiter_echap_'.$tag)
246
+				|| function_exists($f = $f.'_dist')
247 247
 				|| $callback_secure_prefix && (
248
-					function_exists($f = $callback_prefix . 'traiter_echap_' . $tag)
249
-					|| function_exists($f = $f . '_dist')
248
+					function_exists($f = $callback_prefix.'traiter_echap_'.$tag)
249
+					|| function_exists($f = $f.'_dist')
250 250
 				)
251 251
 			) {
252 252
 				$callbacks[$tag] = $f;
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 	if (!is_string($letexte) || !strlen($letexte)) {
287 287
 		return $letexte;
288 288
 	}
289
-	return CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte, (string)$source, (string)$filtre);
289
+	return CollecteurHtmlTag::retablir_depuisHtmlBase64((string) $letexte, (string) $source, (string) $filtre);
290 290
 }
291 291
 
292 292
 // Reinserer le javascript de confiance (venant des modeles)
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
 	if (!is_string($letexte) || !strlen($letexte)) {
296 296
 		return $letexte;
297 297
 	}
298
-	$letexte = CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte);
298
+	$letexte = CollecteurHtmlTag::retablir_depuisHtmlBase64((string) $letexte);
299 299
 
300 300
 	// Dans les appels directs hors squelette, securiser aussi ici
301 301
 	// c'est interdire_scripts() qui rétablit les scripts des modeles echappés avec _PROTEGE_JS_MODELES et _PROTEGE_PHP_MODELES
@@ -364,8 +364,8 @@  discard block
 block discarded – undo
364 364
 	$texte = nettoyer_raccourcis_typo($texte);
365 365
 
366 366
 	// balises de sauts de ligne et paragraphe
367
-	$texte = preg_replace('/<p( [^>]*)?' . '>/', "\r\r", $texte);
368
-	$texte = preg_replace('/<br( [^>]*)?' . '>/', "\n", $texte);
367
+	$texte = preg_replace('/<p( [^>]*)?'.'>/', "\r\r", $texte);
368
+	$texte = preg_replace('/<br( [^>]*)?'.'>/', "\n", $texte);
369 369
 
370 370
 	// on repasse les doubles \n en \r que nettoyer_raccourcis_typo() a pu modifier
371 371
 	$texte = str_replace("\n\n", "\r\r", $texte);
@@ -390,15 +390,15 @@  discard block
 block discarded – undo
390 390
 		// excédentaire est ensuite supprimé par l'appel à preg_replace()
391 391
 		$long = spip_substr($texte, 0, max($taille + 1 - $taille_suite, 1));
392 392
 		$u = $GLOBALS['meta']['pcre_u'];
393
-		$court = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
393
+		$court = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D'.$u, "\\2", $long);
394 394
 		$points = $suite;
395 395
 
396 396
 		// trop court ? ne pas faire de (...)
397 397
 		if (spip_strlen($court) < max(0.75 * $taille, 2)) {
398 398
 			$points = '';
399 399
 			$long = spip_substr($texte, 0, $taille + 1);
400
-			preg_match('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, $long, $m);
401
-			$texte = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
400
+			preg_match('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D'.$u, $long, $m);
401
+			$texte = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D'.$u, "\\2", $long);
402 402
 			// encore trop court ? couper au caractere
403 403
 			if (spip_strlen($texte) < 0.75 * $taille) {
404 404
 				$texte = spip_substr($long, 0, $taille);
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 	// supprimer l'eventuelle entite finale mal coupee
415 415
 	$texte = preg_replace('/&#?[a-z0-9]*$/S', '', $texte);
416 416
 
417
-	return quote_amp(trim($texte)) . $points;
417
+	return quote_amp(trim($texte)).$points;
418 418
 }
419 419
 
420 420
 
@@ -422,16 +422,16 @@  discard block
 block discarded – undo
422 422
 	if (isset($GLOBALS['visiteur_session']) && str_contains($texte, '<')) {
423 423
 		$tags = [
424 424
 			'javascript' => ['tag' => 'script', 'preg' => ',<script.*?($|</script.),isS', 'c' => '_PROTEGE_JS_MODELES'],
425
-			'php' => ['tag' => '?php', 'preg' => ',<\?php.*?($|\?' . '>),isS', 'c' => '_PROTEGE_PHP_MODELES'],
425
+			'php' => ['tag' => '?php', 'preg' => ',<\?php.*?($|\?'.'>),isS', 'c' => '_PROTEGE_PHP_MODELES'],
426 426
 		];
427 427
 		foreach ($tags as $k => $t) {
428
-			if (stripos($texte, '<' . $t['tag']) !== false) {
428
+			if (stripos($texte, '<'.$t['tag']) !== false) {
429 429
 				if (!defined($t['c'])) {
430 430
 					include_spip('inc/acces');
431 431
 					define($t['c'], creer_uniqid());
432 432
 				}
433 433
 				$collecteurHtmlTag = new CollecteurHtmlTag($t['tag'], $t['preg'], '');
434
-				$texte = $collecteurHtmlTag->echapper_enHtmlBase64($texte, $k . constant($t['c']));
434
+				$texte = $collecteurHtmlTag->echapper_enHtmlBase64($texte, $k.constant($t['c']));
435 435
 			}
436 436
 		}
437 437
 	}
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 			if (!empty($options['wrap_suspect'])) {
545 545
 				$texte = wrap($texte, $options['wrap_suspect']);
546 546
 			}
547
-			$texte = "<mark class='danger-js' title='" . attribut_html(_T('erreur_contenu_suspect')) . "'>⚠️</mark> " . $texte;
547
+			$texte = "<mark class='danger-js' title='".attribut_html(_T('erreur_contenu_suspect'))."'>⚠️</mark> ".$texte;
548 548
 		}
549 549
 
550 550
 		$texte = $collecteurModeles->retablir($texte);
@@ -687,11 +687,11 @@  discard block
 block discarded – undo
687 687
  **/
688 688
 function supprime_img($letexte, $message = null) {
689 689
 	if ($message === null) {
690
-		$message = '(' . _T('img_indisponible') . ')';
690
+		$message = '('._T('img_indisponible').')';
691 691
 	}
692 692
 
693 693
 	return preg_replace(
694
-		',<(img|doc|emb)([0-9]+)(\|([^>]*))?' . '\s*/?' . '>,i',
694
+		',<(img|doc|emb)([0-9]+)(\|([^>]*))?'.'\s*/?'.'>,i',
695 695
 		$message,
696 696
 		$letexte
697 697
 	);
Please login to merge, or discard this patch.
Indentation   +454 added lines, -454 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
  **/
23 23
 
24 24
 if (!defined('_ECRIRE_INC_VERSION')) {
25
-	return;
25
+    return;
26 26
 }
27 27
 include_spip('inc/filtres');
28 28
 include_spip('inc/lang');
@@ -44,21 +44,21 @@  discard block
 block discarded – undo
44 44
  **/
45 45
 function definir_puce() {
46 46
 
47
-	// Attention au sens, qui n'est pas defini de la meme facon dans
48
-	// l'espace prive (spip_lang est la langue de l'interface, lang_dir
49
-	// celle du texte) et public (spip_lang est la langue du texte)
50
-	$dir = _DIR_RESTREINT ? lang_dir() : lang_dir($GLOBALS['spip_lang']);
47
+    // Attention au sens, qui n'est pas defini de la meme facon dans
48
+    // l'espace prive (spip_lang est la langue de l'interface, lang_dir
49
+    // celle du texte) et public (spip_lang est la langue du texte)
50
+    $dir = _DIR_RESTREINT ? lang_dir() : lang_dir($GLOBALS['spip_lang']);
51 51
 
52
-	$p = 'puce' . (test_espace_prive() ? '_prive' : '');
53
-	if ($dir == 'rtl') {
54
-		$p .= '_rtl';
55
-	}
52
+    $p = 'puce' . (test_espace_prive() ? '_prive' : '');
53
+    if ($dir == 'rtl') {
54
+        $p .= '_rtl';
55
+    }
56 56
 
57
-	if (!isset($GLOBALS[$p])) {
58
-		$GLOBALS[$p] = '<span class="spip-puce ' . $dir . '"><b>–</b></span>';
59
-	}
57
+    if (!isset($GLOBALS[$p])) {
58
+        $GLOBALS[$p] = '<span class="spip-puce ' . $dir . '"><b>–</b></span>';
59
+    }
60 60
 
61
-	return $GLOBALS[$p];
61
+    return $GLOBALS[$p];
62 62
 }
63 63
 
64 64
 /**
@@ -66,30 +66,30 @@  discard block
 block discarded – undo
66 66
  */
67 67
 function spip_balisage_code(string $corps, bool $bloc = false, string $attributs = '', string $langage = ''): string {
68 68
 
69
-	$echap = spip_htmlspecialchars($corps); // il ne faut pas passer dans entites_html, ne pas transformer les &#xxx; du code !
70
-	$class = 'spip_code ' . ($bloc ? 'spip_code_block' : 'spip_code_inline');
71
-	if ($attributs) {
72
-		$attributs = ' ' . trim($attributs);
73
-	}
74
-	if ($langage) {
75
-		$class .= " language-$langage";
76
-		$attributs .= ' data-language="' . $langage . '"';
77
-	}
78
-	if ($bloc) {
79
-		$html = '<div class="precode">'
80
-		  . "<pre class=\"$class\" dir=\"ltr\" style=\"text-align: left;\"$attributs>"
81
-		  . '<code>'
82
-		  . $echap
83
-		  . '</code>'
84
-		  . '</pre>'
85
-		  . '</div>';
86
-	} else {
87
-		$echap = str_replace("\t", '&nbsp; &nbsp; &nbsp; &nbsp; ', $echap);
88
-		$echap = str_replace('  ', ' &nbsp;', $echap);
89
-		$html = "<code class=\"$class\" dir=\"ltr\"$attributs>" . $echap . '</code>';
90
-	}
91
-
92
-	return $html;
69
+    $echap = spip_htmlspecialchars($corps); // il ne faut pas passer dans entites_html, ne pas transformer les &#xxx; du code !
70
+    $class = 'spip_code ' . ($bloc ? 'spip_code_block' : 'spip_code_inline');
71
+    if ($attributs) {
72
+        $attributs = ' ' . trim($attributs);
73
+    }
74
+    if ($langage) {
75
+        $class .= " language-$langage";
76
+        $attributs .= ' data-language="' . $langage . '"';
77
+    }
78
+    if ($bloc) {
79
+        $html = '<div class="precode">'
80
+            . "<pre class=\"$class\" dir=\"ltr\" style=\"text-align: left;\"$attributs>"
81
+            . '<code>'
82
+            . $echap
83
+            . '</code>'
84
+            . '</pre>'
85
+            . '</div>';
86
+    } else {
87
+        $echap = str_replace("\t", '&nbsp; &nbsp; &nbsp; &nbsp; ', $echap);
88
+        $echap = str_replace('  ', ' &nbsp;', $echap);
89
+        $html = "<code class=\"$class\" dir=\"ltr\"$attributs>" . $echap . '</code>';
90
+    }
91
+
92
+    return $html;
93 93
 }
94 94
 
95 95
 
@@ -112,83 +112,83 @@  discard block
 block discarded – undo
112 112
  * @return string
113 113
  */
114 114
 function code_echappement($rempl, $source = '', $no_transform = false, $mode = null) {
115
-	if (!is_string($rempl) || !strlen($rempl)) {
116
-		return '';
117
-	}
115
+    if (!is_string($rempl) || !strlen($rempl)) {
116
+        return '';
117
+    }
118 118
 
119
-	return CollecteurHtmlTag::echappementHtmlBase64((string)$rempl, (string)$source, in_array($mode, ['div', 'span']) ? $mode === 'div' : null);
119
+    return CollecteurHtmlTag::echappementHtmlBase64((string)$rempl, (string)$source, in_array($mode, ['div', 'span']) ? $mode === 'div' : null);
120 120
 }
121 121
 
122 122
 
123 123
 // Echapper les <html>...</ html>
124 124
 function traiter_echap_html_dist($regs, $options = []) {
125
-	return $regs['innerHtml'];
125
+    return $regs['innerHtml'];
126 126
 }
127 127
 
128 128
 // Echapper les <pre>...</ pre>
129 129
 function traiter_echap_pre_dist($regs, $options = []) {
130
-	// echapper les <code> dans <pre>
131
-	$pre = $regs['innerHtml'];
132
-
133
-	// echapper les < dans <code>
134
-	if (str_contains($pre, '<')) {
135
-		$collecteurCode = new CollecteurHtmlTag('code');
136
-		$collections = $collecteurCode->collecter($pre);
137
-		$collections = array_reverse($collections);
138
-		foreach ($collections as $c) {
139
-			$code = $c['opening'] . spip_htmlspecialchars($c['innerHtml']) . $c['closing'];
140
-			$pre = substr_replace($pre, $code, $c['pos'], $c['length']);
141
-		}
142
-	}
143
-	return "<pre>$pre</pre>";
130
+    // echapper les <code> dans <pre>
131
+    $pre = $regs['innerHtml'];
132
+
133
+    // echapper les < dans <code>
134
+    if (str_contains($pre, '<')) {
135
+        $collecteurCode = new CollecteurHtmlTag('code');
136
+        $collections = $collecteurCode->collecter($pre);
137
+        $collections = array_reverse($collections);
138
+        foreach ($collections as $c) {
139
+            $code = $c['opening'] . spip_htmlspecialchars($c['innerHtml']) . $c['closing'];
140
+            $pre = substr_replace($pre, $code, $c['pos'], $c['length']);
141
+        }
142
+    }
143
+    return "<pre>$pre</pre>";
144 144
 }
145 145
 
146 146
 // Echapper les <code>...</ code>
147 147
 function traiter_echap_code_dist($regs, $options = []) {
148
-	$corps = $regs['innerHtml'];
149
-	$att = $regs['attributs'];
148
+    $corps = $regs['innerHtml'];
149
+    $att = $regs['attributs'];
150 150
 
151
-	// ne pas mettre le <div...> s'il n'y a qu'une ligne
152
-	if (str_contains($corps, "\n")) {
153
-		// supprimer les sauts de ligne debut/fin
154
-		// (mais pas les espaces => ascii art).
155
-		$corps = preg_replace("/^[\n\r]+|[\n\r]+$/s", '', $corps);
151
+    // ne pas mettre le <div...> s'il n'y a qu'une ligne
152
+    if (str_contains($corps, "\n")) {
153
+        // supprimer les sauts de ligne debut/fin
154
+        // (mais pas les espaces => ascii art).
155
+        $corps = preg_replace("/^[\n\r]+|[\n\r]+$/s", '', $corps);
156 156
 
157
-		$echap = spip_balisage_code($corps, true, $att);
158
-	} else {
159
-		$echap = spip_balisage_code($corps, false, $att);
160
-	}
157
+        $echap = spip_balisage_code($corps, true, $att);
158
+    } else {
159
+        $echap = spip_balisage_code($corps, false, $att);
160
+    }
161 161
 
162
-	return $echap;
162
+    return $echap;
163 163
 }
164 164
 
165 165
 // Echapper les <cadre>...</ cadre> aka <frame>...</ frame>
166 166
 function traiter_echap_cadre_dist($regs, $options = []) {
167
-	$echap = trim(entites_html($regs['innerHtml']));
168
-	// compter les lignes un peu plus finement qu'avec les \n
169
-	$lignes = explode("\n", trim($echap));
170
-	$n = 0;
171
-	foreach ($lignes as $l) {
172
-		$n += floor(strlen($l) / 60) + 1;
173
-	}
174
-	$n = max($n, 2);
175
-	$echap = "\n<textarea readonly='readonly' cols='40' rows='$n' class='spip_cadre spip_cadre_block' dir='ltr'>$echap</textarea>";
176
-
177
-	return $echap;
167
+    $echap = trim(entites_html($regs['innerHtml']));
168
+    // compter les lignes un peu plus finement qu'avec les \n
169
+    $lignes = explode("\n", trim($echap));
170
+    $n = 0;
171
+    foreach ($lignes as $l) {
172
+        $n += floor(strlen($l) / 60) + 1;
173
+    }
174
+    $n = max($n, 2);
175
+    $echap = "\n<textarea readonly='readonly' cols='40' rows='$n' class='spip_cadre spip_cadre_block' dir='ltr'>$echap</textarea>";
176
+
177
+    return $echap;
178 178
 }
179 179
 
180 180
 function traiter_echap_frame_dist($regs, $options = []) {
181
-	return traiter_echap_cadre_dist($regs);
181
+    return traiter_echap_cadre_dist($regs);
182 182
 }
183 183
 
184 184
 function traiter_echap_script_dist($regs, $options = []) {
185
-	// rendre joli (et inactif) si c'est un script language=php
186
-	if (strpos($regs['opening'], 'php')) {
187
-		return highlight_string($regs['raw'], true);
188
-	}
185
+    // rendre joli (et inactif) si c'est un script language=php
186
+    if (strpos($regs['opening'], 'php')) {
187
+        return highlight_string($regs['raw'], true);
188
+    }
189 189
 
190
-	// Cas normal : le script passe tel quel
191
-	return $regs['raw'];
190
+    // Cas normal : le script passe tel quel
191
+    return $regs['raw'];
192 192
 }
193 193
 
194 194
 defined('_PROTEGE_BLOCS') || define('_PROTEGE_BLOCS', ',<(' . implode('|', CollecteurHtmlTag::$listeBalisesAProteger) . ')(\b[^>]*)?>(.*)</\1>,UimsS');
@@ -207,69 +207,69 @@  discard block
 block discarded – undo
207 207
  * @return string|string[]
208 208
  */
209 209
 function echappe_html(
210
-	$letexte,
211
-	$source = '',
212
-	$no_transform = false,
213
-	$html_tags = null,
214
-	$callback_prefix = '',
215
-	$callback_options = []
210
+    $letexte,
211
+    $source = '',
212
+    $no_transform = false,
213
+    $html_tags = null,
214
+    $callback_prefix = '',
215
+    $callback_options = []
216 216
 ) {
217
-	if (!is_string($letexte) || !strlen($letexte)) {
218
-		return $letexte;
219
-	}
220
-
221
-	if ($no_transform !== false) {
222
-		trigger_deprecation('spip', '5.0', 'Using "%s" arg is deprecated, use directly "%s" instead.', '$no_transform', 'Spip\Texte\Collecteur\HtmlTag::proteger_balisesHtml', __FUNCTION__);
223
-	}
224
-
225
-	// appels legacy avec un ''
226
-	if (empty($html_tags)) {
227
-		$html_tags = null;
228
-	}
229
-
230
-	// legacy : les appels fournissaient une preg pour repérer les balises HTML
231
-	if ($html_tags && !is_array($html_tags)) {
232
-		trigger_deprecation('spip', '5.0', 'Using a preg for "%s" arg is deprecated, use a tag array instead.', '$html_tags', __FUNCTION__);
233
-		$t = explode(')', $html_tags, 2);
234
-		$t = reset($t);
235
-		$t = explode('(', $t, 2);
236
-		$t = end($t);
237
-		$html_tags = explode('|', $t);
238
-	}
239
-
240
-	$callbacks = [];
241
-	if (!$no_transform) {
242
-		$callback_secure_prefix = ($callback_options['secure_prefix'] ?? '');
243
-		foreach ($html_tags ?: CollecteurHtmlTag::$listeBalisesAProteger as $tag) {
244
-			if (
245
-				function_exists($f = $callback_prefix . $callback_secure_prefix . 'traiter_echap_' . $tag)
246
-				|| function_exists($f = $f . '_dist')
247
-				|| $callback_secure_prefix && (
248
-					function_exists($f = $callback_prefix . 'traiter_echap_' . $tag)
249
-					|| function_exists($f = $f . '_dist')
250
-				)
251
-			) {
252
-				$callbacks[$tag] = $f;
253
-			}
254
-		}
255
-	}
256
-
257
-	$letexte = CollecteurHtmlTag::proteger_balisesHtml($letexte, $source, $html_tags, $callbacks, $callback_options);
258
-
259
-	if ($no_transform) {
260
-		return $letexte;
261
-	}
262
-
263
-	// Echapper le php pour faire joli (ici, c'est pas pour la securite)
264
-	// seulement si on a echappe les <script>
265
-	// (derogatoire car on ne peut pas faire passer < ? ... ? >
266
-	// dans une callback autonommee + la preg pour collecter est un peu spécifique
267
-	if (in_array('script', $html_tags ?: CollecteurHtmlTag::$listeBalisesAProteger)) {
268
-		$htmlTagCollecteur = new CollecteurHtmlTag('?', '@<[?].*($|[?]>)@UsS', '');
269
-		$letexte = $htmlTagCollecteur->echapper_enHtmlBase64($letexte, $source, fn ($c, $o) => highlight_string($c['raw'], true));
270
-	}
271
-
272
-	return $letexte;
217
+    if (!is_string($letexte) || !strlen($letexte)) {
218
+        return $letexte;
219
+    }
220
+
221
+    if ($no_transform !== false) {
222
+        trigger_deprecation('spip', '5.0', 'Using "%s" arg is deprecated, use directly "%s" instead.', '$no_transform', 'Spip\Texte\Collecteur\HtmlTag::proteger_balisesHtml', __FUNCTION__);
223
+    }
224
+
225
+    // appels legacy avec un ''
226
+    if (empty($html_tags)) {
227
+        $html_tags = null;
228
+    }
229
+
230
+    // legacy : les appels fournissaient une preg pour repérer les balises HTML
231
+    if ($html_tags && !is_array($html_tags)) {
232
+        trigger_deprecation('spip', '5.0', 'Using a preg for "%s" arg is deprecated, use a tag array instead.', '$html_tags', __FUNCTION__);
233
+        $t = explode(')', $html_tags, 2);
234
+        $t = reset($t);
235
+        $t = explode('(', $t, 2);
236
+        $t = end($t);
237
+        $html_tags = explode('|', $t);
238
+    }
239
+
240
+    $callbacks = [];
241
+    if (!$no_transform) {
242
+        $callback_secure_prefix = ($callback_options['secure_prefix'] ?? '');
243
+        foreach ($html_tags ?: CollecteurHtmlTag::$listeBalisesAProteger as $tag) {
244
+            if (
245
+                function_exists($f = $callback_prefix . $callback_secure_prefix . 'traiter_echap_' . $tag)
246
+                || function_exists($f = $f . '_dist')
247
+                || $callback_secure_prefix && (
248
+                    function_exists($f = $callback_prefix . 'traiter_echap_' . $tag)
249
+                    || function_exists($f = $f . '_dist')
250
+                )
251
+            ) {
252
+                $callbacks[$tag] = $f;
253
+            }
254
+        }
255
+    }
256
+
257
+    $letexte = CollecteurHtmlTag::proteger_balisesHtml($letexte, $source, $html_tags, $callbacks, $callback_options);
258
+
259
+    if ($no_transform) {
260
+        return $letexte;
261
+    }
262
+
263
+    // Echapper le php pour faire joli (ici, c'est pas pour la securite)
264
+    // seulement si on a echappe les <script>
265
+    // (derogatoire car on ne peut pas faire passer < ? ... ? >
266
+    // dans une callback autonommee + la preg pour collecter est un peu spécifique
267
+    if (in_array('script', $html_tags ?: CollecteurHtmlTag::$listeBalisesAProteger)) {
268
+        $htmlTagCollecteur = new CollecteurHtmlTag('?', '@<[?].*($|[?]>)@UsS', '');
269
+        $letexte = $htmlTagCollecteur->echapper_enHtmlBase64($letexte, $source, fn ($c, $o) => highlight_string($c['raw'], true));
270
+    }
271
+
272
+    return $letexte;
273 273
 }
274 274
 
275 275
 /**
@@ -283,27 +283,27 @@  discard block
 block discarded – undo
283 283
  * @return array|mixed|string|string[]
284 284
  */
285 285
 function echappe_retour($letexte, $source = '', $filtre = '') {
286
-	if (!is_string($letexte) || !strlen($letexte)) {
287
-		return $letexte;
288
-	}
289
-	return CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte, (string)$source, (string)$filtre);
286
+    if (!is_string($letexte) || !strlen($letexte)) {
287
+        return $letexte;
288
+    }
289
+    return CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte, (string)$source, (string)$filtre);
290 290
 }
291 291
 
292 292
 // Reinserer le javascript de confiance (venant des modeles)
293 293
 
294 294
 function echappe_retour_modeles($letexte, $interdire_scripts = false) {
295
-	if (!is_string($letexte) || !strlen($letexte)) {
296
-		return $letexte;
297
-	}
298
-	$letexte = CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte);
299
-
300
-	// Dans les appels directs hors squelette, securiser aussi ici
301
-	// c'est interdire_scripts() qui rétablit les scripts des modeles echappés avec _PROTEGE_JS_MODELES et _PROTEGE_PHP_MODELES
302
-	if ($interdire_scripts) {
303
-		$letexte = interdire_scripts($letexte);
304
-	}
305
-
306
-	return trim($letexte);
295
+    if (!is_string($letexte) || !strlen($letexte)) {
296
+        return $letexte;
297
+    }
298
+    $letexte = CollecteurHtmlTag::retablir_depuisHtmlBase64((string)$letexte);
299
+
300
+    // Dans les appels directs hors squelette, securiser aussi ici
301
+    // c'est interdire_scripts() qui rétablit les scripts des modeles echappés avec _PROTEGE_JS_MODELES et _PROTEGE_PHP_MODELES
302
+    if ($interdire_scripts) {
303
+        $letexte = interdire_scripts($letexte);
304
+    }
305
+
306
+    return trim($letexte);
307 307
 }
308 308
 
309 309
 
@@ -331,129 +331,129 @@  discard block
 block discarded – undo
331 331
  *     texte coupé
332 332
  **/
333 333
 function couper($texte, $taille = 50, $suite = null) {
334
-	if ($taille <= 0) {
335
-		return '';
336
-	}
337
-	$length = spip_strlen($texte);
338
-	if (!$length) {
339
-		return '';
340
-	}
341
-	$offset = 400 + 2 * $taille;
342
-	while (
343
-		$offset < $length
344
-		&& spip_strlen(preg_replace(',<(!--|\w|/)[^>]+>,Uims', '', spip_substr($texte, 0, $offset))) < $taille
345
-	) {
346
-		$offset *= 2;
347
-	}
348
-	if (
349
-		$offset < $length
350
-		&& ($p_tag_ouvrant = strpos($texte, '<', $offset)) !== null
351
-	) {
352
-		$p_tag_fermant = strpos($texte, '>', $offset);
353
-		// prolonger la coupe jusqu'au tag fermant suivant eventuel
354
-		if ($p_tag_fermant && ($p_tag_fermant < $p_tag_ouvrant)) {
355
-			$offset = $p_tag_fermant + 1;
356
-		}
357
-	}
358
-	// éviter de travailler sur 10ko pour extraire 150 caractères
359
-	$texte = spip_substr($texte, 0, $offset);
360
-
361
-	if (!function_exists('nettoyer_raccourcis_typo')) {
362
-		include_spip('inc/lien');
363
-	}
364
-	$texte = nettoyer_raccourcis_typo($texte);
365
-
366
-	// balises de sauts de ligne et paragraphe
367
-	$texte = preg_replace('/<p( [^>]*)?' . '>/', "\r\r", $texte);
368
-	$texte = preg_replace('/<br( [^>]*)?' . '>/', "\n", $texte);
369
-
370
-	// on repasse les doubles \n en \r que nettoyer_raccourcis_typo() a pu modifier
371
-	$texte = str_replace("\n\n", "\r\r", $texte);
372
-
373
-	// supprimer les tags
374
-	$texte = supprimer_tags($texte);
375
-	$texte = trim(str_replace("\n", ' ', $texte));
376
-
377
-	// tester s'il est nécessaire de couper le texte
378
-	if (spip_strlen($texte) <= $taille) {
379
-		$points = '';
380
-	} else {
381
-		// points de suite
382
-		if (is_null($suite)) {
383
-			$suite = (defined('_COUPER_SUITE') ? _COUPER_SUITE : '&nbsp;(...)');
384
-		}
385
-		$taille_suite = spip_strlen(filtrer_entites($suite));
386
-
387
-		// couper au mot precedent (ou au début de la chaîne si c'est le premier mot)
388
-		// on coupe avec un caractère de plus que la taille demandée afin de pouvoir
389
-		// détecter si le dernier mot du texte coupé est complet ou non. ce caractère
390
-		// excédentaire est ensuite supprimé par l'appel à preg_replace()
391
-		$long = spip_substr($texte, 0, max($taille + 1 - $taille_suite, 1));
392
-		$u = $GLOBALS['meta']['pcre_u'];
393
-		$court = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
394
-		$points = $suite;
395
-
396
-		// trop court ? ne pas faire de (...)
397
-		if (spip_strlen($court) < max(0.75 * $taille, 2)) {
398
-			$points = '';
399
-			$long = spip_substr($texte, 0, $taille + 1);
400
-			preg_match('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, $long, $m);
401
-			$texte = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
402
-			// encore trop court ? couper au caractere
403
-			if (spip_strlen($texte) < 0.75 * $taille) {
404
-				$texte = spip_substr($long, 0, $taille);
405
-			}
406
-		} else {
407
-			$texte = $court;
408
-		}
409
-	}
410
-
411
-	// remettre les paragraphes
412
-	$texte = preg_replace("/\r\r+/", "\n\n", $texte);
413
-
414
-	// supprimer l'eventuelle entite finale mal coupee
415
-	$texte = preg_replace('/&#?[a-z0-9]*$/S', '', $texte);
416
-
417
-	return quote_amp(trim($texte)) . $points;
334
+    if ($taille <= 0) {
335
+        return '';
336
+    }
337
+    $length = spip_strlen($texte);
338
+    if (!$length) {
339
+        return '';
340
+    }
341
+    $offset = 400 + 2 * $taille;
342
+    while (
343
+        $offset < $length
344
+        && spip_strlen(preg_replace(',<(!--|\w|/)[^>]+>,Uims', '', spip_substr($texte, 0, $offset))) < $taille
345
+    ) {
346
+        $offset *= 2;
347
+    }
348
+    if (
349
+        $offset < $length
350
+        && ($p_tag_ouvrant = strpos($texte, '<', $offset)) !== null
351
+    ) {
352
+        $p_tag_fermant = strpos($texte, '>', $offset);
353
+        // prolonger la coupe jusqu'au tag fermant suivant eventuel
354
+        if ($p_tag_fermant && ($p_tag_fermant < $p_tag_ouvrant)) {
355
+            $offset = $p_tag_fermant + 1;
356
+        }
357
+    }
358
+    // éviter de travailler sur 10ko pour extraire 150 caractères
359
+    $texte = spip_substr($texte, 0, $offset);
360
+
361
+    if (!function_exists('nettoyer_raccourcis_typo')) {
362
+        include_spip('inc/lien');
363
+    }
364
+    $texte = nettoyer_raccourcis_typo($texte);
365
+
366
+    // balises de sauts de ligne et paragraphe
367
+    $texte = preg_replace('/<p( [^>]*)?' . '>/', "\r\r", $texte);
368
+    $texte = preg_replace('/<br( [^>]*)?' . '>/', "\n", $texte);
369
+
370
+    // on repasse les doubles \n en \r que nettoyer_raccourcis_typo() a pu modifier
371
+    $texte = str_replace("\n\n", "\r\r", $texte);
372
+
373
+    // supprimer les tags
374
+    $texte = supprimer_tags($texte);
375
+    $texte = trim(str_replace("\n", ' ', $texte));
376
+
377
+    // tester s'il est nécessaire de couper le texte
378
+    if (spip_strlen($texte) <= $taille) {
379
+        $points = '';
380
+    } else {
381
+        // points de suite
382
+        if (is_null($suite)) {
383
+            $suite = (defined('_COUPER_SUITE') ? _COUPER_SUITE : '&nbsp;(...)');
384
+        }
385
+        $taille_suite = spip_strlen(filtrer_entites($suite));
386
+
387
+        // couper au mot precedent (ou au début de la chaîne si c'est le premier mot)
388
+        // on coupe avec un caractère de plus que la taille demandée afin de pouvoir
389
+        // détecter si le dernier mot du texte coupé est complet ou non. ce caractère
390
+        // excédentaire est ensuite supprimé par l'appel à preg_replace()
391
+        $long = spip_substr($texte, 0, max($taille + 1 - $taille_suite, 1));
392
+        $u = $GLOBALS['meta']['pcre_u'];
393
+        $court = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
394
+        $points = $suite;
395
+
396
+        // trop court ? ne pas faire de (...)
397
+        if (spip_strlen($court) < max(0.75 * $taille, 2)) {
398
+            $points = '';
399
+            $long = spip_substr($texte, 0, $taille + 1);
400
+            preg_match('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, $long, $m);
401
+            $texte = preg_replace('/(^|([^\s ])[\s ]+)([\s ]|[^\s ]+)?$/D' . $u, "\\2", $long);
402
+            // encore trop court ? couper au caractere
403
+            if (spip_strlen($texte) < 0.75 * $taille) {
404
+                $texte = spip_substr($long, 0, $taille);
405
+            }
406
+        } else {
407
+            $texte = $court;
408
+        }
409
+    }
410
+
411
+    // remettre les paragraphes
412
+    $texte = preg_replace("/\r\r+/", "\n\n", $texte);
413
+
414
+    // supprimer l'eventuelle entite finale mal coupee
415
+    $texte = preg_replace('/&#?[a-z0-9]*$/S', '', $texte);
416
+
417
+    return quote_amp(trim($texte)) . $points;
418 418
 }
419 419
 
420 420
 
421 421
 function protege_js_modeles($texte) {
422
-	if (isset($GLOBALS['visiteur_session']) && str_contains($texte, '<')) {
423
-		$tags = [
424
-			'javascript' => ['tag' => 'script', 'preg' => ',<script.*?($|</script.),isS', 'c' => '_PROTEGE_JS_MODELES'],
425
-			'php' => ['tag' => '?php', 'preg' => ',<\?php.*?($|\?' . '>),isS', 'c' => '_PROTEGE_PHP_MODELES'],
426
-		];
427
-		foreach ($tags as $k => $t) {
428
-			if (stripos($texte, '<' . $t['tag']) !== false) {
429
-				if (!defined($t['c'])) {
430
-					include_spip('inc/acces');
431
-					define($t['c'], creer_uniqid());
432
-				}
433
-				$collecteurHtmlTag = new CollecteurHtmlTag($t['tag'], $t['preg'], '');
434
-				$texte = $collecteurHtmlTag->echapper_enHtmlBase64($texte, $k . constant($t['c']));
435
-			}
436
-		}
437
-	}
438
-	return $texte;
422
+    if (isset($GLOBALS['visiteur_session']) && str_contains($texte, '<')) {
423
+        $tags = [
424
+            'javascript' => ['tag' => 'script', 'preg' => ',<script.*?($|</script.),isS', 'c' => '_PROTEGE_JS_MODELES'],
425
+            'php' => ['tag' => '?php', 'preg' => ',<\?php.*?($|\?' . '>),isS', 'c' => '_PROTEGE_PHP_MODELES'],
426
+        ];
427
+        foreach ($tags as $k => $t) {
428
+            if (stripos($texte, '<' . $t['tag']) !== false) {
429
+                if (!defined($t['c'])) {
430
+                    include_spip('inc/acces');
431
+                    define($t['c'], creer_uniqid());
432
+                }
433
+                $collecteurHtmlTag = new CollecteurHtmlTag($t['tag'], $t['preg'], '');
434
+                $texte = $collecteurHtmlTag->echapper_enHtmlBase64($texte, $k . constant($t['c']));
435
+            }
436
+        }
437
+    }
438
+    return $texte;
439 439
 }
440 440
 
441 441
 
442 442
 function echapper_faux_tags($letexte) {
443
-	if (!str_contains($letexte, '<')) {
444
-		return $letexte;
445
-	}
446
-	$textMatches = preg_split(',(</?[a-z!][^<>]*>),', $letexte, -1, PREG_SPLIT_DELIM_CAPTURE);
447
-
448
-	$letexte = '';
449
-	while (is_countable($textMatches) ? count($textMatches) : 0) {
450
-		// un texte a echapper
451
-		$letexte .= str_replace('<', '&lt;', array_shift($textMatches));
452
-		// un tag html qui a servit a faite le split
453
-		$letexte .= array_shift($textMatches);
454
-	}
455
-
456
-	return $letexte;
443
+    if (!str_contains($letexte, '<')) {
444
+        return $letexte;
445
+    }
446
+    $textMatches = preg_split(',(</?[a-z!][^<>]*>),', $letexte, -1, PREG_SPLIT_DELIM_CAPTURE);
447
+
448
+    $letexte = '';
449
+    while (is_countable($textMatches) ? count($textMatches) : 0) {
450
+        // un texte a echapper
451
+        $letexte .= str_replace('<', '&lt;', array_shift($textMatches));
452
+        // un tag html qui a servit a faite le split
453
+        $letexte .= array_shift($textMatches);
454
+    }
455
+
456
+    return $letexte;
457 457
 }
458 458
 
459 459
 /**
@@ -473,107 +473,107 @@  discard block
 block discarded – undo
473 473
  * @return string
474 474
  */
475 475
 function echapper_html_suspect($texte, $options = [], $connect = null, $env = []) {
476
-	static $echapper_html_suspect;
477
-	if (!$texte || !is_string($texte)) {
478
-		return $texte;
479
-	}
480
-
481
-	if (!isset($echapper_html_suspect)) {
482
-		$echapper_html_suspect = charger_fonction('echapper_html_suspect', 'inc', true);
483
-	}
484
-	// si fonction personalisee, on delegue
485
-	if ($echapper_html_suspect) {
486
-		// on collecte le tableau d'arg minimal pour ne pas casser un appel a une fonction inc_echapper_html_suspect() selon l'ancienne signature
487
-		$args = [$texte, $options];
488
-		if ($connect || !empty($env)) {
489
-			$args[] = $connect;
490
-		}
491
-		if (!empty($env)) {
492
-			$args[] = $env;
493
-		}
494
-		return $echapper_html_suspect(...$args);
495
-	}
496
-
497
-	if (is_bool($options)) {
498
-		$options = ['strict' => $options];
499
-	}
500
-	$strict = $options['strict'] ?? true;
501
-
502
-	// pas de balise html ou pas d'attribut sur les balises ? c'est OK
503
-	if (
504
-		!str_contains($texte, '<')
505
-		|| !str_contains($texte, '=')
506
-	) {
507
-		return $texte;
508
-	}
509
-
510
-	// dans le prive, on veut afficher tout echappé pour la moderation
511
-	if (!isset($env['espace_prive'])) {
512
-		// conserver le comportement historique en cas d'appel court sans env
513
-		$env['espace_prive'] = test_espace_prive();
514
-	}
515
-	if (!empty($env['espace_prive']) || !empty($env['wysiwyg'])) {
516
-		// quand c'est du texte qui passe par propre on est plus coulant tant qu'il y a pas d'attribut du type onxxx=
517
-		// car sinon on declenche sur les modeles ou ressources
518
-		if (
519
-			!$strict && (!str_contains($texte, 'on') || !preg_match(",<\w+.*\bon\w+\s*=,UimsS", $texte))
520
-		) {
521
-			return $texte;
522
-		}
523
-
524
-		$collecteurModeles = new CollecteurModeles();
525
-		$texte = $collecteurModeles->echapper($texte);
526
-		$texte = echappe_js($texte);
527
-
528
-		$texte_to_check = $texte;
529
-		// si les raccourcis liens vont etre interprétés, il faut les expanser avant de vérifier que le html est safe
530
-		// car un raccourci peut etre utilisé pour faire un lien malin
531
-		// et un raccourci est potentiellement modifié par safehtml, ce qui fait un faux positif dans is_html_safe
532
-		if (!empty($options['expanser_liens'])) {
533
-			$texte_to_check = expanser_liens($texte_to_check, $connect, $env);
534
-		}
535
-		if (!is_html_safe($texte_to_check)) {
536
-			$texte = $options['texte_source_affiche'] ?? $texte;
537
-			$texte = preg_replace(",<(/?\w+\b[^>]*>),", "<tt>&lt;\\1</tt>", $texte);
538
-			$texte = str_replace('<', '&lt;', $texte);
539
-			$texte = str_replace('&lt;tt>', '<tt>', $texte);
540
-			$texte = str_replace('&lt;/tt>', '</tt>', $texte);
541
-			if (!function_exists('attribut_html')) {
542
-				include_spip('inc/filtres');
543
-			}
544
-			if (!empty($options['wrap_suspect'])) {
545
-				$texte = wrap($texte, $options['wrap_suspect']);
546
-			}
547
-			$texte = "<mark class='danger-js' title='" . attribut_html(_T('erreur_contenu_suspect')) . "'>⚠️</mark> " . $texte;
548
-		}
549
-
550
-		$texte = $collecteurModeles->retablir($texte);
551
-	}
552
-
553
-	// si on est là dans le public c'est le mode parano
554
-	// on veut donc un rendu propre et secure, et virer silencieusement ce qui est dangereux
555
-	else {
556
-		$collecteurLiens = $collecteurModeles = null;
557
-		if (!empty($options['expanser_liens'])) {
558
-			$texte = expanser_liens($texte, $connect, $env);
559
-		}
560
-		else {
561
-			$collecteurLiens = new CollecteurLiens();
562
-			$texte = $collecteurLiens->echapper($texte, ['sanitize_callback' => 'safehtml']);
563
-
564
-			$collecteurModeles = new CollecteurModeles();
565
-			$texte = $collecteurModeles->echapper($texte);
566
-		}
567
-		$texte = safehtml($texte);
568
-		if ($collecteurModeles) {
569
-			$texte = $collecteurModeles->retablir($texte);
570
-		}
571
-		if ($collecteurLiens) {
572
-			$texte = $collecteurLiens->retablir($texte);
573
-		}
574
-	}
575
-
576
-	return $texte;
476
+    static $echapper_html_suspect;
477
+    if (!$texte || !is_string($texte)) {
478
+        return $texte;
479
+    }
480
+
481
+    if (!isset($echapper_html_suspect)) {
482
+        $echapper_html_suspect = charger_fonction('echapper_html_suspect', 'inc', true);
483
+    }
484
+    // si fonction personalisee, on delegue
485
+    if ($echapper_html_suspect) {
486
+        // on collecte le tableau d'arg minimal pour ne pas casser un appel a une fonction inc_echapper_html_suspect() selon l'ancienne signature
487
+        $args = [$texte, $options];
488
+        if ($connect || !empty($env)) {
489
+            $args[] = $connect;
490
+        }
491
+        if (!empty($env)) {
492
+            $args[] = $env;
493
+        }
494
+        return $echapper_html_suspect(...$args);
495
+    }
496
+
497
+    if (is_bool($options)) {
498
+        $options = ['strict' => $options];
499
+    }
500
+    $strict = $options['strict'] ?? true;
501
+
502
+    // pas de balise html ou pas d'attribut sur les balises ? c'est OK
503
+    if (
504
+        !str_contains($texte, '<')
505
+        || !str_contains($texte, '=')
506
+    ) {
507
+        return $texte;
508
+    }
509
+
510
+    // dans le prive, on veut afficher tout echappé pour la moderation
511
+    if (!isset($env['espace_prive'])) {
512
+        // conserver le comportement historique en cas d'appel court sans env
513
+        $env['espace_prive'] = test_espace_prive();
514
+    }
515
+    if (!empty($env['espace_prive']) || !empty($env['wysiwyg'])) {
516
+        // quand c'est du texte qui passe par propre on est plus coulant tant qu'il y a pas d'attribut du type onxxx=
517
+        // car sinon on declenche sur les modeles ou ressources
518
+        if (
519
+            !$strict && (!str_contains($texte, 'on') || !preg_match(",<\w+.*\bon\w+\s*=,UimsS", $texte))
520
+        ) {
521
+            return $texte;
522
+        }
523
+
524
+        $collecteurModeles = new CollecteurModeles();
525
+        $texte = $collecteurModeles->echapper($texte);
526
+        $texte = echappe_js($texte);
527
+
528
+        $texte_to_check = $texte;
529
+        // si les raccourcis liens vont etre interprétés, il faut les expanser avant de vérifier que le html est safe
530
+        // car un raccourci peut etre utilisé pour faire un lien malin
531
+        // et un raccourci est potentiellement modifié par safehtml, ce qui fait un faux positif dans is_html_safe
532
+        if (!empty($options['expanser_liens'])) {
533
+            $texte_to_check = expanser_liens($texte_to_check, $connect, $env);
534
+        }
535
+        if (!is_html_safe($texte_to_check)) {
536
+            $texte = $options['texte_source_affiche'] ?? $texte;
537
+            $texte = preg_replace(",<(/?\w+\b[^>]*>),", "<tt>&lt;\\1</tt>", $texte);
538
+            $texte = str_replace('<', '&lt;', $texte);
539
+            $texte = str_replace('&lt;tt>', '<tt>', $texte);
540
+            $texte = str_replace('&lt;/tt>', '</tt>', $texte);
541
+            if (!function_exists('attribut_html')) {
542
+                include_spip('inc/filtres');
543
+            }
544
+            if (!empty($options['wrap_suspect'])) {
545
+                $texte = wrap($texte, $options['wrap_suspect']);
546
+            }
547
+            $texte = "<mark class='danger-js' title='" . attribut_html(_T('erreur_contenu_suspect')) . "'>⚠️</mark> " . $texte;
548
+        }
549
+
550
+        $texte = $collecteurModeles->retablir($texte);
551
+    }
552
+
553
+    // si on est là dans le public c'est le mode parano
554
+    // on veut donc un rendu propre et secure, et virer silencieusement ce qui est dangereux
555
+    else {
556
+        $collecteurLiens = $collecteurModeles = null;
557
+        if (!empty($options['expanser_liens'])) {
558
+            $texte = expanser_liens($texte, $connect, $env);
559
+        }
560
+        else {
561
+            $collecteurLiens = new CollecteurLiens();
562
+            $texte = $collecteurLiens->echapper($texte, ['sanitize_callback' => 'safehtml']);
563
+
564
+            $collecteurModeles = new CollecteurModeles();
565
+            $texte = $collecteurModeles->echapper($texte);
566
+        }
567
+        $texte = safehtml($texte);
568
+        if ($collecteurModeles) {
569
+            $texte = $collecteurModeles->retablir($texte);
570
+        }
571
+        if ($collecteurLiens) {
572
+            $texte = $collecteurLiens->retablir($texte);
573
+        }
574
+    }
575
+
576
+    return $texte;
577 577
 }
578 578
 
579 579
 
@@ -594,48 +594,48 @@  discard block
 block discarded – undo
594 594
  *      texte sécurisé
595 595
  **/
596 596
 function safehtml($t) {
597
-	static $safehtml;
598
-
599
-	if (!$t || !is_string($t)) {
600
-		return $t;
601
-	}
602
-	# attention safehtml nettoie deux ou trois caracteres de plus. A voir
603
-	if (!str_contains($t, '<')) {
604
-		return str_replace("\x00", '', $t);
605
-	}
606
-
607
-	$collecteurIdiomes = null;
608
-	if (stripos($t, '<:') !== false) {
609
-		$collecteurIdiomes = new CollecteurIdiomes();
610
-		$t = $collecteurIdiomes->echapper($t);
611
-	}
612
-	$collecteurMultis = null;
613
-	if (stripos($t, '<multi') !== false) {
614
-		$collecteurMultis = new CollecteurMultis();
615
-		$t = $collecteurMultis->echapper($t, ['sanitize_callback' => 'safehtml']);
616
-	}
617
-
618
-	if (!function_exists('interdire_scripts')) {
619
-		include_spip('inc/texte');
620
-	}
621
-	$t = interdire_scripts($t); // jolifier le php
622
-	$t = echappe_js($t);
623
-
624
-	if (!isset($safehtml)) {
625
-		$safehtml = charger_fonction('safehtml', 'inc', true);
626
-	}
627
-	if ($safehtml) {
628
-		$t = $safehtml($t);
629
-	}
630
-
631
-	if ($collecteurMultis) {
632
-		$t = $collecteurMultis->retablir($t);
633
-	}
634
-	if ($collecteurIdiomes) {
635
-		$t = $collecteurIdiomes->retablir($t);
636
-	}
637
-
638
-	return interdire_scripts($t); // interdire le php (2 precautions)
597
+    static $safehtml;
598
+
599
+    if (!$t || !is_string($t)) {
600
+        return $t;
601
+    }
602
+    # attention safehtml nettoie deux ou trois caracteres de plus. A voir
603
+    if (!str_contains($t, '<')) {
604
+        return str_replace("\x00", '', $t);
605
+    }
606
+
607
+    $collecteurIdiomes = null;
608
+    if (stripos($t, '<:') !== false) {
609
+        $collecteurIdiomes = new CollecteurIdiomes();
610
+        $t = $collecteurIdiomes->echapper($t);
611
+    }
612
+    $collecteurMultis = null;
613
+    if (stripos($t, '<multi') !== false) {
614
+        $collecteurMultis = new CollecteurMultis();
615
+        $t = $collecteurMultis->echapper($t, ['sanitize_callback' => 'safehtml']);
616
+    }
617
+
618
+    if (!function_exists('interdire_scripts')) {
619
+        include_spip('inc/texte');
620
+    }
621
+    $t = interdire_scripts($t); // jolifier le php
622
+    $t = echappe_js($t);
623
+
624
+    if (!isset($safehtml)) {
625
+        $safehtml = charger_fonction('safehtml', 'inc', true);
626
+    }
627
+    if ($safehtml) {
628
+        $t = $safehtml($t);
629
+    }
630
+
631
+    if ($collecteurMultis) {
632
+        $t = $collecteurMultis->retablir($t);
633
+    }
634
+    if ($collecteurIdiomes) {
635
+        $t = $collecteurIdiomes->retablir($t);
636
+    }
637
+
638
+    return interdire_scripts($t); // interdire le php (2 precautions)
639 639
 }
640 640
 
641 641
 
@@ -643,29 +643,29 @@  discard block
 block discarded – undo
643 643
  * Detecter si un texte est "safe" ie non modifie significativement par safehtml()
644 644
  */
645 645
 function is_html_safe(string $texte): bool {
646
-	if ($is_html_safe = charger_fonction('is_html_safe', 'inc', true)) {
647
-		return $is_html_safe($texte);
648
-	}
649
-
650
-	// simplifier les retour ligne pour etre certain de ce que l'on compare
651
-	$texte = str_replace("\r\n", "\n", $texte);
652
-	// safehtml reduit aussi potentiellement les &nbsp;
653
-	$texte = str_replace('&nbsp;', ' ', $texte);
654
-	// safehtml remplace les entités html
655
-	if (str_contains($texte, '&') && str_contains($texte, ';')) {
656
-		$texte = html2unicode($texte, true);
657
-	}
658
-	// safehtml remplace les entités numériques
659
-	if (str_contains($texte, '&#')) {
660
-		$texte = unicode2charset($texte);
661
-	}
662
-
663
-	$texte_safe = safehtml($texte);
664
-
665
-	// on teste sur strlen car safehtml supprime le contenu dangereux
666
-	// mais il peut aussi changer des ' en " sur les attributs html,
667
-	// donc un test d'egalite est trop strict
668
-	return strlen($texte_safe) === strlen($texte);
646
+    if ($is_html_safe = charger_fonction('is_html_safe', 'inc', true)) {
647
+        return $is_html_safe($texte);
648
+    }
649
+
650
+    // simplifier les retour ligne pour etre certain de ce que l'on compare
651
+    $texte = str_replace("\r\n", "\n", $texte);
652
+    // safehtml reduit aussi potentiellement les &nbsp;
653
+    $texte = str_replace('&nbsp;', ' ', $texte);
654
+    // safehtml remplace les entités html
655
+    if (str_contains($texte, '&') && str_contains($texte, ';')) {
656
+        $texte = html2unicode($texte, true);
657
+    }
658
+    // safehtml remplace les entités numériques
659
+    if (str_contains($texte, '&#')) {
660
+        $texte = unicode2charset($texte);
661
+    }
662
+
663
+    $texte_safe = safehtml($texte);
664
+
665
+    // on teste sur strlen car safehtml supprime le contenu dangereux
666
+    // mais il peut aussi changer des ' en " sur les attributs html,
667
+    // donc un test d'egalite est trop strict
668
+    return strlen($texte_safe) === strlen($texte);
669 669
 }
670 670
 
671 671
 /**
@@ -686,13 +686,13 @@  discard block
 block discarded – undo
686 686
  *     texte sans les modèles d'image
687 687
  **/
688 688
 function supprime_img($letexte, $message = null) {
689
-	if ($message === null) {
690
-		$message = '(' . _T('img_indisponible') . ')';
691
-	}
692
-
693
-	return preg_replace(
694
-		',<(img|doc|emb)([0-9]+)(\|([^>]*))?' . '\s*/?' . '>,i',
695
-		$message,
696
-		$letexte
697
-	);
689
+    if ($message === null) {
690
+        $message = '(' . _T('img_indisponible') . ')';
691
+    }
692
+
693
+    return preg_replace(
694
+        ',<(img|doc|emb)([0-9]+)(\|([^>]*))?' . '\s*/?' . '>,i',
695
+        $message,
696
+        $letexte
697
+    );
698 698
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -556,8 +556,7 @@
 block discarded – undo
556 556
 		$collecteurLiens = $collecteurModeles = null;
557 557
 		if (!empty($options['expanser_liens'])) {
558 558
 			$texte = expanser_liens($texte, $connect, $env);
559
-		}
560
-		else {
559
+		} else {
561 560
 			$collecteurLiens = new CollecteurLiens();
562 561
 			$texte = $collecteurLiens->echapper($texte, ['sanitize_callback' => 'safehtml']);
563 562
 
Please login to merge, or discard this patch.
ecrire/plugins/afficher_nom_plugin.php 2 patches
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -10,53 +10,53 @@
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 include_spip('inc/charsets');
16 16
 include_spip('inc/texte');
17 17
 include_spip('plugins/afficher_plugin');
18 18
 
19 19
 function plugins_afficher_nom_plugin_dist(
20
-	$url_page,
21
-	$plug_file,
22
-	$checked,
23
-	$actif,
24
-	$expose = false,
25
-	$class_li = 'item',
26
-	$dir_plugins = _DIR_PLUGINS
20
+    $url_page,
21
+    $plug_file,
22
+    $checked,
23
+    $actif,
24
+    $expose = false,
25
+    $class_li = 'item',
26
+    $dir_plugins = _DIR_PLUGINS
27 27
 ) {
28
-	static $versions = [];
29
-
30
-	$erreur = false;
31
-	$s = '';
32
-
33
-	$get_infos = charger_fonction('get_infos', 'plugins');
34
-	$info = $get_infos($plug_file, false, $dir_plugins);
35
-
36
-	// numerotons les occurences d'un meme prefix
37
-	$versions[$info['prefix']] ??= 0;
38
-	$versions[$info['prefix']]++;
39
-	$id = $info['prefix'] . $versions[$info['prefix']];
40
-
41
-	$class = $class_li;
42
-	$class .= $actif ? ' actif' : '';
43
-	$class .= $expose ? ' on' : '';
44
-	$erreur = isset($info['erreur']);
45
-	if ($erreur) {
46
-		$class .= ' error';
47
-	}
48
-	$s .= "<li id='$id' class='$class'>";
49
-
50
-	// Cartouche Resume
51
-	$s .= "<div class='resume'>";
52
-	$s .= "<strong class='nom'>" . typo($info['nom']) . '</strong>';
53
-	$s .= " <span class='version'>" . $info['version'] . '</span>';
54
-	$s .= " <span class='etat'> - " . plugin_etat_en_clair($info['etat']) . '</span>';
55
-	$s .= '</div>';
56
-
57
-	if ($erreur) {
58
-		$s .= "<div class='erreur'>" . implode('<br >', $info['erreur']) . '</div>';
59
-	}
60
-
61
-	return $s . '</li>';
28
+    static $versions = [];
29
+
30
+    $erreur = false;
31
+    $s = '';
32
+
33
+    $get_infos = charger_fonction('get_infos', 'plugins');
34
+    $info = $get_infos($plug_file, false, $dir_plugins);
35
+
36
+    // numerotons les occurences d'un meme prefix
37
+    $versions[$info['prefix']] ??= 0;
38
+    $versions[$info['prefix']]++;
39
+    $id = $info['prefix'] . $versions[$info['prefix']];
40
+
41
+    $class = $class_li;
42
+    $class .= $actif ? ' actif' : '';
43
+    $class .= $expose ? ' on' : '';
44
+    $erreur = isset($info['erreur']);
45
+    if ($erreur) {
46
+        $class .= ' error';
47
+    }
48
+    $s .= "<li id='$id' class='$class'>";
49
+
50
+    // Cartouche Resume
51
+    $s .= "<div class='resume'>";
52
+    $s .= "<strong class='nom'>" . typo($info['nom']) . '</strong>';
53
+    $s .= " <span class='version'>" . $info['version'] . '</span>';
54
+    $s .= " <span class='etat'> - " . plugin_etat_en_clair($info['etat']) . '</span>';
55
+    $s .= '</div>';
56
+
57
+    if ($erreur) {
58
+        $s .= "<div class='erreur'>" . implode('<br >', $info['erreur']) . '</div>';
59
+    }
60
+
61
+    return $s . '</li>';
62 62
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	// numerotons les occurences d'un meme prefix
37 37
 	$versions[$info['prefix']] ??= 0;
38 38
 	$versions[$info['prefix']]++;
39
-	$id = $info['prefix'] . $versions[$info['prefix']];
39
+	$id = $info['prefix'].$versions[$info['prefix']];
40 40
 
41 41
 	$class = $class_li;
42 42
 	$class .= $actif ? ' actif' : '';
@@ -49,14 +49,14 @@  discard block
 block discarded – undo
49 49
 
50 50
 	// Cartouche Resume
51 51
 	$s .= "<div class='resume'>";
52
-	$s .= "<strong class='nom'>" . typo($info['nom']) . '</strong>';
53
-	$s .= " <span class='version'>" . $info['version'] . '</span>';
54
-	$s .= " <span class='etat'> - " . plugin_etat_en_clair($info['etat']) . '</span>';
52
+	$s .= "<strong class='nom'>".typo($info['nom']).'</strong>';
53
+	$s .= " <span class='version'>".$info['version'].'</span>';
54
+	$s .= " <span class='etat'> - ".plugin_etat_en_clair($info['etat']).'</span>';
55 55
 	$s .= '</div>';
56 56
 
57 57
 	if ($erreur) {
58
-		$s .= "<div class='erreur'>" . implode('<br >', $info['erreur']) . '</div>';
58
+		$s .= "<div class='erreur'>".implode('<br >', $info['erreur']).'</div>';
59 59
 	}
60 60
 
61
-	return $s . '</li>';
61
+	return $s.'</li>';
62 62
 }
Please login to merge, or discard this patch.
ecrire/plugins/afficher_plugin.php 2 patches
Indentation   +301 added lines, -301 removed lines patch added patch discarded remove patch
@@ -16,212 +16,212 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 include_spip('inc/charsets');
22 22
 include_spip('inc/texte');
23 23
 include_spip('inc/plugin'); // pour plugin_est_installe
24 24
 
25 25
 function plugins_afficher_plugin_dist(
26
-	$url_page,
27
-	$plug_file,
28
-	$checked,
29
-	$actif,
30
-	$expose = false,
31
-	$class_li = 'item',
32
-	$dir_plugins = _DIR_PLUGINS
26
+    $url_page,
27
+    $plug_file,
28
+    $checked,
29
+    $actif,
30
+    $expose = false,
31
+    $class_li = 'item',
32
+    $dir_plugins = _DIR_PLUGINS
33 33
 ) {
34 34
 
35
-	static $id_input = 0;
36
-	static $versions = [];
37
-
38
-	$force_reload = (_request('var_mode') == 'recalcul');
39
-	$get_infos = charger_fonction('get_infos', 'plugins');
40
-	$info = $get_infos($plug_file, $force_reload, $dir_plugins);
41
-	$prefix = $info['prefix'];
42
-	$cfg = '';
43
-	$checkable = ($dir_plugins !== _DIR_PLUGINS_DIST);
44
-	$nom = plugin_nom($info, $dir_plugins, $plug_file);
45
-	$erreur = '';
46
-
47
-	if (!plugin_version_compatible($info['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
48
-		$info['slogan'] = _T('plugin_info_non_compatible_spip');
49
-		$erreur = http_img_pack(
50
-			'plugin-dis-32.png',
51
-			_T('plugin_info_non_compatible_spip'),
52
-			" class='picto_err'",
53
-			_T('plugin_info_non_compatible_spip')
54
-		);
55
-		$class_li .= ' disabled';
56
-		$checkable = false;
57
-	} elseif (isset($info['erreur'])) {
58
-		$class_li .= ' error';
59
-		$erreur = http_img_pack(
60
-			'plugin-err-32.png',
61
-			_T('plugin_info_erreur_xml'),
62
-			" class='picto_err'",
63
-			_T('plugin_info_erreur_xml')
64
-		)
65
-			. "<div class='erreur'>" . join('<br >', $info['erreur']) . '</div>';
66
-		$checkable = false;
67
-	} elseif (isset($GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file])) {
68
-		$class_li .= ' error';
69
-		$erreur = http_img_pack(
70
-			'plugin-err-32.png',
71
-			_T('plugin_impossible_activer', ['plugin' => $nom]),
72
-			" class='picto_err'",
73
-			_T('plugin_impossible_activer', ['plugin' => $nom])
74
-		)
75
-			. "<div class='erreur'>" . implode(
76
-				'<br />',
77
-				$GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file]
78
-			) . '</div>';
79
-	} else {
80
-		$cfg = $actif ? plugin_bouton_config($plug_file, $info, $dir_plugins) : '';
81
-		if (defined('_DEV_VERSION_SPIP_COMPAT') && !plugin_version_compatible($info['compatibilite'], $GLOBALS['spip_version_branche'])) {
82
-			//$info['slogan'] = _T('plugin_info_non_compatible_spip');
83
-			$erreur = http_img_pack(
84
-				'plugin-dis-32.png',
85
-				_T('plugin_info_non_compatible_spip'),
86
-				" class='picto_err picto_compat_forcee'",
87
-				_L('Version incompatible : compatibilité forcée')
88
-			);
89
-		}
90
-	}
91
-
92
-	// numerotons les occurrences d'un meme prefix
93
-	$versions[$prefix] = $id = isset($versions[$prefix]) ? intval($versions[$prefix]) + 1 : '';
94
-
95
-	$class_li .= ($actif ? ' actif' : '') . ($expose ? ' on' : '');
96
-
97
-	return "<li id='$prefix$id' class='$class_li'>"
98
-	. ((!$checkable && !$checked)
99
-		? '' : plugin_checkbox(++$id_input, $dir_plugins . $plug_file, $checked))
100
-	. plugin_resume($info, $dir_plugins, $plug_file, $url_page)
101
-	. $cfg
102
-	. $erreur
103
-	. (($dir_plugins !== _DIR_PLUGINS_DIST && plugin_est_installe($plug_file))
104
-		? plugin_desintalle($plug_file, $nom, $dir_plugins) : '')
105
-	. "<div class='details'>" // pour l'ajax de exec/info_plugin
106
-	. (!$expose ? '' : affiche_bloc_plugin($plug_file, $info, $dir_plugins))
107
-	. '</div>'
108
-	. '</li>';
35
+    static $id_input = 0;
36
+    static $versions = [];
37
+
38
+    $force_reload = (_request('var_mode') == 'recalcul');
39
+    $get_infos = charger_fonction('get_infos', 'plugins');
40
+    $info = $get_infos($plug_file, $force_reload, $dir_plugins);
41
+    $prefix = $info['prefix'];
42
+    $cfg = '';
43
+    $checkable = ($dir_plugins !== _DIR_PLUGINS_DIST);
44
+    $nom = plugin_nom($info, $dir_plugins, $plug_file);
45
+    $erreur = '';
46
+
47
+    if (!plugin_version_compatible($info['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
48
+        $info['slogan'] = _T('plugin_info_non_compatible_spip');
49
+        $erreur = http_img_pack(
50
+            'plugin-dis-32.png',
51
+            _T('plugin_info_non_compatible_spip'),
52
+            " class='picto_err'",
53
+            _T('plugin_info_non_compatible_spip')
54
+        );
55
+        $class_li .= ' disabled';
56
+        $checkable = false;
57
+    } elseif (isset($info['erreur'])) {
58
+        $class_li .= ' error';
59
+        $erreur = http_img_pack(
60
+            'plugin-err-32.png',
61
+            _T('plugin_info_erreur_xml'),
62
+            " class='picto_err'",
63
+            _T('plugin_info_erreur_xml')
64
+        )
65
+            . "<div class='erreur'>" . join('<br >', $info['erreur']) . '</div>';
66
+        $checkable = false;
67
+    } elseif (isset($GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file])) {
68
+        $class_li .= ' error';
69
+        $erreur = http_img_pack(
70
+            'plugin-err-32.png',
71
+            _T('plugin_impossible_activer', ['plugin' => $nom]),
72
+            " class='picto_err'",
73
+            _T('plugin_impossible_activer', ['plugin' => $nom])
74
+        )
75
+            . "<div class='erreur'>" . implode(
76
+                '<br />',
77
+                $GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file]
78
+            ) . '</div>';
79
+    } else {
80
+        $cfg = $actif ? plugin_bouton_config($plug_file, $info, $dir_plugins) : '';
81
+        if (defined('_DEV_VERSION_SPIP_COMPAT') && !plugin_version_compatible($info['compatibilite'], $GLOBALS['spip_version_branche'])) {
82
+            //$info['slogan'] = _T('plugin_info_non_compatible_spip');
83
+            $erreur = http_img_pack(
84
+                'plugin-dis-32.png',
85
+                _T('plugin_info_non_compatible_spip'),
86
+                " class='picto_err picto_compat_forcee'",
87
+                _L('Version incompatible : compatibilité forcée')
88
+            );
89
+        }
90
+    }
91
+
92
+    // numerotons les occurrences d'un meme prefix
93
+    $versions[$prefix] = $id = isset($versions[$prefix]) ? intval($versions[$prefix]) + 1 : '';
94
+
95
+    $class_li .= ($actif ? ' actif' : '') . ($expose ? ' on' : '');
96
+
97
+    return "<li id='$prefix$id' class='$class_li'>"
98
+    . ((!$checkable && !$checked)
99
+        ? '' : plugin_checkbox(++$id_input, $dir_plugins . $plug_file, $checked))
100
+    . plugin_resume($info, $dir_plugins, $plug_file, $url_page)
101
+    . $cfg
102
+    . $erreur
103
+    . (($dir_plugins !== _DIR_PLUGINS_DIST && plugin_est_installe($plug_file))
104
+        ? plugin_desintalle($plug_file, $nom, $dir_plugins) : '')
105
+    . "<div class='details'>" // pour l'ajax de exec/info_plugin
106
+    . (!$expose ? '' : affiche_bloc_plugin($plug_file, $info, $dir_plugins))
107
+    . '</div>'
108
+    . '</li>';
109 109
 }
110 110
 
111 111
 function plugin_bouton_config($nom, $infos, $dir) {
112
-	// la verification se base sur le filesystem
113
-	// il faut donc n'utiliser que des minuscules, par convention
114
-	$prefix = strtolower($infos['prefix']);
115
-	// si paquet.xml fournit un squelette, le prendre
116
-	if (isset($infos['config']) && $infos['config']) {
117
-		return recuperer_fond(
118
-			"$dir$nom/" . $infos['config'],
119
-			[
120
-				'script' => 'configurer_' . $prefix,
121
-				'nom' => $nom
122
-			]
123
-		);
124
-	}
125
-
126
-	// sinon prendre le squelette std sur le nom std
127
-	return recuperer_fond(
128
-		'prive/squelettes/inclure/cfg',
129
-		[
130
-			'script' => 'configurer_' . $prefix,
131
-			'nom' => $nom
132
-		]
133
-	);
112
+    // la verification se base sur le filesystem
113
+    // il faut donc n'utiliser que des minuscules, par convention
114
+    $prefix = strtolower($infos['prefix']);
115
+    // si paquet.xml fournit un squelette, le prendre
116
+    if (isset($infos['config']) && $infos['config']) {
117
+        return recuperer_fond(
118
+            "$dir$nom/" . $infos['config'],
119
+            [
120
+                'script' => 'configurer_' . $prefix,
121
+                'nom' => $nom
122
+            ]
123
+        );
124
+    }
125
+
126
+    // sinon prendre le squelette std sur le nom std
127
+    return recuperer_fond(
128
+        'prive/squelettes/inclure/cfg',
129
+        [
130
+            'script' => 'configurer_' . $prefix,
131
+            'nom' => $nom
132
+        ]
133
+    );
134 134
 }
135 135
 
136 136
 // checkbox pour activer ou desactiver
137 137
 // si ce n'est pas une extension
138 138
 
139 139
 function plugin_checkbox($id_input, $file, $actif) {
140
-	$name = substr(md5($file), 0, 16);
141
-
142
-	return "<div class='check'>\n"
143
-	. "<input type='checkbox' name='s$name' id='label_$id_input'"
144
-	. ($actif ? " checked='checked'" : '')
145
-	. " class='checkbox'  value='O' />"
146
-	. "\n<label for='label_$id_input'>" . _T('activer_plugin') . '</label>'
147
-	. '</div>';
140
+    $name = substr(md5($file), 0, 16);
141
+
142
+    return "<div class='check'>\n"
143
+    . "<input type='checkbox' name='s$name' id='label_$id_input'"
144
+    . ($actif ? " checked='checked'" : '')
145
+    . " class='checkbox'  value='O' />"
146
+    . "\n<label for='label_$id_input'>" . _T('activer_plugin') . '</label>'
147
+    . '</div>';
148 148
 }
149 149
 
150 150
 function plugin_nom($info, $dir_plugins, $plug_file) {
151
-	$prefix = $info['prefix'];
152
-	$dir = "$dir_plugins$plug_file";
153
-	// Si dtd paquet, on traite le nom soit par son item de langue soit par sa valeur immediate a l'index "nom"
154
-	if ($info['dtd'] == 'paquet') {
155
-		$nom = plugin_typo("{$prefix}_nom", "$dir/lang/paquet-$prefix");
156
-		if (!$nom) {
157
-			$nom = typo($info['nom']);
158
-		}
159
-	} else {
160
-		$nom = typo(attribut_html($info['nom']));
161
-	}
162
-
163
-	return trim($nom);
151
+    $prefix = $info['prefix'];
152
+    $dir = "$dir_plugins$plug_file";
153
+    // Si dtd paquet, on traite le nom soit par son item de langue soit par sa valeur immediate a l'index "nom"
154
+    if ($info['dtd'] == 'paquet') {
155
+        $nom = plugin_typo("{$prefix}_nom", "$dir/lang/paquet-$prefix");
156
+        if (!$nom) {
157
+            $nom = typo($info['nom']);
158
+        }
159
+    } else {
160
+        $nom = typo(attribut_html($info['nom']));
161
+    }
162
+
163
+    return trim($nom);
164 164
 }
165 165
 
166 166
 // Cartouche Resume
167 167
 function plugin_resume($info, $dir_plugins, $plug_file, $url_page) {
168
-	$prefix = $info['prefix'];
169
-	$dir = "$dir_plugins$plug_file";
170
-	$slogan = PtoBR(plugin_propre($info['slogan'], "$dir/lang/paquet-$prefix"));
171
-	// une seule ligne dans le slogan : couper si besoin
172
-	if (($p = strpos($slogan, '<br />')) !== false) {
173
-		$slogan = substr($slogan, 0, $p);
174
-	}
175
-	// couper par securite
176
-	$slogan = couper($slogan, 80);
177
-
178
-	$nom = plugin_nom($info, $dir_plugins, $plug_file);
179
-
180
-	$url = parametre_url($url_page, 'plugin', substr($dir, strlen(_DIR_RACINE)));
181
-
182
-	$icon_class = 'icon';
183
-	$img = '';
184
-	if (isset($info['logo']) && ($i = trim($info['logo']))) {
185
-		$img = http_img_pack("$dir/$i", '', " width='32' height='32'", '', ['variante_svg_si_possible' => true, 'chemin_image' => false]);
186
-		if (!extraire_attribut($img, 'src')) {
187
-			$img = '';
188
-		}
189
-	}
190
-	if (!$img) {
191
-		$img = http_img_pack('plugin-xx.svg', '', " width='32' height='32'");
192
-		$icon_class .= ' no-logo';
193
-	}
194
-
195
-	$i = "<div class='$icon_class'><a href='$url' rel='info'>$img</a></div>";
196
-
197
-	return "<div class='resume'>"
198
-	. "<h3><a href='$url' rel='info'>"
199
-	. $nom
200
-	. '</a></h3>'
201
-	. " <span class='version'>" . $info['version'] . '</span>'
202
-	. " <span class='etat'> - "
203
-	. plugin_etat_en_clair($info['etat'])
204
-	. '</span>'
205
-	. "<div class='short'>" . $slogan . '</div>'
206
-	. $i
207
-	. '</div>';
168
+    $prefix = $info['prefix'];
169
+    $dir = "$dir_plugins$plug_file";
170
+    $slogan = PtoBR(plugin_propre($info['slogan'], "$dir/lang/paquet-$prefix"));
171
+    // une seule ligne dans le slogan : couper si besoin
172
+    if (($p = strpos($slogan, '<br />')) !== false) {
173
+        $slogan = substr($slogan, 0, $p);
174
+    }
175
+    // couper par securite
176
+    $slogan = couper($slogan, 80);
177
+
178
+    $nom = plugin_nom($info, $dir_plugins, $plug_file);
179
+
180
+    $url = parametre_url($url_page, 'plugin', substr($dir, strlen(_DIR_RACINE)));
181
+
182
+    $icon_class = 'icon';
183
+    $img = '';
184
+    if (isset($info['logo']) && ($i = trim($info['logo']))) {
185
+        $img = http_img_pack("$dir/$i", '', " width='32' height='32'", '', ['variante_svg_si_possible' => true, 'chemin_image' => false]);
186
+        if (!extraire_attribut($img, 'src')) {
187
+            $img = '';
188
+        }
189
+    }
190
+    if (!$img) {
191
+        $img = http_img_pack('plugin-xx.svg', '', " width='32' height='32'");
192
+        $icon_class .= ' no-logo';
193
+    }
194
+
195
+    $i = "<div class='$icon_class'><a href='$url' rel='info'>$img</a></div>";
196
+
197
+    return "<div class='resume'>"
198
+    . "<h3><a href='$url' rel='info'>"
199
+    . $nom
200
+    . '</a></h3>'
201
+    . " <span class='version'>" . $info['version'] . '</span>'
202
+    . " <span class='etat'> - "
203
+    . plugin_etat_en_clair($info['etat'])
204
+    . '</span>'
205
+    . "<div class='short'>" . $slogan . '</div>'
206
+    . $i
207
+    . '</div>';
208 208
 }
209 209
 
210 210
 function plugin_desintalle($plug_file, $nom, $dir_plugins = null) {
211
-	if (!$dir_plugins) {
212
-		$dir_plugins = _DIR_PLUGINS;
213
-	}
211
+    if (!$dir_plugins) {
212
+        $dir_plugins = _DIR_PLUGINS;
213
+    }
214 214
 
215
-	$action = redirige_action_auteur('desinstaller_plugin', "$dir_plugins::$plug_file", 'admin_plugin');
216
-	$text = _T('bouton_desinstaller');
217
-	$text2 = _T('info_desinstaller_plugin');
218
-	$file = basename($plug_file);
215
+    $action = redirige_action_auteur('desinstaller_plugin', "$dir_plugins::$plug_file", 'admin_plugin');
216
+    $text = _T('bouton_desinstaller');
217
+    $text2 = _T('info_desinstaller_plugin');
218
+    $file = basename($plug_file);
219 219
 
220
-	return "<div class='actions'>[" .
221
-	"<a href='$action'
220
+    return "<div class='actions'>[" .
221
+    "<a href='$action'
222 222
 		onclick='return confirm(\"$text $nom ?\\n$text2\")'>"
223
-	. $text
224
-	. '</a>]</div>';
223
+    . $text
224
+    . '</a>]</div>';
225 225
 }
226 226
 
227 227
 /**
@@ -235,143 +235,143 @@  discard block
 block discarded – undo
235 235
  *     Traduction de l'état dans la langue en cours
236 236
  **/
237 237
 function plugin_etat_en_clair($etat) {
238
-	if (!in_array($etat, ['stable', 'test', 'experimental'])) {
239
-		$etat = 'developpement';
240
-	}
238
+    if (!in_array($etat, ['stable', 'test', 'experimental'])) {
239
+        $etat = 'developpement';
240
+    }
241 241
 
242
-	return _T('plugin_etat_' . $etat);
242
+    return _T('plugin_etat_' . $etat);
243 243
 }
244 244
 
245 245
 function plugin_propre($texte, $module = '', $propre = 'propre') {
246
-	// retirer le retour a la racine du module, car le find_in_path se fait depuis la racine
247
-	if (_DIR_RACINE && str_starts_with($module, _DIR_RACINE)) {
248
-		$module = substr($module, strlen(_DIR_RACINE));
249
-	}
250
-	if (preg_match('|^\w+_[\w_]+$|', $texte)) {
251
-		$texte = _T(($module ? "$module:" : '') . $texte, [], ['force' => false]);
252
-	}
253
-
254
-	return $propre($texte);
246
+    // retirer le retour a la racine du module, car le find_in_path se fait depuis la racine
247
+    if (_DIR_RACINE && str_starts_with($module, _DIR_RACINE)) {
248
+        $module = substr($module, strlen(_DIR_RACINE));
249
+    }
250
+    if (preg_match('|^\w+_[\w_]+$|', $texte)) {
251
+        $texte = _T(($module ? "$module:" : '') . $texte, [], ['force' => false]);
252
+    }
253
+
254
+    return $propre($texte);
255 255
 }
256 256
 
257 257
 function plugin_typo($texte, $module = '') {
258
-	return plugin_propre($texte, $module, 'typo');
258
+    return plugin_propre($texte, $module, 'typo');
259 259
 }
260 260
 
261 261
 
262 262
 function affiche_bloc_plugin($plug_file, $info, $dir_plugins = null) {
263
-	$log = null;
264
-	if (!$dir_plugins) {
265
-		$dir_plugins = _DIR_PLUGINS;
266
-	}
267
-
268
-	$prefix = $info['prefix'];
269
-	$dir = "$dir_plugins$plug_file/lang/paquet-$prefix";
270
-
271
-	$s = '';
272
-	// TODO: le traiter_multi ici n'est pas beau
273
-	// cf. description du plugin/_stable_/ortho/plugin.xml
274
-	// concerne les anciens plugin.xml donc on devrait plus en avoir besoin
275
-	$description = '';
276
-	if (isset($info['description'])) {
277
-		$description = plugin_propre($info['description'], $dir);
278
-	}
279
-
280
-	if (
281
-		isset($info['documentation']) && ($lien = $info['documentation'])
282
-	) {
283
-		$description .= "<p><em class='site'><a href='$lien' class='spip_out'>" . _T('en_savoir_plus') . '</a></em></p>';
284
-	}
285
-	$s .= "<dd class='desc'>" . $description . "</dd>\n";
286
-
287
-	if (isset($info['auteur'])) {
288
-		if (is_array($info['auteur'])) {
289
-			$a = formater_credits($info['auteur'], ', ');
290
-		} // pour compat mais ne doit plus arriver
291
-		else {
292
-			$a = trim($info['auteur']);
293
-		}
294
-		if ($a) {
295
-			$s .= "<dt class='auteurs'>" . _T('public:par_auteur') . "</dt><dd class='auteurs'>" . PtoBR(propre(
296
-				$a,
297
-				$dir
298
-			)) . "</dd>\n";
299
-		}
300
-	}
301
-
302
-	if (isset($info['credit'])) {
303
-		if ($a = formater_credits($info['credit'], ', ')) {
304
-			$s .= "<dt class='credits'>" . _T('plugin_info_credit') . "</dt><dd class='credits'>" . PtoBR(propre(
305
-				$a,
306
-				$dir
307
-			)) . "</dd>\n";
308
-		}
309
-	}
310
-
311
-	if (isset($info['licence'])) {
312
-		if (is_array($info['licence'])) {
313
-			$a = formater_credits($info['licence'], ', ');
314
-		} // pour compat mais ne doit plus arriver
315
-		else {
316
-			$a = trim($info['licence']);
317
-		}
318
-		if ($a) {
319
-			$s .= "<dt class='licence'>" . _T('intitule_licence') . "</dt><dd class='licence'>" . PtoBR(propre(
320
-				$a,
321
-				$dir
322
-			)) . "</dd>\n";
323
-		}
324
-	}
325
-
326
-	$s = "<dl class='description'>$s</dl>";
327
-
328
-	//
329
-	// Ajouter les infos techniques
330
-	//
331
-	$infotech = [];
332
-
333
-	$version = '<dt>' . _T('version') . '</dt><dd>' . $info['version'];
334
-	// Version VCS
335
-	if ($vcs = version_vcs_courante($dir_plugins . $plug_file)) {
336
-		$version .= ' ' . $vcs;
337
-	}
338
-	$version .= '</dd>';
339
-	$infotech[] = $version;
340
-	$infotech[] = '<dt>' . _T('repertoire_plugins') . '</dt><dd>' . joli_repertoire("$dir_plugins$plug_file") . '</dd>';
341
-	// source zip le cas echeant
342
-	$infotech[] = (lire_fichier($dir_plugins . $plug_file . '/install.log', $log) && preg_match(',^source:(.*)$,m', $log, $r))
343
-		? '<dt>' . _T('plugin_source') . '</dt><dd>' . trim($r[1]) . '</dd>'
344
-		: '';
345
-
346
-	$infotech[] = !$info['necessite'] ? '' :
347
-		('<dt>' . _T('plugin_info_necessite') . '</dt><dd>' . join(
348
-			' ',
349
-			array_map('array_shift', $info['necessite'])
350
-		) . '</dd>');
351
-
352
-	$s .= "<dl class='tech'>"
353
-		. join('', $infotech)
354
-		. '</dl>';
355
-
356
-
357
-	return $s;
263
+    $log = null;
264
+    if (!$dir_plugins) {
265
+        $dir_plugins = _DIR_PLUGINS;
266
+    }
267
+
268
+    $prefix = $info['prefix'];
269
+    $dir = "$dir_plugins$plug_file/lang/paquet-$prefix";
270
+
271
+    $s = '';
272
+    // TODO: le traiter_multi ici n'est pas beau
273
+    // cf. description du plugin/_stable_/ortho/plugin.xml
274
+    // concerne les anciens plugin.xml donc on devrait plus en avoir besoin
275
+    $description = '';
276
+    if (isset($info['description'])) {
277
+        $description = plugin_propre($info['description'], $dir);
278
+    }
279
+
280
+    if (
281
+        isset($info['documentation']) && ($lien = $info['documentation'])
282
+    ) {
283
+        $description .= "<p><em class='site'><a href='$lien' class='spip_out'>" . _T('en_savoir_plus') . '</a></em></p>';
284
+    }
285
+    $s .= "<dd class='desc'>" . $description . "</dd>\n";
286
+
287
+    if (isset($info['auteur'])) {
288
+        if (is_array($info['auteur'])) {
289
+            $a = formater_credits($info['auteur'], ', ');
290
+        } // pour compat mais ne doit plus arriver
291
+        else {
292
+            $a = trim($info['auteur']);
293
+        }
294
+        if ($a) {
295
+            $s .= "<dt class='auteurs'>" . _T('public:par_auteur') . "</dt><dd class='auteurs'>" . PtoBR(propre(
296
+                $a,
297
+                $dir
298
+            )) . "</dd>\n";
299
+        }
300
+    }
301
+
302
+    if (isset($info['credit'])) {
303
+        if ($a = formater_credits($info['credit'], ', ')) {
304
+            $s .= "<dt class='credits'>" . _T('plugin_info_credit') . "</dt><dd class='credits'>" . PtoBR(propre(
305
+                $a,
306
+                $dir
307
+            )) . "</dd>\n";
308
+        }
309
+    }
310
+
311
+    if (isset($info['licence'])) {
312
+        if (is_array($info['licence'])) {
313
+            $a = formater_credits($info['licence'], ', ');
314
+        } // pour compat mais ne doit plus arriver
315
+        else {
316
+            $a = trim($info['licence']);
317
+        }
318
+        if ($a) {
319
+            $s .= "<dt class='licence'>" . _T('intitule_licence') . "</dt><dd class='licence'>" . PtoBR(propre(
320
+                $a,
321
+                $dir
322
+            )) . "</dd>\n";
323
+        }
324
+    }
325
+
326
+    $s = "<dl class='description'>$s</dl>";
327
+
328
+    //
329
+    // Ajouter les infos techniques
330
+    //
331
+    $infotech = [];
332
+
333
+    $version = '<dt>' . _T('version') . '</dt><dd>' . $info['version'];
334
+    // Version VCS
335
+    if ($vcs = version_vcs_courante($dir_plugins . $plug_file)) {
336
+        $version .= ' ' . $vcs;
337
+    }
338
+    $version .= '</dd>';
339
+    $infotech[] = $version;
340
+    $infotech[] = '<dt>' . _T('repertoire_plugins') . '</dt><dd>' . joli_repertoire("$dir_plugins$plug_file") . '</dd>';
341
+    // source zip le cas echeant
342
+    $infotech[] = (lire_fichier($dir_plugins . $plug_file . '/install.log', $log) && preg_match(',^source:(.*)$,m', $log, $r))
343
+        ? '<dt>' . _T('plugin_source') . '</dt><dd>' . trim($r[1]) . '</dd>'
344
+        : '';
345
+
346
+    $infotech[] = !$info['necessite'] ? '' :
347
+        ('<dt>' . _T('plugin_info_necessite') . '</dt><dd>' . join(
348
+            ' ',
349
+            array_map('array_shift', $info['necessite'])
350
+        ) . '</dd>');
351
+
352
+    $s .= "<dl class='tech'>"
353
+        . join('', $infotech)
354
+        . '</dl>';
355
+
356
+
357
+    return $s;
358 358
 }
359 359
 
360 360
 function formater_credits($infos, $sep = ', ') {
361
-	$texte = '';
362
-
363
-	foreach ($infos as $_credit) {
364
-		if ($texte) {
365
-			$texte .= $sep;
366
-		}
367
-		// Si le credit en cours n'est pas un array c'est donc un copyright
368
-		$texte .=
369
-			(!is_array($_credit))
370
-				? PtoBR(propre($_credit))
371
-				: ($_credit['url'] ? '<a href="' . $_credit['url'] . '">' : '') .
372
-				$_credit['nom'] .
373
-				($_credit['url'] ? '</a>' : '');
374
-	}
375
-
376
-	return $texte;
361
+    $texte = '';
362
+
363
+    foreach ($infos as $_credit) {
364
+        if ($texte) {
365
+            $texte .= $sep;
366
+        }
367
+        // Si le credit en cours n'est pas un array c'est donc un copyright
368
+        $texte .=
369
+            (!is_array($_credit))
370
+                ? PtoBR(propre($_credit))
371
+                : ($_credit['url'] ? '<a href="' . $_credit['url'] . '">' : '') .
372
+                $_credit['nom'] .
373
+                ($_credit['url'] ? '</a>' : '');
374
+    }
375
+
376
+    return $texte;
377 377
 }
Please login to merge, or discard this patch.
Spacing   +34 added lines, -35 removed lines patch added patch discarded remove patch
@@ -62,9 +62,9 @@  discard block
 block discarded – undo
62 62
 			" class='picto_err'",
63 63
 			_T('plugin_info_erreur_xml')
64 64
 		)
65
-			. "<div class='erreur'>" . join('<br >', $info['erreur']) . '</div>';
65
+			. "<div class='erreur'>".join('<br >', $info['erreur']).'</div>';
66 66
 		$checkable = false;
67
-	} elseif (isset($GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file])) {
67
+	} elseif (isset($GLOBALS['erreurs_activation_raw'][$dir_plugins.$plug_file])) {
68 68
 		$class_li .= ' error';
69 69
 		$erreur = http_img_pack(
70 70
 			'plugin-err-32.png',
@@ -72,10 +72,10 @@  discard block
 block discarded – undo
72 72
 			" class='picto_err'",
73 73
 			_T('plugin_impossible_activer', ['plugin' => $nom])
74 74
 		)
75
-			. "<div class='erreur'>" . implode(
75
+			. "<div class='erreur'>".implode(
76 76
 				'<br />',
77
-				$GLOBALS['erreurs_activation_raw'][$dir_plugins . $plug_file]
78
-			) . '</div>';
77
+				$GLOBALS['erreurs_activation_raw'][$dir_plugins.$plug_file]
78
+			).'</div>';
79 79
 	} else {
80 80
 		$cfg = $actif ? plugin_bouton_config($plug_file, $info, $dir_plugins) : '';
81 81
 		if (defined('_DEV_VERSION_SPIP_COMPAT') && !plugin_version_compatible($info['compatibilite'], $GLOBALS['spip_version_branche'])) {
@@ -92,11 +92,11 @@  discard block
 block discarded – undo
92 92
 	// numerotons les occurrences d'un meme prefix
93 93
 	$versions[$prefix] = $id = isset($versions[$prefix]) ? intval($versions[$prefix]) + 1 : '';
94 94
 
95
-	$class_li .= ($actif ? ' actif' : '') . ($expose ? ' on' : '');
95
+	$class_li .= ($actif ? ' actif' : '').($expose ? ' on' : '');
96 96
 
97 97
 	return "<li id='$prefix$id' class='$class_li'>"
98 98
 	. ((!$checkable && !$checked)
99
-		? '' : plugin_checkbox(++$id_input, $dir_plugins . $plug_file, $checked))
99
+		? '' : plugin_checkbox(++$id_input, $dir_plugins.$plug_file, $checked))
100 100
 	. plugin_resume($info, $dir_plugins, $plug_file, $url_page)
101 101
 	. $cfg
102 102
 	. $erreur
@@ -115,9 +115,9 @@  discard block
 block discarded – undo
115 115
 	// si paquet.xml fournit un squelette, le prendre
116 116
 	if (isset($infos['config']) && $infos['config']) {
117 117
 		return recuperer_fond(
118
-			"$dir$nom/" . $infos['config'],
118
+			"$dir$nom/".$infos['config'],
119 119
 			[
120
-				'script' => 'configurer_' . $prefix,
120
+				'script' => 'configurer_'.$prefix,
121 121
 				'nom' => $nom
122 122
 			]
123 123
 		);
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	return recuperer_fond(
128 128
 		'prive/squelettes/inclure/cfg',
129 129
 		[
130
-			'script' => 'configurer_' . $prefix,
130
+			'script' => 'configurer_'.$prefix,
131 131
 			'nom' => $nom
132 132
 		]
133 133
 	);
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	. "<input type='checkbox' name='s$name' id='label_$id_input'"
144 144
 	. ($actif ? " checked='checked'" : '')
145 145
 	. " class='checkbox'  value='O' />"
146
-	. "\n<label for='label_$id_input'>" . _T('activer_plugin') . '</label>'
146
+	. "\n<label for='label_$id_input'>"._T('activer_plugin').'</label>'
147 147
 	. '</div>';
148 148
 }
149 149
 
@@ -198,11 +198,11 @@  discard block
 block discarded – undo
198 198
 	. "<h3><a href='$url' rel='info'>"
199 199
 	. $nom
200 200
 	. '</a></h3>'
201
-	. " <span class='version'>" . $info['version'] . '</span>'
201
+	. " <span class='version'>".$info['version'].'</span>'
202 202
 	. " <span class='etat'> - "
203 203
 	. plugin_etat_en_clair($info['etat'])
204 204
 	. '</span>'
205
-	. "<div class='short'>" . $slogan . '</div>'
205
+	. "<div class='short'>".$slogan.'</div>'
206 206
 	. $i
207 207
 	. '</div>';
208 208
 }
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 	$text2 = _T('info_desinstaller_plugin');
218 218
 	$file = basename($plug_file);
219 219
 
220
-	return "<div class='actions'>[" .
220
+	return "<div class='actions'>[".
221 221
 	"<a href='$action'
222 222
 		onclick='return confirm(\"$text $nom ?\\n$text2\")'>"
223 223
 	. $text
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 		$etat = 'developpement';
240 240
 	}
241 241
 
242
-	return _T('plugin_etat_' . $etat);
242
+	return _T('plugin_etat_'.$etat);
243 243
 }
244 244
 
245 245
 function plugin_propre($texte, $module = '', $propre = 'propre') {
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		$module = substr($module, strlen(_DIR_RACINE));
249 249
 	}
250 250
 	if (preg_match('|^\w+_[\w_]+$|', $texte)) {
251
-		$texte = _T(($module ? "$module:" : '') . $texte, [], ['force' => false]);
251
+		$texte = _T(($module ? "$module:" : '').$texte, [], ['force' => false]);
252 252
 	}
253 253
 
254 254
 	return $propre($texte);
@@ -280,9 +280,9 @@  discard block
 block discarded – undo
280 280
 	if (
281 281
 		isset($info['documentation']) && ($lien = $info['documentation'])
282 282
 	) {
283
-		$description .= "<p><em class='site'><a href='$lien' class='spip_out'>" . _T('en_savoir_plus') . '</a></em></p>';
283
+		$description .= "<p><em class='site'><a href='$lien' class='spip_out'>"._T('en_savoir_plus').'</a></em></p>';
284 284
 	}
285
-	$s .= "<dd class='desc'>" . $description . "</dd>\n";
285
+	$s .= "<dd class='desc'>".$description."</dd>\n";
286 286
 
287 287
 	if (isset($info['auteur'])) {
288 288
 		if (is_array($info['auteur'])) {
@@ -292,19 +292,19 @@  discard block
 block discarded – undo
292 292
 			$a = trim($info['auteur']);
293 293
 		}
294 294
 		if ($a) {
295
-			$s .= "<dt class='auteurs'>" . _T('public:par_auteur') . "</dt><dd class='auteurs'>" . PtoBR(propre(
295
+			$s .= "<dt class='auteurs'>"._T('public:par_auteur')."</dt><dd class='auteurs'>".PtoBR(propre(
296 296
 				$a,
297 297
 				$dir
298
-			)) . "</dd>\n";
298
+			))."</dd>\n";
299 299
 		}
300 300
 	}
301 301
 
302 302
 	if (isset($info['credit'])) {
303 303
 		if ($a = formater_credits($info['credit'], ', ')) {
304
-			$s .= "<dt class='credits'>" . _T('plugin_info_credit') . "</dt><dd class='credits'>" . PtoBR(propre(
304
+			$s .= "<dt class='credits'>"._T('plugin_info_credit')."</dt><dd class='credits'>".PtoBR(propre(
305 305
 				$a,
306 306
 				$dir
307
-			)) . "</dd>\n";
307
+			))."</dd>\n";
308 308
 		}
309 309
 	}
310 310
 
@@ -316,10 +316,10 @@  discard block
 block discarded – undo
316 316
 			$a = trim($info['licence']);
317 317
 		}
318 318
 		if ($a) {
319
-			$s .= "<dt class='licence'>" . _T('intitule_licence') . "</dt><dd class='licence'>" . PtoBR(propre(
319
+			$s .= "<dt class='licence'>"._T('intitule_licence')."</dt><dd class='licence'>".PtoBR(propre(
320 320
 				$a,
321 321
 				$dir
322
-			)) . "</dd>\n";
322
+			))."</dd>\n";
323 323
 		}
324 324
 	}
325 325
 
@@ -330,24 +330,23 @@  discard block
 block discarded – undo
330 330
 	//
331 331
 	$infotech = [];
332 332
 
333
-	$version = '<dt>' . _T('version') . '</dt><dd>' . $info['version'];
333
+	$version = '<dt>'._T('version').'</dt><dd>'.$info['version'];
334 334
 	// Version VCS
335
-	if ($vcs = version_vcs_courante($dir_plugins . $plug_file)) {
336
-		$version .= ' ' . $vcs;
335
+	if ($vcs = version_vcs_courante($dir_plugins.$plug_file)) {
336
+		$version .= ' '.$vcs;
337 337
 	}
338 338
 	$version .= '</dd>';
339 339
 	$infotech[] = $version;
340
-	$infotech[] = '<dt>' . _T('repertoire_plugins') . '</dt><dd>' . joli_repertoire("$dir_plugins$plug_file") . '</dd>';
340
+	$infotech[] = '<dt>'._T('repertoire_plugins').'</dt><dd>'.joli_repertoire("$dir_plugins$plug_file").'</dd>';
341 341
 	// source zip le cas echeant
342
-	$infotech[] = (lire_fichier($dir_plugins . $plug_file . '/install.log', $log) && preg_match(',^source:(.*)$,m', $log, $r))
343
-		? '<dt>' . _T('plugin_source') . '</dt><dd>' . trim($r[1]) . '</dd>'
342
+	$infotech[] = (lire_fichier($dir_plugins.$plug_file.'/install.log', $log) && preg_match(',^source:(.*)$,m', $log, $r))
343
+		? '<dt>'._T('plugin_source').'</dt><dd>'.trim($r[1]).'</dd>'
344 344
 		: '';
345 345
 
346
-	$infotech[] = !$info['necessite'] ? '' :
347
-		('<dt>' . _T('plugin_info_necessite') . '</dt><dd>' . join(
346
+	$infotech[] = !$info['necessite'] ? '' : ('<dt>'._T('plugin_info_necessite').'</dt><dd>'.join(
348 347
 			' ',
349 348
 			array_map('array_shift', $info['necessite'])
350
-		) . '</dd>');
349
+		).'</dd>');
351 350
 
352 351
 	$s .= "<dl class='tech'>"
353 352
 		. join('', $infotech)
@@ -368,8 +367,8 @@  discard block
 block discarded – undo
368 367
 		$texte .=
369 368
 			(!is_array($_credit))
370 369
 				? PtoBR(propre($_credit))
371
-				: ($_credit['url'] ? '<a href="' . $_credit['url'] . '">' : '') .
372
-				$_credit['nom'] .
370
+				: ($_credit['url'] ? '<a href="'.$_credit['url'].'">' : '').
371
+				$_credit['nom'].
373 372
 				($_credit['url'] ? '</a>' : '');
374 373
 	}
375 374
 
Please login to merge, or discard this patch.
ecrire/install/etape_1.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
  */
20 20
 
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	return;
22
+    return;
23 23
 }
24 24
 
25 25
 /**
@@ -36,45 +36,45 @@  discard block
 block discarded – undo
36 36
  */
37 37
 function install_etape_1_dist() {
38 38
 
39
-	$minipage = new Installation();
40
-	echo $minipage->installDebutPage();
39
+    $minipage = new Installation();
40
+    echo $minipage->installDebutPage();
41 41
 
42
-	// stopper en cas de grosse incompatibilite de l'hebergement
43
-	tester_compatibilite_hebergement();
42
+    // stopper en cas de grosse incompatibilite de l'hebergement
43
+    tester_compatibilite_hebergement();
44 44
 
45
-	// Recuperer les anciennes donnees pour plus de facilite (si presentes)
46
-	$s = @is_readable(_FILE_CONNECT_TMP) ? analyse_fichier_connection(_FILE_CONNECT_TMP) : '';
45
+    // Recuperer les anciennes donnees pour plus de facilite (si presentes)
46
+    $s = @is_readable(_FILE_CONNECT_TMP) ? analyse_fichier_connection(_FILE_CONNECT_TMP) : '';
47 47
 
48
-	[$adresse_db, $login_db] = $s ?: ['localhost', ''];
48
+    [$adresse_db, $login_db] = $s ?: ['localhost', ''];
49 49
 
50
-	$chmod = (isset($_GET['chmod']) && preg_match(',^\d+$,', (string) $_GET['chmod'])) ?
51
-		sprintf('%04o', $_GET['chmod']) : '0777';
50
+    $chmod = (isset($_GET['chmod']) && preg_match(',^\d+$,', (string) $_GET['chmod'])) ?
51
+        sprintf('%04o', $_GET['chmod']) : '0777';
52 52
 
53
-	if (@is_readable(_FILE_CHMOD_TMP)) {
54
-		$s = @implode('', @file(_FILE_CHMOD_TMP));
55
-		if (preg_match("#define\('_SPIP_CHMOD', (.*)\)#", $s, $regs)) {
56
-			$chmod = $regs[1];
57
-		}
58
-	}
53
+    if (@is_readable(_FILE_CHMOD_TMP)) {
54
+        $s = @implode('', @file(_FILE_CHMOD_TMP));
55
+        if (preg_match("#define\('_SPIP_CHMOD', (.*)\)#", $s, $regs)) {
56
+            $chmod = $regs[1];
57
+        }
58
+    }
59 59
 
60 60
 
61
-	$db = [$adresse_db, _T('entree_base_donnee_2')];
62
-	$login = [$login_db, _T('entree_login_connexion_2')];
63
-	$pass = ['', _T('entree_mot_passe_2')];
61
+    $db = [$adresse_db, _T('entree_base_donnee_2')];
62
+    $login = [$login_db, _T('entree_login_connexion_2')];
63
+    $pass = ['', _T('entree_mot_passe_2')];
64 64
 
65
-	$predef = [
66
-		defined('_INSTALL_SERVER_DB') ? _INSTALL_SERVER_DB : '',
67
-		defined('_INSTALL_HOST_DB'),
68
-		defined('_INSTALL_USER_DB'),
69
-		defined('_INSTALL_PASS_DB')
70
-	];
65
+    $predef = [
66
+        defined('_INSTALL_SERVER_DB') ? _INSTALL_SERVER_DB : '',
67
+        defined('_INSTALL_HOST_DB'),
68
+        defined('_INSTALL_USER_DB'),
69
+        defined('_INSTALL_PASS_DB')
70
+    ];
71 71
 
72 72
 
73
-	echo info_progression_etape(1, 'etape_', 'install/');
73
+    echo info_progression_etape(1, 'etape_', 'install/');
74 74
 
75
-	// ces deux chaines de langues doivent etre reecrites
75
+    // ces deux chaines de langues doivent etre reecrites
76 76
 #	echo info_etape(_T('info_connexion_mysql'), _T('texte_connexion_mysql').aide ("install1", true));
77
-	echo info_etape(_T('info_connexion_base_donnee'));
78
-	echo install_connexion_form($db, $login, $pass, $predef, "\n<input type='hidden' name='chmod' value='$chmod' />", 2);
79
-	echo $minipage->installFinPage();
77
+    echo info_etape(_T('info_connexion_base_donnee'));
78
+    echo install_connexion_form($db, $login, $pass, $predef, "\n<input type='hidden' name='chmod' value='$chmod' />", 2);
79
+    echo $minipage->installFinPage();
80 80
 }
Please login to merge, or discard this patch.
ecrire/install/etape_fin.php 2 patches
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 \***************************************************************************/
13 13
 
14 14
 if (!defined('_ECRIRE_INC_VERSION')) {
15
-	return;
15
+    return;
16 16
 }
17 17
 
18 18
 include_spip('inc/headers');
@@ -21,61 +21,61 @@  discard block
 block discarded – undo
21 21
 // Mise en place des fichiers de configuration si ce n'est fait
22 22
 
23 23
 function install_etape_fin_dist() {
24
-	ecrire_acces();
24
+    ecrire_acces();
25 25
 
26
-	$f = str_replace(_FILE_TMP_SUFFIX, '.php', (string) _FILE_CHMOD_TMP);
27
-	if (file_exists(_FILE_CHMOD_TMP) && !@rename(_FILE_CHMOD_TMP, $f) && @copy(_FILE_CHMOD_TMP, $f)) {
28
-		spip_unlink(_FILE_CHMOD_TMP);
29
-	}
26
+    $f = str_replace(_FILE_TMP_SUFFIX, '.php', (string) _FILE_CHMOD_TMP);
27
+    if (file_exists(_FILE_CHMOD_TMP) && !@rename(_FILE_CHMOD_TMP, $f) && @copy(_FILE_CHMOD_TMP, $f)) {
28
+        spip_unlink(_FILE_CHMOD_TMP);
29
+    }
30 30
 
31
-	$f = str_replace(_FILE_TMP_SUFFIX, '.php', (string) _FILE_CONNECT_TMP);
32
-	if (file_exists(_FILE_CONNECT_TMP)) {
33
-		spip_log("renomme $f");
34
-		if (!@rename(_FILE_CONNECT_TMP, $f) && @copy(_FILE_CONNECT_TMP, $f)) {
35
-			@spip_unlink(_FILE_CONNECT_TMP);
36
-		}
37
-	}
31
+    $f = str_replace(_FILE_TMP_SUFFIX, '.php', (string) _FILE_CONNECT_TMP);
32
+    if (file_exists(_FILE_CONNECT_TMP)) {
33
+        spip_log("renomme $f");
34
+        if (!@rename(_FILE_CONNECT_TMP, $f) && @copy(_FILE_CONNECT_TMP, $f)) {
35
+            @spip_unlink(_FILE_CONNECT_TMP);
36
+        }
37
+    }
38 38
 
39
-	// creer le repertoire cache, qui sert partout !
40
-	// deja fait en etape 4 en principe, on garde au cas ou
41
-	if (!@file_exists(_DIR_CACHE)) {
42
-		$rep = preg_replace(',' . _DIR_TMP . ',', '', (string) _DIR_CACHE);
43
-		$rep = sous_repertoire(_DIR_TMP, $rep, true, true);
44
-	}
39
+    // creer le repertoire cache, qui sert partout !
40
+    // deja fait en etape 4 en principe, on garde au cas ou
41
+    if (!@file_exists(_DIR_CACHE)) {
42
+        $rep = preg_replace(',' . _DIR_TMP . ',', '', (string) _DIR_CACHE);
43
+        $rep = sous_repertoire(_DIR_TMP, $rep, true, true);
44
+    }
45 45
 
46
-	// Verifier la securite des htaccess
47
-	// Si elle ne fonctionne pas, prevenir
48
-	$msg = install_verifier_htaccess();
49
-	if ($msg) {
50
-		$cible = _T('public:accueil_site');
51
-		$cible = generer_form_ecrire('accueil', '', '', $cible);
52
-		$minipage = new Installation();
53
-		echo $minipage->page($msg . $cible);
54
-		// ok, deboucher dans l'espace prive
55
-	} else {
56
-		redirige_url_ecrire('accueil');
57
-	}
46
+    // Verifier la securite des htaccess
47
+    // Si elle ne fonctionne pas, prevenir
48
+    $msg = install_verifier_htaccess();
49
+    if ($msg) {
50
+        $cible = _T('public:accueil_site');
51
+        $cible = generer_form_ecrire('accueil', '', '', $cible);
52
+        $minipage = new Installation();
53
+        echo $minipage->page($msg . $cible);
54
+        // ok, deboucher dans l'espace prive
55
+    } else {
56
+        redirige_url_ecrire('accueil');
57
+    }
58 58
 }
59 59
 
60 60
 function install_verifier_htaccess() {
61
-	if (
62
-		verifier_htaccess(_DIR_TMP, true)
63
-		&& verifier_htaccess(_DIR_CONNECT, true)
64
-		&& verifier_htaccess(_DIR_VENDOR, true)
65
-	) {
66
-		return '';
67
-	}
61
+    if (
62
+        verifier_htaccess(_DIR_TMP, true)
63
+        && verifier_htaccess(_DIR_CONNECT, true)
64
+        && verifier_htaccess(_DIR_VENDOR, true)
65
+    ) {
66
+        return '';
67
+    }
68 68
 
69
-	$titre = _T('htaccess_inoperant');
69
+    $titre = _T('htaccess_inoperant');
70 70
 
71
-	$averti = _T(
72
-		'htaccess_a_simuler',
73
-		[
74
-			'htaccess' => '<tt>' . _ACCESS_FILE_NAME . '</tt>',
75
-			'constantes' => '<tt>_DIR_TMP &amp; _DIR_CONNECT</tt>',
76
-			'document_root' => '<tt>' . $_SERVER['DOCUMENT_ROOT'] . '</tt>'
77
-		]
78
-	);
71
+    $averti = _T(
72
+        'htaccess_a_simuler',
73
+        [
74
+            'htaccess' => '<tt>' . _ACCESS_FILE_NAME . '</tt>',
75
+            'constantes' => '<tt>_DIR_TMP &amp; _DIR_CONNECT</tt>',
76
+            'document_root' => '<tt>' . $_SERVER['DOCUMENT_ROOT'] . '</tt>'
77
+        ]
78
+    );
79 79
 
80
-	return "<div class='error'><h3>$titre</h3><p>$averti</p></div>";
80
+    return "<div class='error'><h3>$titre</h3><p>$averti</p></div>";
81 81
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
 	// creer le repertoire cache, qui sert partout !
40 40
 	// deja fait en etape 4 en principe, on garde au cas ou
41 41
 	if (!@file_exists(_DIR_CACHE)) {
42
-		$rep = preg_replace(',' . _DIR_TMP . ',', '', (string) _DIR_CACHE);
42
+		$rep = preg_replace(','._DIR_TMP.',', '', (string) _DIR_CACHE);
43 43
 		$rep = sous_repertoire(_DIR_TMP, $rep, true, true);
44 44
 	}
45 45
 
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 		$cible = _T('public:accueil_site');
51 51
 		$cible = generer_form_ecrire('accueil', '', '', $cible);
52 52
 		$minipage = new Installation();
53
-		echo $minipage->page($msg . $cible);
53
+		echo $minipage->page($msg.$cible);
54 54
 		// ok, deboucher dans l'espace prive
55 55
 	} else {
56 56
 		redirige_url_ecrire('accueil');
@@ -71,9 +71,9 @@  discard block
 block discarded – undo
71 71
 	$averti = _T(
72 72
 		'htaccess_a_simuler',
73 73
 		[
74
-			'htaccess' => '<tt>' . _ACCESS_FILE_NAME . '</tt>',
74
+			'htaccess' => '<tt>'._ACCESS_FILE_NAME.'</tt>',
75 75
 			'constantes' => '<tt>_DIR_TMP &amp; _DIR_CONNECT</tt>',
76
-			'document_root' => '<tt>' . $_SERVER['DOCUMENT_ROOT'] . '</tt>'
76
+			'document_root' => '<tt>'.$_SERVER['DOCUMENT_ROOT'].'</tt>'
77 77
 		]
78 78
 	);
79 79
 
Please login to merge, or discard this patch.
ecrire/install/etape_.php 2 patches
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  */
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 /**
@@ -27,20 +27,20 @@  discard block
 block discarded – undo
27 27
  * @uses info_copyright()
28 28
  **/
29 29
 function install_etape__dist() {
30
-	utiliser_langue_visiteur();
31
-	$menu_langues = menu_langues('var_lang_ecrire');
32
-	if (!$menu_langues) {
33
-		redirige_url_ecrire('install', 'etape=chmod');
34
-	} else {
35
-		include_spip('inc/presentation'); // pour info_copyright
30
+    utiliser_langue_visiteur();
31
+    $menu_langues = menu_langues('var_lang_ecrire');
32
+    if (!$menu_langues) {
33
+        redirige_url_ecrire('install', 'etape=chmod');
34
+    } else {
35
+        include_spip('inc/presentation'); // pour info_copyright
36 36
 
37
-		$res = "<div class='petit-centre'><img alt='SPIP' class='logo' src='" . chemin_image('logo-spip.png') . "' />\n" .
38
-			"<p class='small'>" . info_copyright() . "</p></div>\n" .
39
-			'<p>' . _T('install_select_langue') . '</p>' .
40
-			'<div>' . $menu_langues . "</div>\n" .
41
-			generer_form_ecrire('install', "<input type='hidden' name='etape' value='chmod' />" . bouton_suivant());
37
+        $res = "<div class='petit-centre'><img alt='SPIP' class='logo' src='" . chemin_image('logo-spip.png') . "' />\n" .
38
+            "<p class='small'>" . info_copyright() . "</p></div>\n" .
39
+            '<p>' . _T('install_select_langue') . '</p>' .
40
+            '<div>' . $menu_langues . "</div>\n" .
41
+            generer_form_ecrire('install', "<input type='hidden' name='etape' value='chmod' />" . bouton_suivant());
42 42
 
43
-		$minipage = new Installation();
44
-		echo $minipage->page($res);
45
-	}
43
+        $minipage = new Installation();
44
+        echo $minipage->page($res);
45
+    }
46 46
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -34,11 +34,11 @@
 block discarded – undo
34 34
 	} else {
35 35
 		include_spip('inc/presentation'); // pour info_copyright
36 36
 
37
-		$res = "<div class='petit-centre'><img alt='SPIP' class='logo' src='" . chemin_image('logo-spip.png') . "' />\n" .
38
-			"<p class='small'>" . info_copyright() . "</p></div>\n" .
39
-			'<p>' . _T('install_select_langue') . '</p>' .
40
-			'<div>' . $menu_langues . "</div>\n" .
41
-			generer_form_ecrire('install', "<input type='hidden' name='etape' value='chmod' />" . bouton_suivant());
37
+		$res = "<div class='petit-centre'><img alt='SPIP' class='logo' src='".chemin_image('logo-spip.png')."' />\n".
38
+			"<p class='small'>".info_copyright()."</p></div>\n".
39
+			'<p>'._T('install_select_langue').'</p>'.
40
+			'<div>'.$menu_langues."</div>\n".
41
+			generer_form_ecrire('install', "<input type='hidden' name='etape' value='chmod' />".bouton_suivant());
42 42
 
43 43
 		$minipage = new Installation();
44 44
 		echo $minipage->page($res);
Please login to merge, or discard this patch.
ecrire/install/etape_2.php 2 patches
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -12,167 +12,167 @@
 block discarded – undo
12 12
 \***************************************************************************/
13 13
 
14 14
 if (!defined('_ECRIRE_INC_VERSION')) {
15
-	return;
15
+    return;
16 16
 }
17 17
 
18 18
 include_spip('base/abstract_sql');
19 19
 
20 20
 function install_etape_2_dist() {
21
-	$adresse_db = defined('_INSTALL_HOST_DB')
22
-		? _INSTALL_HOST_DB
23
-		: _request('adresse_db');
21
+    $adresse_db = defined('_INSTALL_HOST_DB')
22
+        ? _INSTALL_HOST_DB
23
+        : _request('adresse_db');
24 24
 
25
-	if (preg_match(',(.*):(.*),', (string) $adresse_db, $r)) {
26
-		[, $adresse_db, $port] = $r;
27
-	} else {
28
-		$port = '';
29
-	}
25
+    if (preg_match(',(.*):(.*),', (string) $adresse_db, $r)) {
26
+        [, $adresse_db, $port] = $r;
27
+    } else {
28
+        $port = '';
29
+    }
30 30
 
31
-	$login_db = defined('_INSTALL_USER_DB')
32
-		? _INSTALL_USER_DB
33
-		: _request('login_db');
31
+    $login_db = defined('_INSTALL_USER_DB')
32
+        ? _INSTALL_USER_DB
33
+        : _request('login_db');
34 34
 
35
-	$pass_db = defined('_INSTALL_PASS_DB')
36
-		? _INSTALL_PASS_DB
37
-		: _request('pass_db');
35
+    $pass_db = defined('_INSTALL_PASS_DB')
36
+        ? _INSTALL_PASS_DB
37
+        : _request('pass_db');
38 38
 
39
-	$server_db = defined('_INSTALL_SERVER_DB')
40
-		? _INSTALL_SERVER_DB
41
-		: _request('server_db');
39
+    $server_db = defined('_INSTALL_SERVER_DB')
40
+        ? _INSTALL_SERVER_DB
41
+        : _request('server_db');
42 42
 
43
-	$name_db = defined('_INSTALL_NAME_DB')
44
-		? _INSTALL_NAME_DB
45
-		: '';
43
+    $name_db = defined('_INSTALL_NAME_DB')
44
+        ? _INSTALL_NAME_DB
45
+        : '';
46 46
 
47
-	$chmod = _request('chmod');
47
+    $chmod = _request('chmod');
48 48
 
49
-	$link = spip_connect_db($adresse_db, $port, $login_db, $pass_db, $name_db, $server_db);
50
-	$GLOBALS['connexions'][$server_db] = $link;
49
+    $link = spip_connect_db($adresse_db, $port, $login_db, $pass_db, $name_db, $server_db);
50
+    $GLOBALS['connexions'][$server_db] = $link;
51 51
 
52
-	$GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
53
-		= $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
52
+    $GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
53
+        = $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
54 54
 
55
-	$minipage = new Installation();
56
-	echo $minipage->installDebutPage();
55
+    $minipage = new Installation();
56
+    echo $minipage->installDebutPage();
57 57
 
58 58
 
59 59
 // prenons toutes les dispositions possibles pour que rien ne s'affiche !
60 60
 
61
-	/*
61
+    /*
62 62
 	 * /!\ sqlite3/PDO : erreur sur join(', ', $link)
63 63
 	 * L'objet PDO ne peut pas etre transformee en chaine
64 64
 	 * Un echo $link ne fonctionne pas non plus
65 65
 	 * Il faut utiliser par exemple print_r($link)
66 66
 	 */
67
-	//echo "\n<!--\n", join(', ', $link), " $login_db ";
68
-	$db_connect = 0; // revoirfunction_exists($ferrno) ? $ferrno() : 0;
69
-	//echo join(', ', $GLOBALS['connexions'][$server_db]);
70
-	//echo "\n-->\n";
67
+    //echo "\n<!--\n", join(', ', $link), " $login_db ";
68
+    $db_connect = 0; // revoirfunction_exists($ferrno) ? $ferrno() : 0;
69
+    //echo join(', ', $GLOBALS['connexions'][$server_db]);
70
+    //echo "\n-->\n";
71 71
 
72
-	if (($db_connect == '0') && $link) {
73
-		echo "<div class='success'><b>" . _T('info_connexion_ok') . '</b></div>';
74
-		echo info_progression_etape(2, 'etape_', 'install/');
72
+    if (($db_connect == '0') && $link) {
73
+        echo "<div class='success'><b>" . _T('info_connexion_ok') . '</b></div>';
74
+        echo info_progression_etape(2, 'etape_', 'install/');
75 75
 
76
-		echo info_etape(_T('menu_aide_installation_choix_base') . aider('install2', true));
76
+        echo info_etape(_T('menu_aide_installation_choix_base') . aider('install2', true));
77 77
 
78
-		echo "\n", '<!-- ', sql_version($server_db), ' -->';
79
-		[$checked, $res] = install_etape_2_bases($login_db, $server_db);
78
+        echo "\n", '<!-- ', sql_version($server_db), ' -->';
79
+        [$checked, $res] = install_etape_2_bases($login_db, $server_db);
80 80
 
81
-		$hidden = (defined('_SPIP_CHMOD')
82
-				? ''
83
-				: ("\n<input type='hidden' name='chmod' value='" . spip_htmlspecialchars($chmod) . "' />"))
84
-			. predef_ou_cache($adresse_db . ($port ? ':' . $port : ''), $login_db, $pass_db, $server_db);
81
+        $hidden = (defined('_SPIP_CHMOD')
82
+                ? ''
83
+                : ("\n<input type='hidden' name='chmod' value='" . spip_htmlspecialchars($chmod) . "' />"))
84
+            . predef_ou_cache($adresse_db . ($port ? ':' . $port : ''), $login_db, $pass_db, $server_db);
85 85
 
86
-		echo install_etape_2_form($hidden, $checked, $res, 3);
87
-	} else {
88
-		echo info_progression_etape(1, 'etape_', 'install/', true);
86
+        echo install_etape_2_form($hidden, $checked, $res, 3);
87
+    } else {
88
+        echo info_progression_etape(1, 'etape_', 'install/', true);
89 89
 
90
-		echo "<div class='error'>";
91
-		echo info_etape(_T('info_connexion_base'));
92
-		echo '<h3>' . _T('avis_connexion_echec_1') . '</h3>';
93
-		echo '<p>' . _T('avis_connexion_echec_2') . '</p>';
90
+        echo "<div class='error'>";
91
+        echo info_etape(_T('info_connexion_base'));
92
+        echo '<h3>' . _T('avis_connexion_echec_1') . '</h3>';
93
+        echo '<p>' . _T('avis_connexion_echec_2') . '</p>';
94 94
 
95
-		echo "<p style='font-size: small;'>",
96
-		_T('avis_connexion_echec_3'),
97
-		'</p></div>';
98
-	}
95
+        echo "<p style='font-size: small;'>",
96
+        _T('avis_connexion_echec_3'),
97
+        '</p></div>';
98
+    }
99 99
 
100
-	echo $minipage->installFinPage();
100
+    echo $minipage->installFinPage();
101 101
 }
102 102
 
103 103
 // Liste les bases accessibles,
104 104
 // avec une heuristique pour preselectionner la plus probable
105 105
 
106 106
 function install_etape_2_bases($login_db, $server_db) {
107
-	$res = install_etape_liste_bases($server_db, $login_db);
108
-	if ($res) {
109
-		[$checked, $bases] = $res;
110
-
111
-		return [
112
-			$checked,
113
-			"<label for='choix_db'><b>"
114
-			. _T('texte_choix_base_2')
115
-			. '</b><br />'
116
-			. _T('texte_choix_base_3')
117
-			. '</label>'
118
-			. "<ul>\n<li>"
119
-			. implode("</li>\n<li>", $bases)
120
-			. "</li>\n</ul><p>"
121
-			. _T('info_ou')
122
-			. ' '
123
-		];
124
-	}
125
-	$res = '<b>' . _T('avis_lecture_noms_bases_1') . '</b>
107
+    $res = install_etape_liste_bases($server_db, $login_db);
108
+    if ($res) {
109
+        [$checked, $bases] = $res;
110
+
111
+        return [
112
+            $checked,
113
+            "<label for='choix_db'><b>"
114
+            . _T('texte_choix_base_2')
115
+            . '</b><br />'
116
+            . _T('texte_choix_base_3')
117
+            . '</label>'
118
+            . "<ul>\n<li>"
119
+            . implode("</li>\n<li>", $bases)
120
+            . "</li>\n</ul><p>"
121
+            . _T('info_ou')
122
+            . ' '
123
+        ];
124
+    }
125
+    $res = '<b>' . _T('avis_lecture_noms_bases_1') . '</b>
126 126
 		' . _T('avis_lecture_noms_bases_2') . '<p>';
127 127
 
128
-	$checked = false;
129
-	if ($login_db) {
130
-		// Si un login comporte un point, le nom de la base est plus
131
-		// probablement le login sans le point -- testons pour savoir
132
-		$test_base = $login_db;
133
-		$ok = sql_selectdb($test_base, $server_db);
134
-		$test_base2 = str_replace('.', '_', (string) $test_base);
135
-		if (sql_selectdb($test_base2, $server_db)) {
136
-			$test_base = $test_base2;
137
-			$ok = true;
138
-		}
139
-
140
-		if ($ok) {
141
-			$res .= _T('avis_lecture_noms_bases_3')
142
-				. '<ul>'
143
-				. '<li><input name="choix_db" value="' . $test_base . "\" type='radio' id='stand' checked='checked' />"
144
-				. "<label for='stand'>" . $test_base . "</label></li>\n"
145
-				. '</ul>'
146
-				. '<p>' . _T('info_ou') . ' ';
147
-			$checked = true;
148
-		}
149
-	}
150
-
151
-	return [$checked, $res];
128
+    $checked = false;
129
+    if ($login_db) {
130
+        // Si un login comporte un point, le nom de la base est plus
131
+        // probablement le login sans le point -- testons pour savoir
132
+        $test_base = $login_db;
133
+        $ok = sql_selectdb($test_base, $server_db);
134
+        $test_base2 = str_replace('.', '_', (string) $test_base);
135
+        if (sql_selectdb($test_base2, $server_db)) {
136
+            $test_base = $test_base2;
137
+            $ok = true;
138
+        }
139
+
140
+        if ($ok) {
141
+            $res .= _T('avis_lecture_noms_bases_3')
142
+                . '<ul>'
143
+                . '<li><input name="choix_db" value="' . $test_base . "\" type='radio' id='stand' checked='checked' />"
144
+                . "<label for='stand'>" . $test_base . "</label></li>\n"
145
+                . '</ul>'
146
+                . '<p>' . _T('info_ou') . ' ';
147
+            $checked = true;
148
+        }
149
+    }
150
+
151
+    return [$checked, $res];
152 152
 }
153 153
 
154 154
 function install_etape_2_form($hidden, $checked, $res, $etape) {
155
-	return generer_form_ecrire('install', (
156
-		"\n<input type='hidden' name='etape' value='$etape' />"
157
-		. $hidden
158
-		. (defined('_INSTALL_NAME_DB')
159
-			? '<h3>' . _T('install_nom_base_hebergeur') . ' <tt>' . _INSTALL_NAME_DB . '</tt>' . '</h3>'
160
-			: "\n<fieldset><legend>" . _T('texte_choix_base_1') . "</legend>\n"
161
-			. $res
162
-			. "\n<input name=\"choix_db\" value=\"new_spip\" type='radio' id='nou'"
163
-			. ($checked ? '' : " checked='checked'")
164
-			. " />\n<label for='nou'>" . _T('info_creer_base') . "</label></p>\n<p>"
165
-			. "\n<input type='text' name='table_new' class='text' value=\"spip\" size='20' /></p></fieldset>\n"
166
-		)
167
-
168
-		. ((defined('_INSTALL_TABLE_PREFIX') || $GLOBALS['table_prefix'] != 'spip')
169
-			? '<h3>' . _T('install_table_prefix_hebergeur') . '  <tt>' . $GLOBALS['table_prefix'] . '</tt>' . '</h3>'
170
-			: '<fieldset><legend>' . _T('texte_choix_table_prefix') . "</legend>\n"
171
-			. "<p><label for='table_prefix'>" . _T('info_table_prefix') . '</label></p><p>'
172
-			. "\n<input type='text' id='tprefix' name='tprefix' class='text' value='"
173
-			. 'spip' # valeur par defaut
174
-			. "' size='20' /></p></fieldset>"
175
-		)
176
-
177
-		. bouton_suivant()));
155
+    return generer_form_ecrire('install', (
156
+        "\n<input type='hidden' name='etape' value='$etape' />"
157
+        . $hidden
158
+        . (defined('_INSTALL_NAME_DB')
159
+            ? '<h3>' . _T('install_nom_base_hebergeur') . ' <tt>' . _INSTALL_NAME_DB . '</tt>' . '</h3>'
160
+            : "\n<fieldset><legend>" . _T('texte_choix_base_1') . "</legend>\n"
161
+            . $res
162
+            . "\n<input name=\"choix_db\" value=\"new_spip\" type='radio' id='nou'"
163
+            . ($checked ? '' : " checked='checked'")
164
+            . " />\n<label for='nou'>" . _T('info_creer_base') . "</label></p>\n<p>"
165
+            . "\n<input type='text' name='table_new' class='text' value=\"spip\" size='20' /></p></fieldset>\n"
166
+        )
167
+
168
+        . ((defined('_INSTALL_TABLE_PREFIX') || $GLOBALS['table_prefix'] != 'spip')
169
+            ? '<h3>' . _T('install_table_prefix_hebergeur') . '  <tt>' . $GLOBALS['table_prefix'] . '</tt>' . '</h3>'
170
+            : '<fieldset><legend>' . _T('texte_choix_table_prefix') . "</legend>\n"
171
+            . "<p><label for='table_prefix'>" . _T('info_table_prefix') . '</label></p><p>'
172
+            . "\n<input type='text' id='tprefix' name='tprefix' class='text' value='"
173
+            . 'spip' # valeur par defaut
174
+            . "' size='20' /></p></fieldset>"
175
+        )
176
+
177
+        . bouton_suivant()));
178 178
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 	$GLOBALS['connexions'][$server_db] = $link;
51 51
 
52 52
 	$GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
53
-		= $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
53
+		= $GLOBALS['spip_'.$server_db.'_functions_'.$GLOBALS['spip_sql_version']];
54 54
 
55 55
 	$minipage = new Installation();
56 56
 	echo $minipage->installDebutPage();
@@ -70,18 +70,18 @@  discard block
 block discarded – undo
70 70
 	//echo "\n-->\n";
71 71
 
72 72
 	if (($db_connect == '0') && $link) {
73
-		echo "<div class='success'><b>" . _T('info_connexion_ok') . '</b></div>';
73
+		echo "<div class='success'><b>"._T('info_connexion_ok').'</b></div>';
74 74
 		echo info_progression_etape(2, 'etape_', 'install/');
75 75
 
76
-		echo info_etape(_T('menu_aide_installation_choix_base') . aider('install2', true));
76
+		echo info_etape(_T('menu_aide_installation_choix_base').aider('install2', true));
77 77
 
78 78
 		echo "\n", '<!-- ', sql_version($server_db), ' -->';
79 79
 		[$checked, $res] = install_etape_2_bases($login_db, $server_db);
80 80
 
81 81
 		$hidden = (defined('_SPIP_CHMOD')
82 82
 				? ''
83
-				: ("\n<input type='hidden' name='chmod' value='" . spip_htmlspecialchars($chmod) . "' />"))
84
-			. predef_ou_cache($adresse_db . ($port ? ':' . $port : ''), $login_db, $pass_db, $server_db);
83
+				: ("\n<input type='hidden' name='chmod' value='".spip_htmlspecialchars($chmod)."' />"))
84
+			. predef_ou_cache($adresse_db.($port ? ':'.$port : ''), $login_db, $pass_db, $server_db);
85 85
 
86 86
 		echo install_etape_2_form($hidden, $checked, $res, 3);
87 87
 	} else {
@@ -89,8 +89,8 @@  discard block
 block discarded – undo
89 89
 
90 90
 		echo "<div class='error'>";
91 91
 		echo info_etape(_T('info_connexion_base'));
92
-		echo '<h3>' . _T('avis_connexion_echec_1') . '</h3>';
93
-		echo '<p>' . _T('avis_connexion_echec_2') . '</p>';
92
+		echo '<h3>'._T('avis_connexion_echec_1').'</h3>';
93
+		echo '<p>'._T('avis_connexion_echec_2').'</p>';
94 94
 
95 95
 		echo "<p style='font-size: small;'>",
96 96
 		_T('avis_connexion_echec_3'),
@@ -122,8 +122,8 @@  discard block
 block discarded – undo
122 122
 			. ' '
123 123
 		];
124 124
 	}
125
-	$res = '<b>' . _T('avis_lecture_noms_bases_1') . '</b>
126
-		' . _T('avis_lecture_noms_bases_2') . '<p>';
125
+	$res = '<b>'._T('avis_lecture_noms_bases_1').'</b>
126
+		' . _T('avis_lecture_noms_bases_2').'<p>';
127 127
 
128 128
 	$checked = false;
129 129
 	if ($login_db) {
@@ -140,10 +140,10 @@  discard block
 block discarded – undo
140 140
 		if ($ok) {
141 141
 			$res .= _T('avis_lecture_noms_bases_3')
142 142
 				. '<ul>'
143
-				. '<li><input name="choix_db" value="' . $test_base . "\" type='radio' id='stand' checked='checked' />"
144
-				. "<label for='stand'>" . $test_base . "</label></li>\n"
143
+				. '<li><input name="choix_db" value="'.$test_base."\" type='radio' id='stand' checked='checked' />"
144
+				. "<label for='stand'>".$test_base."</label></li>\n"
145 145
 				. '</ul>'
146
-				. '<p>' . _T('info_ou') . ' ';
146
+				. '<p>'._T('info_ou').' ';
147 147
 			$checked = true;
148 148
 		}
149 149
 	}
@@ -156,19 +156,19 @@  discard block
 block discarded – undo
156 156
 		"\n<input type='hidden' name='etape' value='$etape' />"
157 157
 		. $hidden
158 158
 		. (defined('_INSTALL_NAME_DB')
159
-			? '<h3>' . _T('install_nom_base_hebergeur') . ' <tt>' . _INSTALL_NAME_DB . '</tt>' . '</h3>'
160
-			: "\n<fieldset><legend>" . _T('texte_choix_base_1') . "</legend>\n"
159
+			? '<h3>'._T('install_nom_base_hebergeur').' <tt>'._INSTALL_NAME_DB.'</tt>'.'</h3>'
160
+			: "\n<fieldset><legend>"._T('texte_choix_base_1')."</legend>\n"
161 161
 			. $res
162 162
 			. "\n<input name=\"choix_db\" value=\"new_spip\" type='radio' id='nou'"
163 163
 			. ($checked ? '' : " checked='checked'")
164
-			. " />\n<label for='nou'>" . _T('info_creer_base') . "</label></p>\n<p>"
164
+			. " />\n<label for='nou'>"._T('info_creer_base')."</label></p>\n<p>"
165 165
 			. "\n<input type='text' name='table_new' class='text' value=\"spip\" size='20' /></p></fieldset>\n"
166 166
 		)
167 167
 
168 168
 		. ((defined('_INSTALL_TABLE_PREFIX') || $GLOBALS['table_prefix'] != 'spip')
169
-			? '<h3>' . _T('install_table_prefix_hebergeur') . '  <tt>' . $GLOBALS['table_prefix'] . '</tt>' . '</h3>'
170
-			: '<fieldset><legend>' . _T('texte_choix_table_prefix') . "</legend>\n"
171
-			. "<p><label for='table_prefix'>" . _T('info_table_prefix') . '</label></p><p>'
169
+			? '<h3>'._T('install_table_prefix_hebergeur').'  <tt>'.$GLOBALS['table_prefix'].'</tt>'.'</h3>'
170
+			: '<fieldset><legend>'._T('texte_choix_table_prefix')."</legend>\n"
171
+			. "<p><label for='table_prefix'>"._T('info_table_prefix').'</label></p><p>'
172 172
 			. "\n<input type='text' id='tprefix' name='tprefix' class='text' value='"
173 173
 			. 'spip' # valeur par defaut
174 174
 			. "' size='20' /></p></fieldset>"
Please login to merge, or discard this patch.
ecrire/src/Chiffrer/SpipCles.php 2 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -13,169 +13,169 @@
 block discarded – undo
13 13
 
14 14
 /** Gestion des clés d’authentification / chiffrement de SPIP */
15 15
 final class SpipCles {
16
-	private static array $instances = [];
17
-
18
-	private string $file = _DIR_ETC . 'cles.php';
19
-	private readonly Cles $cles;
20
-
21
-	public static function instance(string $file = ''): self {
22
-		if (empty(self::$instances[$file])) {
23
-			self::$instances[$file] = new self($file);
24
-		}
25
-		return self::$instances[$file];
26
-	}
27
-
28
-	/**
29
-	 * Retourne le secret du site (shorthand)
30
-	 * @uses self::getSecretSite()
31
-	 */
32
-	public static function secret_du_site(): ?string {
33
-		return (self::instance())->getSecretSite();
34
-	}
35
-
36
-	private function __construct(string $file = '') {
37
-		if ($file) {
38
-			$this->file = $file;
39
-		}
40
-		$this->cles = new Cles($this->read());
41
-	}
42
-
43
-	/**
44
-	 * Renvoyer le secret du site
45
-	 *
46
-	 * Le secret du site doit rester aussi secret que possible, et est eternel
47
-	 * On ne doit pas l'exporter
48
-	 *
49
-	 * Le secret est partagé entre une clé disque et une clé bdd
50
-	 *
51
-	 * @return string
52
-	 */
53
-	public function getSecretSite(bool $autoInit = true): ?string {
54
-		$key = $this->getKey('secret_du_site', $autoInit);
55
-		$meta = $this->getMetaKey('secret_du_site', $autoInit);
56
-		// conserve la même longeur.
57
-		return $key ^ $meta;
58
-	}
59
-
60
-	/** Renvoyer le secret des authentifications */
61
-	public function getSecretAuth(bool $autoInit = false): ?string {
62
-		return $this->getKey('secret_des_auth', $autoInit);
63
-	}
64
-	public function save(): bool {
65
-		return ecrire_fichier_securise($this->file, $this->cles->toJson());
66
-	}
67
-
68
-	/**
69
-	 * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
70
-	 *
71
-	 * @param string $withKey Clé de chiffrage de la sauvegarde
72
-	 * @return string Contenu de la sauvegarde chiffrée générée
73
-	 */
74
-	public function backup(
75
-		#[\SensitiveParameter]
76
-		string $withKey
77
-	): string {
78
-		if (count($this->cles)) {
79
-			return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
80
-		}
81
-		return '';
82
-	}
83
-
84
-	/**
85
-	 * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
86
-	 * (si la sauvegarde est bien valide)
87
-	 */
88
-	public function restore(
89
-		/** Sauvegarde chiffrée (générée par backup()) */
90
-		string $backup,
91
-		#[\SensitiveParameter]
92
-		string $password_clair,
93
-		#[\SensitiveParameter]
94
-		string $password_hash,
95
-		int $id_auteur
96
-	): bool {
97
-		if (empty($backup)) {
98
-			return false;
99
-		}
100
-
101
-		$sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
102
-		$json = json_decode($sauvegarde, true, 512, JSON_THROW_ON_ERROR);
103
-		if (!$json) {
104
-			return false;
105
-		}
106
-
107
-		// cela semble une sauvegarde valide
108
-		$cles_potentielles = array_map('base64_decode', $json);
109
-
110
-		// il faut faire une double verif sur secret_des_auth
111
-		// pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
112
-		// et par extension tous les passwords
113
-		if (
114
-			!empty($cles_potentielles['secret_des_auth'])
115
-			&& !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116
-		) {
117
-			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
118
-			unset($cles_potentielles['secret_des_auth']);
119
-		}
120
-
121
-		// on merge les cles pour recuperer les cles manquantes
122
-		$restauration = false;
123
-		foreach ($cles_potentielles as $name => $key) {
124
-			if (!$this->cles->has($name)) {
125
-				$this->cles->set($name, $key);
126
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
127
-				$restauration = true;
128
-			}
129
-		}
130
-		return $restauration;
131
-	}
132
-
133
-	private function getKey(string $name, bool $autoInit): ?string {
134
-		if ($this->cles->has($name)) {
135
-			return $this->cles->get($name);
136
-		}
137
-		if ($autoInit) {
138
-			$this->cles->generate($name);
139
-			// si l'ecriture de fichier a bien marche on peut utiliser la cle
140
-			if ($this->save()) {
141
-				return $this->cles->get($name);
142
-			}
143
-			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
145
-			$this->cles->delete($name);
146
-		}
147
-		return null;
148
-	}
149
-
150
-	private function getMetaKey(string $name, bool $autoInit = true): ?string {
151
-		if (!isset($GLOBALS['meta'][$name])) {
152
-			include_spip('base/abstract_sql');
153
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
154
-		}
155
-		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
156
-		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
157
-			return $key;
158
-		}
159
-		if (!$autoInit) {
160
-			return null;
161
-		}
162
-		$key = Chiffrement::keygen();
163
-		ecrire_meta($name, base64_encode($key), 'non');
164
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
165
-
166
-		return $key;
167
-	}
168
-
169
-	private function read(): array {
170
-		$json = null;
171
-		lire_fichier_securise($this->file, $json);
172
-		if (
173
-			$json
174
-			&& ($json = \json_decode($json, true, 512, JSON_THROW_ON_ERROR))
175
-			&& is_array($json)
176
-		) {
177
-			return array_map('base64_decode', $json);
178
-		}
179
-		return [];
180
-	}
16
+    private static array $instances = [];
17
+
18
+    private string $file = _DIR_ETC . 'cles.php';
19
+    private readonly Cles $cles;
20
+
21
+    public static function instance(string $file = ''): self {
22
+        if (empty(self::$instances[$file])) {
23
+            self::$instances[$file] = new self($file);
24
+        }
25
+        return self::$instances[$file];
26
+    }
27
+
28
+    /**
29
+     * Retourne le secret du site (shorthand)
30
+     * @uses self::getSecretSite()
31
+     */
32
+    public static function secret_du_site(): ?string {
33
+        return (self::instance())->getSecretSite();
34
+    }
35
+
36
+    private function __construct(string $file = '') {
37
+        if ($file) {
38
+            $this->file = $file;
39
+        }
40
+        $this->cles = new Cles($this->read());
41
+    }
42
+
43
+    /**
44
+     * Renvoyer le secret du site
45
+     *
46
+     * Le secret du site doit rester aussi secret que possible, et est eternel
47
+     * On ne doit pas l'exporter
48
+     *
49
+     * Le secret est partagé entre une clé disque et une clé bdd
50
+     *
51
+     * @return string
52
+     */
53
+    public function getSecretSite(bool $autoInit = true): ?string {
54
+        $key = $this->getKey('secret_du_site', $autoInit);
55
+        $meta = $this->getMetaKey('secret_du_site', $autoInit);
56
+        // conserve la même longeur.
57
+        return $key ^ $meta;
58
+    }
59
+
60
+    /** Renvoyer le secret des authentifications */
61
+    public function getSecretAuth(bool $autoInit = false): ?string {
62
+        return $this->getKey('secret_des_auth', $autoInit);
63
+    }
64
+    public function save(): bool {
65
+        return ecrire_fichier_securise($this->file, $this->cles->toJson());
66
+    }
67
+
68
+    /**
69
+     * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
70
+     *
71
+     * @param string $withKey Clé de chiffrage de la sauvegarde
72
+     * @return string Contenu de la sauvegarde chiffrée générée
73
+     */
74
+    public function backup(
75
+        #[\SensitiveParameter]
76
+        string $withKey
77
+    ): string {
78
+        if (count($this->cles)) {
79
+            return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
80
+        }
81
+        return '';
82
+    }
83
+
84
+    /**
85
+     * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
86
+     * (si la sauvegarde est bien valide)
87
+     */
88
+    public function restore(
89
+        /** Sauvegarde chiffrée (générée par backup()) */
90
+        string $backup,
91
+        #[\SensitiveParameter]
92
+        string $password_clair,
93
+        #[\SensitiveParameter]
94
+        string $password_hash,
95
+        int $id_auteur
96
+    ): bool {
97
+        if (empty($backup)) {
98
+            return false;
99
+        }
100
+
101
+        $sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
102
+        $json = json_decode($sauvegarde, true, 512, JSON_THROW_ON_ERROR);
103
+        if (!$json) {
104
+            return false;
105
+        }
106
+
107
+        // cela semble une sauvegarde valide
108
+        $cles_potentielles = array_map('base64_decode', $json);
109
+
110
+        // il faut faire une double verif sur secret_des_auth
111
+        // pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
112
+        // et par extension tous les passwords
113
+        if (
114
+            !empty($cles_potentielles['secret_des_auth'])
115
+            && !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116
+        ) {
117
+            spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
118
+            unset($cles_potentielles['secret_des_auth']);
119
+        }
120
+
121
+        // on merge les cles pour recuperer les cles manquantes
122
+        $restauration = false;
123
+        foreach ($cles_potentielles as $name => $key) {
124
+            if (!$this->cles->has($name)) {
125
+                $this->cles->set($name, $key);
126
+                spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
127
+                $restauration = true;
128
+            }
129
+        }
130
+        return $restauration;
131
+    }
132
+
133
+    private function getKey(string $name, bool $autoInit): ?string {
134
+        if ($this->cles->has($name)) {
135
+            return $this->cles->get($name);
136
+        }
137
+        if ($autoInit) {
138
+            $this->cles->generate($name);
139
+            // si l'ecriture de fichier a bien marche on peut utiliser la cle
140
+            if ($this->save()) {
141
+                return $this->cles->get($name);
142
+            }
143
+            // sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
+            spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
145
+            $this->cles->delete($name);
146
+        }
147
+        return null;
148
+    }
149
+
150
+    private function getMetaKey(string $name, bool $autoInit = true): ?string {
151
+        if (!isset($GLOBALS['meta'][$name])) {
152
+            include_spip('base/abstract_sql');
153
+            $GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
154
+        }
155
+        $key = base64_decode($GLOBALS['meta'][$name] ?? '');
156
+        if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
157
+            return $key;
158
+        }
159
+        if (!$autoInit) {
160
+            return null;
161
+        }
162
+        $key = Chiffrement::keygen();
163
+        ecrire_meta($name, base64_encode($key), 'non');
164
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
165
+
166
+        return $key;
167
+    }
168
+
169
+    private function read(): array {
170
+        $json = null;
171
+        lire_fichier_securise($this->file, $json);
172
+        if (
173
+            $json
174
+            && ($json = \json_decode($json, true, 512, JSON_THROW_ON_ERROR))
175
+            && is_array($json)
176
+        ) {
177
+            return array_map('base64_decode', $json);
178
+        }
179
+        return [];
180
+    }
181 181
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 final class SpipCles {
16 16
 	private static array $instances = [];
17 17
 
18
-	private string $file = _DIR_ETC . 'cles.php';
18
+	private string $file = _DIR_ETC.'cles.php';
19 19
 	private readonly Cles $cles;
20 20
 
21 21
 	public static function instance(string $file = ''): self {
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			!empty($cles_potentielles['secret_des_auth'])
115 115
 			&& !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116 116
 		) {
117
-			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
117
+			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer'._LOG_INFO_IMPORTANTE);
118 118
 			unset($cles_potentielles['secret_des_auth']);
119 119
 		}
120 120
 
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 		foreach ($cles_potentielles as $name => $key) {
124 124
 			if (!$this->cles->has($name)) {
125 125
 				$this->cles->set($name, $key);
126
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
126
+				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer'._LOG_INFO_IMPORTANTE);
127 127
 				$restauration = true;
128 128
 			}
129 129
 		}
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 				return $this->cles->get($name);
142 142
 			}
143 143
 			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
144
+			spip_log('Echec ecriture du fichier cle '.$this->file." ; impossible de generer une cle $name", 'chiffrer'._LOG_ERREUR);
145 145
 			$this->cles->delete($name);
146 146
 		}
147 147
 		return null;
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	private function getMetaKey(string $name, bool $autoInit = true): ?string {
151 151
 		if (!isset($GLOBALS['meta'][$name])) {
152 152
 			include_spip('base/abstract_sql');
153
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
153
+			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = '.sql_quote($name, '', 'string'));
154 154
 		}
155 155
 		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
156 156
 		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
Please login to merge, or discard this patch.