Completed
Push — master ( 3fe97a...7569f9 )
by cam
02:24
created
ecrire/action/editer_rubrique.php 1 patch
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * @package SPIP\Core\Rubriques\Edition
16 16
  */
17 17
 if (!defined('_ECRIRE_INC_VERSION')) {
18
-	return;
18
+    return;
19 19
 }
20 20
 
21 21
 include_spip('inc/rubriques');
@@ -37,34 +37,34 @@  discard block
 block discarded – undo
37 37
  */
38 38
 function action_editer_rubrique_dist($arg = null) {
39 39
 
40
-	if (is_null($arg)) {
41
-		$securiser_action = charger_fonction('securiser_action', 'inc');
42
-		$arg = $securiser_action();
43
-	}
44
-
45
-	if (!$id_rubrique = (int) $arg) {
46
-		if ($arg != 'oui') {
47
-			include_spip('inc/headers');
48
-			redirige_url_ecrire();
49
-		}
50
-		$id_rubrique = rubrique_inserer(_request('id_parent'));
51
-	}
52
-
53
-	$err = rubrique_modifier($id_rubrique);
54
-
55
-	if (_request('redirect')) {
56
-		$redirect = parametre_url(
57
-			urldecode((string) _request('redirect')),
58
-			'id_rubrique',
59
-			$id_rubrique,
60
-			'&'
61
-		);
62
-
63
-		include_spip('inc/headers');
64
-		redirige_par_entete($redirect);
65
-	}
66
-
67
-	return [$id_rubrique, $err];
40
+    if (is_null($arg)) {
41
+        $securiser_action = charger_fonction('securiser_action', 'inc');
42
+        $arg = $securiser_action();
43
+    }
44
+
45
+    if (!$id_rubrique = (int) $arg) {
46
+        if ($arg != 'oui') {
47
+            include_spip('inc/headers');
48
+            redirige_url_ecrire();
49
+        }
50
+        $id_rubrique = rubrique_inserer(_request('id_parent'));
51
+    }
52
+
53
+    $err = rubrique_modifier($id_rubrique);
54
+
55
+    if (_request('redirect')) {
56
+        $redirect = parametre_url(
57
+            urldecode((string) _request('redirect')),
58
+            'id_rubrique',
59
+            $id_rubrique,
60
+            '&'
61
+        );
62
+
63
+        include_spip('inc/headers');
64
+        redirige_par_entete($redirect);
65
+    }
66
+
67
+    return [$id_rubrique, $err];
68 68
 }
69 69
 
70 70
 
@@ -79,64 +79,64 @@  discard block
 block discarded – undo
79 79
  *     Identifiant de la rubrique crée
80 80
  */
81 81
 function rubrique_inserer($id_parent, $set = null) {
82
-	$champs = [
83
-		'titre' => _T('item_nouvelle_rubrique'),
84
-		'id_parent' => (int) $id_parent,
85
-		'statut' => 'prepa'
86
-	];
87
-
88
-	if ($set) {
89
-		$champs = array_merge($champs, $set);
90
-	}
91
-
92
-	// Envoyer aux plugins
93
-	$champs = pipeline(
94
-		'pre_insertion',
95
-		[
96
-			'args' => [
97
-				'table' => 'spip_rubriques',
98
-			],
99
-			'data' => $champs
100
-		]
101
-	);
102
-
103
-	$id_rubrique = sql_insertq('spip_rubriques', $champs);
104
-	pipeline(
105
-		'post_insertion',
106
-		[
107
-			'args' => [
108
-				'table' => 'spip_rubriques',
109
-				'id_objet' => $id_rubrique
110
-			],
111
-			'data' => $champs
112
-		]
113
-	);
114
-	propager_les_secteurs();
115
-	calculer_langues_rubriques();
116
-
117
-	// Appeler une notification
118
-	if ($notifications = charger_fonction('notifications', 'inc')) {
119
-		$notifications(
120
-			'rubrique_inserer',
121
-			$id_rubrique,
122
-			[
123
-				'id_parent' => $id_parent,
124
-				'champs' => $champs,
125
-			]
126
-		);
127
-		$notifications(
128
-			'objet_inserer',
129
-			$id_rubrique,
130
-			[
131
-				'objet' => 'rubrique',
132
-				'id_objet' => $id_rubrique,
133
-				'id_parent' => $id_parent,
134
-				'champs' => $champs,
135
-			]
136
-		);
137
-	}
138
-
139
-	return $id_rubrique;
82
+    $champs = [
83
+        'titre' => _T('item_nouvelle_rubrique'),
84
+        'id_parent' => (int) $id_parent,
85
+        'statut' => 'prepa'
86
+    ];
87
+
88
+    if ($set) {
89
+        $champs = array_merge($champs, $set);
90
+    }
91
+
92
+    // Envoyer aux plugins
93
+    $champs = pipeline(
94
+        'pre_insertion',
95
+        [
96
+            'args' => [
97
+                'table' => 'spip_rubriques',
98
+            ],
99
+            'data' => $champs
100
+        ]
101
+    );
102
+
103
+    $id_rubrique = sql_insertq('spip_rubriques', $champs);
104
+    pipeline(
105
+        'post_insertion',
106
+        [
107
+            'args' => [
108
+                'table' => 'spip_rubriques',
109
+                'id_objet' => $id_rubrique
110
+            ],
111
+            'data' => $champs
112
+        ]
113
+    );
114
+    propager_les_secteurs();
115
+    calculer_langues_rubriques();
116
+
117
+    // Appeler une notification
118
+    if ($notifications = charger_fonction('notifications', 'inc')) {
119
+        $notifications(
120
+            'rubrique_inserer',
121
+            $id_rubrique,
122
+            [
123
+                'id_parent' => $id_parent,
124
+                'champs' => $champs,
125
+            ]
126
+        );
127
+        $notifications(
128
+            'objet_inserer',
129
+            $id_rubrique,
130
+            [
131
+                'objet' => 'rubrique',
132
+                'id_objet' => $id_rubrique,
133
+                'id_parent' => $id_parent,
134
+                'champs' => $champs,
135
+            ]
136
+        );
137
+    }
138
+
139
+    return $id_rubrique;
140 140
 }
141 141
 
142 142
 /**
@@ -152,46 +152,46 @@  discard block
 block discarded – undo
152 152
  *     - chaîne : texte d'un message d'erreur
153 153
  */
154 154
 function rubrique_modifier($id_rubrique, $set = null) {
155
-	include_spip('inc/autoriser');
156
-	include_spip('inc/filtres');
157
-
158
-	include_spip('inc/modifier');
159
-	$c = collecter_requests(
160
-		// include list
161
-		objet_info('rubrique', 'champs_editables'),
162
-		// exclude list
163
-		['id_parent', 'confirme_deplace'],
164
-		// donnees eventuellement fournies
165
-		$set
166
-	);
167
-
168
-	if (
169
-		$err = objet_modifier_champs(
170
-			'rubrique',
171
-			$id_rubrique,
172
-			[
173
-			'data' => $set,
174
-			'nonvide' => ['titre' => _T('titre_nouvelle_rubrique') . ' ' . _T('info_numero_abbreviation') . $id_rubrique]
175
-			],
176
-			$c
177
-		)
178
-	) {
179
-		return $err;
180
-	}
181
-
182
-	$c = collecter_requests(['id_parent', 'confirme_deplace'], [], $set);
183
-	// Deplacer la rubrique
184
-	if (isset($c['id_parent'])) {
185
-		$err = rubrique_instituer($id_rubrique, $c);
186
-	}
187
-
188
-	// invalider les caches marques de cette rubrique
189
-	include_spip('inc/invalideur');
190
-	suivre_invalideur("id='rubrique/$id_rubrique'");
191
-	// et celui de menu_rubriques
192
-	effacer_meta('date_calcul_rubriques');
193
-
194
-	return $err;
155
+    include_spip('inc/autoriser');
156
+    include_spip('inc/filtres');
157
+
158
+    include_spip('inc/modifier');
159
+    $c = collecter_requests(
160
+        // include list
161
+        objet_info('rubrique', 'champs_editables'),
162
+        // exclude list
163
+        ['id_parent', 'confirme_deplace'],
164
+        // donnees eventuellement fournies
165
+        $set
166
+    );
167
+
168
+    if (
169
+        $err = objet_modifier_champs(
170
+            'rubrique',
171
+            $id_rubrique,
172
+            [
173
+            'data' => $set,
174
+            'nonvide' => ['titre' => _T('titre_nouvelle_rubrique') . ' ' . _T('info_numero_abbreviation') . $id_rubrique]
175
+            ],
176
+            $c
177
+        )
178
+    ) {
179
+        return $err;
180
+    }
181
+
182
+    $c = collecter_requests(['id_parent', 'confirme_deplace'], [], $set);
183
+    // Deplacer la rubrique
184
+    if (isset($c['id_parent'])) {
185
+        $err = rubrique_instituer($id_rubrique, $c);
186
+    }
187
+
188
+    // invalider les caches marques de cette rubrique
189
+    include_spip('inc/invalideur');
190
+    suivre_invalideur("id='rubrique/$id_rubrique'");
191
+    // et celui de menu_rubriques
192
+    effacer_meta('date_calcul_rubriques');
193
+
194
+    return $err;
195 195
 }
196 196
 
197 197
 /**
@@ -214,29 +214,29 @@  discard block
 block discarded – undo
214 214
  *     false si la confirmation du déplacement n'est pas présente
215 215
  */
216 216
 function editer_rubrique_breves($id_rubrique, $id_parent, $c = []) {
217
-	if (!sql_table_exists('spip_breves')) {
218
-		return true;
219
-	}
220
-
221
-	if (!sql_countsel('spip_breves', "id_rubrique=$id_rubrique")) {
222
-		return true;
223
-	}
224
-
225
-	if (empty($c['confirme_deplace']) || $c['confirme_deplace'] != 'oui') {
226
-		return false;
227
-	}
228
-
229
-	if (
230
-		$id_secteur = sql_getfetsel(
231
-			'id_secteur',
232
-			'spip_rubriques',
233
-			"id_rubrique=$id_parent"
234
-		)
235
-	) {
236
-		sql_updateq('spip_breves', ['id_rubrique' => $id_secteur], "id_rubrique=$id_rubrique");
237
-	}
238
-
239
-	return true;
217
+    if (!sql_table_exists('spip_breves')) {
218
+        return true;
219
+    }
220
+
221
+    if (!sql_countsel('spip_breves', "id_rubrique=$id_rubrique")) {
222
+        return true;
223
+    }
224
+
225
+    if (empty($c['confirme_deplace']) || $c['confirme_deplace'] != 'oui') {
226
+        return false;
227
+    }
228
+
229
+    if (
230
+        $id_secteur = sql_getfetsel(
231
+            'id_secteur',
232
+            'spip_rubriques',
233
+            "id_rubrique=$id_parent"
234
+        )
235
+    ) {
236
+        sql_updateq('spip_breves', ['id_rubrique' => $id_secteur], "id_rubrique=$id_rubrique");
237
+    }
238
+
239
+    return true;
240 240
 }
241 241
 
242 242
 
@@ -258,72 +258,72 @@  discard block
 block discarded – undo
258 258
  *     Chaîne : texte du message d'erreur
259 259
  */
260 260
 function rubrique_instituer($id_rubrique, $c) {
261
-	// traitement de la rubrique parente
262
-	// interdiction de deplacer vers ou a partir d'une rubrique
263
-	// qu'on n'administre pas.
264
-
265
-	if (null !== ($id_parent = $c['id_parent'])) {
266
-		$id_parent = (int) $id_parent;
267
-		$filles = calcul_branche_in($id_rubrique);
268
-		if (str_contains(",$id_parent,", (string) ",$filles,")) {
269
-			spip_log("La rubrique $id_rubrique ne peut etre fille de sa descendante $id_parent");
270
-		} else {
271
-			$s = sql_fetsel('id_parent, statut', 'spip_rubriques', "id_rubrique=$id_rubrique");
272
-			$old_parent = $s['id_parent'];
273
-
274
-			if (
275
-				!($id_parent != $old_parent
276
-				&& autoriser('publierdans', 'rubrique', $id_parent)
277
-				&& autoriser('creerrubriquedans', 'rubrique', $id_parent)
278
-				&& autoriser('publierdans', 'rubrique', $old_parent)
279
-				)
280
-			) {
281
-				if ($s['statut'] != 'prepa') {
282
-					spip_log("deplacement de $id_rubrique vers $id_parent refuse a " . $GLOBALS['visiteur_session']['id_auteur'] . ' ' . $GLOBALS['visiteur_session']['statut']);
283
-				}
284
-			} elseif (editer_rubrique_breves($id_rubrique, $id_parent, $c)) {
285
-				$statut_ancien = $s['statut'];
286
-				sql_updateq('spip_rubriques', ['id_parent' => $id_parent], "id_rubrique=$id_rubrique");
287
-
288
-
289
-				propager_les_secteurs();
290
-
291
-				// Deplacement d'une rubrique publiee ==> chgt general de leur statut
292
-				if ($statut_ancien == 'publie') {
293
-					calculer_rubriques_if($old_parent, ['id_rubrique' => $id_parent], ['statut_ancien' => $statut_ancien]);
294
-				}
295
-				// Creation ou deplacement d'une rubrique non publiee
296
-				// invalider le cache de leur menu
297
-				elseif (!$statut_ancien || $old_parent != $id_parent) {
298
-					effacer_meta('date_calcul_rubriques');
299
-				}
300
-
301
-				calculer_langues_rubriques();
302
-
303
-				// Appeler une notification
304
-				if ($notifications = charger_fonction('notifications', 'inc')) {
305
-					$notifications(
306
-						'rubrique_instituer',
307
-						$id_rubrique,
308
-						[
309
-							'statut_ancien' => $statut_ancien,
310
-							'id_parent_ancien' => $old_parent,
311
-						]
312
-					);
313
-					$notifications(
314
-						'objet_instituer',
315
-						$id_rubrique,
316
-						[
317
-							'objet' => 'rubrique',
318
-							'id_objet' => $id_rubrique,
319
-							'statut_ancien' => $statut_ancien,
320
-							'id_parent_ancien' => $old_parent,
321
-						]
322
-					);
323
-				}
324
-			}
325
-		}
326
-	}
327
-
328
-	return ''; // pas d'erreur
261
+    // traitement de la rubrique parente
262
+    // interdiction de deplacer vers ou a partir d'une rubrique
263
+    // qu'on n'administre pas.
264
+
265
+    if (null !== ($id_parent = $c['id_parent'])) {
266
+        $id_parent = (int) $id_parent;
267
+        $filles = calcul_branche_in($id_rubrique);
268
+        if (str_contains(",$id_parent,", (string) ",$filles,")) {
269
+            spip_log("La rubrique $id_rubrique ne peut etre fille de sa descendante $id_parent");
270
+        } else {
271
+            $s = sql_fetsel('id_parent, statut', 'spip_rubriques', "id_rubrique=$id_rubrique");
272
+            $old_parent = $s['id_parent'];
273
+
274
+            if (
275
+                !($id_parent != $old_parent
276
+                && autoriser('publierdans', 'rubrique', $id_parent)
277
+                && autoriser('creerrubriquedans', 'rubrique', $id_parent)
278
+                && autoriser('publierdans', 'rubrique', $old_parent)
279
+                )
280
+            ) {
281
+                if ($s['statut'] != 'prepa') {
282
+                    spip_log("deplacement de $id_rubrique vers $id_parent refuse a " . $GLOBALS['visiteur_session']['id_auteur'] . ' ' . $GLOBALS['visiteur_session']['statut']);
283
+                }
284
+            } elseif (editer_rubrique_breves($id_rubrique, $id_parent, $c)) {
285
+                $statut_ancien = $s['statut'];
286
+                sql_updateq('spip_rubriques', ['id_parent' => $id_parent], "id_rubrique=$id_rubrique");
287
+
288
+
289
+                propager_les_secteurs();
290
+
291
+                // Deplacement d'une rubrique publiee ==> chgt general de leur statut
292
+                if ($statut_ancien == 'publie') {
293
+                    calculer_rubriques_if($old_parent, ['id_rubrique' => $id_parent], ['statut_ancien' => $statut_ancien]);
294
+                }
295
+                // Creation ou deplacement d'une rubrique non publiee
296
+                // invalider le cache de leur menu
297
+                elseif (!$statut_ancien || $old_parent != $id_parent) {
298
+                    effacer_meta('date_calcul_rubriques');
299
+                }
300
+
301
+                calculer_langues_rubriques();
302
+
303
+                // Appeler une notification
304
+                if ($notifications = charger_fonction('notifications', 'inc')) {
305
+                    $notifications(
306
+                        'rubrique_instituer',
307
+                        $id_rubrique,
308
+                        [
309
+                            'statut_ancien' => $statut_ancien,
310
+                            'id_parent_ancien' => $old_parent,
311
+                        ]
312
+                    );
313
+                    $notifications(
314
+                        'objet_instituer',
315
+                        $id_rubrique,
316
+                        [
317
+                            'objet' => 'rubrique',
318
+                            'id_objet' => $id_rubrique,
319
+                            'statut_ancien' => $statut_ancien,
320
+                            'id_parent_ancien' => $old_parent,
321
+                        ]
322
+                    );
323
+                }
324
+            }
325
+        }
326
+    }
327
+
328
+    return ''; // pas d'erreur
329 329
 }
Please login to merge, or discard this patch.
ecrire/action/annuler_job.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -25,13 +25,13 @@  discard block
 block discarded – undo
25 25
  * @return void
26 26
  */
27 27
 function action_annuler_job_dist() {
28
-	$securiser_action = charger_fonction('securiser_action', 'inc');
29
-	$id_job = $securiser_action();
28
+    $securiser_action = charger_fonction('securiser_action', 'inc');
29
+    $id_job = $securiser_action();
30 30
 
31
-	if (
32
-		($id_job = (int) $id_job)
33
-		&& autoriser('annuler', 'job', $id_job)
34
-	) {
35
-		job_queue_remove($id_job);
36
-	}
31
+    if (
32
+        ($id_job = (int) $id_job)
33
+        && autoriser('annuler', 'job', $id_job)
34
+    ) {
35
+        job_queue_remove($id_job);
36
+    }
37 37
 }
Please login to merge, or discard this patch.
ecrire/action/activer_plugins.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -27,49 +27,49 @@  discard block
 block discarded – undo
27 27
  * @return void
28 28
  */
29 29
 function enregistre_modif_plugin() {
30
-	include_spip('inc/plugin');
31
-	// recuperer les plugins dans l'ordre des $_POST
32
-	$test = [];
33
-	foreach (liste_plugin_files() as $file) {
34
-		$test['s' . substr(md5(_DIR_PLUGINS . $file), 0, 16)] = $file;
35
-	}
36
-	if (defined('_DIR_PLUGINS_SUPPL')) {
37
-		foreach (liste_plugin_files(_DIR_PLUGINS_SUPPL) as $file) {
38
-			$test['s' . substr(md5(_DIR_PLUGINS_SUPPL . $file), 0, 16)] = $file;
39
-		}
40
-	}
30
+    include_spip('inc/plugin');
31
+    // recuperer les plugins dans l'ordre des $_POST
32
+    $test = [];
33
+    foreach (liste_plugin_files() as $file) {
34
+        $test['s' . substr(md5(_DIR_PLUGINS . $file), 0, 16)] = $file;
35
+    }
36
+    if (defined('_DIR_PLUGINS_SUPPL')) {
37
+        foreach (liste_plugin_files(_DIR_PLUGINS_SUPPL) as $file) {
38
+            $test['s' . substr(md5(_DIR_PLUGINS_SUPPL . $file), 0, 16)] = $file;
39
+        }
40
+    }
41 41
 
42
-	$plugin = [];
42
+    $plugin = [];
43 43
 
44
-	foreach ($_POST as $choix => $val) {
45
-		if (isset($test[$choix]) && $val == 'O') {
46
-			$plugin[] = $test[$choix];
47
-		}
48
-	}
44
+    foreach ($_POST as $choix => $val) {
45
+        if (isset($test[$choix]) && $val == 'O') {
46
+            $plugin[] = $test[$choix];
47
+        }
48
+    }
49 49
 
50
-	spip_log("Changement des plugins actifs par l'auteur " . $GLOBALS['visiteur_session']['id_auteur'] . ': ' . implode(
51
-		',',
52
-		$plugin
53
-	));
54
-	ecrire_plugin_actifs($plugin);
50
+    spip_log("Changement des plugins actifs par l'auteur " . $GLOBALS['visiteur_session']['id_auteur'] . ': ' . implode(
51
+        ',',
52
+        $plugin
53
+    ));
54
+    ecrire_plugin_actifs($plugin);
55 55
 
56
-	// Chaque fois que l'on valide des plugins, on memorise la liste de ces plugins comme etant "interessants", avec un score initial, qui sera decremente a chaque tour : ainsi un plugin active pourra reter visible a l'ecran, jusqu'a ce qu'il tombe dans l'oubli.
57
-	$plugins_interessants = @unserialize($GLOBALS['meta']['plugins_interessants']);
58
-	if (!is_array($plugins_interessants)) {
59
-		$plugins_interessants = [];
60
-	}
56
+    // Chaque fois que l'on valide des plugins, on memorise la liste de ces plugins comme etant "interessants", avec un score initial, qui sera decremente a chaque tour : ainsi un plugin active pourra reter visible a l'ecran, jusqu'a ce qu'il tombe dans l'oubli.
57
+    $plugins_interessants = @unserialize($GLOBALS['meta']['plugins_interessants']);
58
+    if (!is_array($plugins_interessants)) {
59
+        $plugins_interessants = [];
60
+    }
61 61
 
62
-	$plugins_interessants2 = [];
62
+    $plugins_interessants2 = [];
63 63
 
64
-	foreach ($plugins_interessants as $plug => $score) {
65
-		if ($score > 1) {
66
-			$plugins_interessants2[$plug] = $score - 1;
67
-		}
68
-	}
69
-	foreach ($plugin as $plug) {
70
-		$plugins_interessants2[$plug] = 10;
71
-	} // score initial
72
-	ecrire_meta('plugins_interessants', serialize($plugins_interessants2));
64
+    foreach ($plugins_interessants as $plug => $score) {
65
+        if ($score > 1) {
66
+            $plugins_interessants2[$plug] = $score - 1;
67
+        }
68
+    }
69
+    foreach ($plugin as $plug) {
70
+        $plugins_interessants2[$plug] = 10;
71
+    } // score initial
72
+    ecrire_meta('plugins_interessants', serialize($plugins_interessants2));
73 73
 }
74 74
 
75 75
 /**
@@ -81,13 +81,13 @@  discard block
 block discarded – undo
81 81
  */
82 82
 function action_activer_plugins_dist() {
83 83
 
84
-	$securiser_action = charger_fonction('securiser_action', 'inc');
85
-	$securiser_action();
84
+    $securiser_action = charger_fonction('securiser_action', 'inc');
85
+    $securiser_action();
86 86
 
87
-	if (!autoriser('configurer', '_plugins')) {
88
-		die('erreur');
89
-	}
90
-	// forcer la maj des meta pour les cas de modif de numero de version base via phpmyadmin
91
-	lire_metas();
92
-	enregistre_modif_plugin();
87
+    if (!autoriser('configurer', '_plugins')) {
88
+        die('erreur');
89
+    }
90
+    // forcer la maj des meta pour les cas de modif de numero de version base via phpmyadmin
91
+    lire_metas();
92
+    enregistre_modif_plugin();
93 93
 }
Please login to merge, or discard this patch.
ecrire/src/Sql/Sqlite/Traducteur.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -9,195 +9,195 @@
 block discarded – undo
9 9
  */
10 10
 class Traducteur
11 11
 {
12
-	/** Pour les corrections à effectuer sur les requêtes : array(code=>'texte') trouvé
13
-	 *
14
-	 * @var array
15
-	 */
16
-	public $textes = [];
17
-
18
-	/**
19
-	 * Constructeur
20
-	 */
21
-	public function __construct(
22
-		/** Requête à préparer */
23
-		public string $query,
24
-		/** Prefixe des tables à utiliser */
25
-		public string $prefixe,
26
-		/** Version SQLite (2 ou 3) */
27
-		public string $sqlite_version
28
-	) {
29
-	}
30
-
31
-	/**
32
-	 * Transformer la requete pour SQLite
33
-	 *
34
-	 * Enlève les textes, transforme la requête pour quelle soit
35
-	 * bien interprétée par SQLite, puis remet les textes
36
-	 * la fonction affecte `$this->query`
37
-	 */
38
-	public function traduire_requete() {
39
-		//
40
-		// 1) Protection des textes en les remplacant par des codes
41
-		//
42
-		// enlever les 'textes' et initialiser avec
43
-		[$this->query, $textes] = query_echappe_textes($this->query);
44
-
45
-		//
46
-		// 2) Corrections de la requete
47
-		//
48
-		// Correction Create Database
49
-		// Create Database -> requete ignoree
50
-		if (str_starts_with((string) $this->query, 'CREATE DATABASE')) {
51
-			spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.' . _LOG_AVERTISSEMENT);
52
-			$this->query = 'SELECT 1';
53
-		}
54
-
55
-		// Correction Insert Ignore
56
-		// INSERT IGNORE -> insert (tout court et pas 'insert or replace')
57
-		if (str_starts_with((string) $this->query, 'INSERT IGNORE')) {
58
-			spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.' . _LOG_DEBUG);
59
-			$this->query = 'INSERT ' . substr((string) $this->query, '13');
60
-		}
61
-
62
-		// Correction des dates avec INTERVAL
63
-		// utiliser sql_date_proche() de preference
64
-		if (str_contains((string) $this->query, 'INTERVAL')) {
65
-			$this->query = preg_replace_callback(
66
-				'/DATE_(ADD|SUB)(.*)INTERVAL\s+(\d+)\s+([a-zA-Z]+)\)/U',
67
-				fn(array $matches): string => $this->_remplacerDateParTime($matches),
68
-				(string) $this->query
69
-			);
70
-		}
71
-
72
-		if (str_contains((string) $this->query, 'LEFT(')) {
73
-			$this->query = str_replace('LEFT(', '_LEFT(', (string) $this->query);
74
-		}
75
-
76
-		if (str_contains((string) $this->query, 'TIMESTAMPDIFF(')) {
77
-			$this->query = preg_replace('/TIMESTAMPDIFF\(\s*([^,]*)\s*,/Uims', "TIMESTAMPDIFF('\\1',", (string) $this->query);
78
-		}
79
-
80
-
81
-		// Correction Using
82
-		// USING (non reconnu en sqlite2)
83
-		// problematique car la jointure ne se fait pas du coup.
84
-		if (($this->sqlite_version == 2) && (str_contains((string) $this->query, 'USING'))) {
85
-			spip_log(
86
-				"'USING (champ)' n'est pas reconnu en SQLite 2. Utilisez 'ON table1.champ = table2.champ'",
87
-				'sqlite.' . _LOG_ERREUR
88
-			);
89
-			$this->query = preg_replace('/USING\s*\([^\)]*\)/', '', (string) $this->query);
90
-		}
91
-
92
-		// Correction Field
93
-		// remplace FIELD(table,i,j,k...) par CASE WHEN table=i THEN n ... ELSE 0 END
94
-		if (str_contains((string) $this->query, 'FIELD')) {
95
-			$this->query = preg_replace_callback(
96
-				'/FIELD\s*\(([^\)]*)\)/',
97
-				fn(array $matches): string => $this->_remplacerFieldParCase($matches),
98
-				(string) $this->query
99
-			);
100
-		}
101
-
102
-		// Correction des noms de tables FROM
103
-		// mettre les bons noms de table dans from, update, insert, replace...
104
-		if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/iS', (string) $this->query, $regs)) {
105
-			$suite = strstr((string) $this->query, $regs[0]);
106
-			$this->query = substr((string) $this->query, 0, -strlen($suite));
107
-		} else {
108
-			$suite = '';
109
-		}
110
-		$pref = ($this->prefixe) ? $this->prefixe . '_' : '';
111
-		$this->query = preg_replace('/([,\s])spip_/S', '\1' . $pref, (string) $this->query) . $suite;
112
-
113
-		// Correction zero AS x
114
-		// pg n'aime pas 0+x AS alias, sqlite, dans le meme style,
115
-		// n'apprecie pas du tout SELECT 0 as x ... ORDER BY x
116
-		// il dit que x ne doit pas être un integer dans le order by !
117
-		// on remplace du coup x par vide() dans ce cas uniquement
118
-		//
119
-		// apparait dans public/vertebrer.php et dans le plugin menu aussi qui genere aussi ce genre de requete via un {par num #GET{tri_num}}
120
-		// mais est-ce encore un soucis pour sqlite en 2021 ? (ie commenter le preg_replace marche très bien en sqlite 3.28)
121
-		// on ne remplace que dans ORDER BY ou GROUP BY
122
-		if (str_contains($this->query, '0 AS') && preg_match('/\s(ORDER|GROUP) BY\s/i', $this->query, $regs)) {
123
-			$suite = strstr($this->query, $regs[0]);
124
-			$this->query = substr($this->query, 0, -strlen($suite));
125
-			// on cherche les noms des x dans 0 AS x
126
-			// on remplace dans $suite le nom par vide()
127
-			preg_match_all('/\b0 AS\s*([^\s,]+)/', $this->query, $matches, PREG_PATTERN_ORDER);
128
-			foreach ($matches[1] as $m) {
129
-				if (str_contains($suite, $m)) {
130
-					$suite = preg_replace(",\b$m\b,", 'VIDE()', $suite);
131
-				}
132
-			}
133
-			$this->query .= $suite;
134
-		}
135
-
136
-		// Correction possible des divisions entieres
137
-		// Le standard SQL (lequel? ou?) semble indiquer que
138
-		// a/b=c doit donner c entier si a et b sont entiers 4/3=1.
139
-		// C'est ce que retournent effectivement SQL Server et SQLite
140
-		// Ce n'est pas ce qu'applique MySQL qui retourne un reel : 4/3=1.333...
141
-		//
142
-		// On peut forcer la conversion en multipliant par 1.0 avant la division
143
-		// /!\ SQLite 3.5.9 Debian/Ubuntu est victime d'un bug en plus !
144
-		// cf. https://bugs.launchpad.net/ubuntu/+source/sqlite3/+bug/254228
145
-		//     http://www.sqlite.org/cvstrac/tktview?tn=3202
146
-		// (4*1.0/3) n'est pas rendu dans ce cas !
147
-		# $this->query = str_replace('/','* 1.00 / ',$this->query);
148
-
149
-
150
-		// Correction critere REGEXP, non reconnu en sqlite2
151
-		if (($this->sqlite_version == 2) && (str_contains($this->query, 'REGEXP'))) {
152
-			$this->query = preg_replace('/([^\s\(]*)(\s*)REGEXP(\s*)([^\s\)]*)/', 'REGEXP($4, $1)', $this->query);
153
-		}
154
-
155
-		//
156
-		// 3) Remise en place des textes d'origine
157
-		//
158
-		// Correction Antiquotes et echappements
159
-		// ` => rien
160
-		if (str_contains($this->query, '`')) {
161
-			$this->query = str_replace('`', '', $this->query);
162
-		}
163
-
164
-		$this->query = query_reinjecte_textes($this->query, $textes);
165
-
166
-		return $this->query;
167
-	}
168
-
169
-	/**
170
-	 * Callback pour remplacer `DATE_` / `INTERVAL`
171
-	 * par `DATE ... strtotime`
172
-	 *
173
-	 * @param array $matches Captures
174
-	 * @return string texte de date compris par SQLite
175
-	 */
176
-	public function _remplacerDateParTime($matches) {
177
-		$op = strtoupper($matches[1] == 'ADD') ? '+' : '-';
178
-
179
-		return "datetime$matches[2] '$op$matches[3] $matches[4]')";
180
-	}
181
-
182
-	/**
183
-	 * Callback pour remplacer `FIELD(table,i,j,k...)`
184
-	 * par `CASE WHEN table=i THEN n ... ELSE 0 END`
185
-	 *
186
-	 * @param array $matches Captures
187
-	 * @return string texte de liste ordonnée compris par SQLite
188
-	 */
189
-	public function _remplacerFieldParCase($matches) {
190
-		$fields = substr((string) $matches[0], 6, -1); // ne recuperer que l'interieur X de field(X)
191
-		$t = explode(',', $fields);
192
-		$index = array_shift($t);
193
-
194
-		$res = '';
195
-		$n = 0;
196
-		foreach ($t as $v) {
197
-			$n++;
198
-			$res .= "\nWHEN $index=$v THEN $n";
199
-		}
200
-
201
-		return "CASE $res ELSE 0 END ";
202
-	}
12
+    /** Pour les corrections à effectuer sur les requêtes : array(code=>'texte') trouvé
13
+     *
14
+     * @var array
15
+     */
16
+    public $textes = [];
17
+
18
+    /**
19
+     * Constructeur
20
+     */
21
+    public function __construct(
22
+        /** Requête à préparer */
23
+        public string $query,
24
+        /** Prefixe des tables à utiliser */
25
+        public string $prefixe,
26
+        /** Version SQLite (2 ou 3) */
27
+        public string $sqlite_version
28
+    ) {
29
+    }
30
+
31
+    /**
32
+     * Transformer la requete pour SQLite
33
+     *
34
+     * Enlève les textes, transforme la requête pour quelle soit
35
+     * bien interprétée par SQLite, puis remet les textes
36
+     * la fonction affecte `$this->query`
37
+     */
38
+    public function traduire_requete() {
39
+        //
40
+        // 1) Protection des textes en les remplacant par des codes
41
+        //
42
+        // enlever les 'textes' et initialiser avec
43
+        [$this->query, $textes] = query_echappe_textes($this->query);
44
+
45
+        //
46
+        // 2) Corrections de la requete
47
+        //
48
+        // Correction Create Database
49
+        // Create Database -> requete ignoree
50
+        if (str_starts_with((string) $this->query, 'CREATE DATABASE')) {
51
+            spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.' . _LOG_AVERTISSEMENT);
52
+            $this->query = 'SELECT 1';
53
+        }
54
+
55
+        // Correction Insert Ignore
56
+        // INSERT IGNORE -> insert (tout court et pas 'insert or replace')
57
+        if (str_starts_with((string) $this->query, 'INSERT IGNORE')) {
58
+            spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.' . _LOG_DEBUG);
59
+            $this->query = 'INSERT ' . substr((string) $this->query, '13');
60
+        }
61
+
62
+        // Correction des dates avec INTERVAL
63
+        // utiliser sql_date_proche() de preference
64
+        if (str_contains((string) $this->query, 'INTERVAL')) {
65
+            $this->query = preg_replace_callback(
66
+                '/DATE_(ADD|SUB)(.*)INTERVAL\s+(\d+)\s+([a-zA-Z]+)\)/U',
67
+                fn(array $matches): string => $this->_remplacerDateParTime($matches),
68
+                (string) $this->query
69
+            );
70
+        }
71
+
72
+        if (str_contains((string) $this->query, 'LEFT(')) {
73
+            $this->query = str_replace('LEFT(', '_LEFT(', (string) $this->query);
74
+        }
75
+
76
+        if (str_contains((string) $this->query, 'TIMESTAMPDIFF(')) {
77
+            $this->query = preg_replace('/TIMESTAMPDIFF\(\s*([^,]*)\s*,/Uims', "TIMESTAMPDIFF('\\1',", (string) $this->query);
78
+        }
79
+
80
+
81
+        // Correction Using
82
+        // USING (non reconnu en sqlite2)
83
+        // problematique car la jointure ne se fait pas du coup.
84
+        if (($this->sqlite_version == 2) && (str_contains((string) $this->query, 'USING'))) {
85
+            spip_log(
86
+                "'USING (champ)' n'est pas reconnu en SQLite 2. Utilisez 'ON table1.champ = table2.champ'",
87
+                'sqlite.' . _LOG_ERREUR
88
+            );
89
+            $this->query = preg_replace('/USING\s*\([^\)]*\)/', '', (string) $this->query);
90
+        }
91
+
92
+        // Correction Field
93
+        // remplace FIELD(table,i,j,k...) par CASE WHEN table=i THEN n ... ELSE 0 END
94
+        if (str_contains((string) $this->query, 'FIELD')) {
95
+            $this->query = preg_replace_callback(
96
+                '/FIELD\s*\(([^\)]*)\)/',
97
+                fn(array $matches): string => $this->_remplacerFieldParCase($matches),
98
+                (string) $this->query
99
+            );
100
+        }
101
+
102
+        // Correction des noms de tables FROM
103
+        // mettre les bons noms de table dans from, update, insert, replace...
104
+        if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/iS', (string) $this->query, $regs)) {
105
+            $suite = strstr((string) $this->query, $regs[0]);
106
+            $this->query = substr((string) $this->query, 0, -strlen($suite));
107
+        } else {
108
+            $suite = '';
109
+        }
110
+        $pref = ($this->prefixe) ? $this->prefixe . '_' : '';
111
+        $this->query = preg_replace('/([,\s])spip_/S', '\1' . $pref, (string) $this->query) . $suite;
112
+
113
+        // Correction zero AS x
114
+        // pg n'aime pas 0+x AS alias, sqlite, dans le meme style,
115
+        // n'apprecie pas du tout SELECT 0 as x ... ORDER BY x
116
+        // il dit que x ne doit pas être un integer dans le order by !
117
+        // on remplace du coup x par vide() dans ce cas uniquement
118
+        //
119
+        // apparait dans public/vertebrer.php et dans le plugin menu aussi qui genere aussi ce genre de requete via un {par num #GET{tri_num}}
120
+        // mais est-ce encore un soucis pour sqlite en 2021 ? (ie commenter le preg_replace marche très bien en sqlite 3.28)
121
+        // on ne remplace que dans ORDER BY ou GROUP BY
122
+        if (str_contains($this->query, '0 AS') && preg_match('/\s(ORDER|GROUP) BY\s/i', $this->query, $regs)) {
123
+            $suite = strstr($this->query, $regs[0]);
124
+            $this->query = substr($this->query, 0, -strlen($suite));
125
+            // on cherche les noms des x dans 0 AS x
126
+            // on remplace dans $suite le nom par vide()
127
+            preg_match_all('/\b0 AS\s*([^\s,]+)/', $this->query, $matches, PREG_PATTERN_ORDER);
128
+            foreach ($matches[1] as $m) {
129
+                if (str_contains($suite, $m)) {
130
+                    $suite = preg_replace(",\b$m\b,", 'VIDE()', $suite);
131
+                }
132
+            }
133
+            $this->query .= $suite;
134
+        }
135
+
136
+        // Correction possible des divisions entieres
137
+        // Le standard SQL (lequel? ou?) semble indiquer que
138
+        // a/b=c doit donner c entier si a et b sont entiers 4/3=1.
139
+        // C'est ce que retournent effectivement SQL Server et SQLite
140
+        // Ce n'est pas ce qu'applique MySQL qui retourne un reel : 4/3=1.333...
141
+        //
142
+        // On peut forcer la conversion en multipliant par 1.0 avant la division
143
+        // /!\ SQLite 3.5.9 Debian/Ubuntu est victime d'un bug en plus !
144
+        // cf. https://bugs.launchpad.net/ubuntu/+source/sqlite3/+bug/254228
145
+        //     http://www.sqlite.org/cvstrac/tktview?tn=3202
146
+        // (4*1.0/3) n'est pas rendu dans ce cas !
147
+        # $this->query = str_replace('/','* 1.00 / ',$this->query);
148
+
149
+
150
+        // Correction critere REGEXP, non reconnu en sqlite2
151
+        if (($this->sqlite_version == 2) && (str_contains($this->query, 'REGEXP'))) {
152
+            $this->query = preg_replace('/([^\s\(]*)(\s*)REGEXP(\s*)([^\s\)]*)/', 'REGEXP($4, $1)', $this->query);
153
+        }
154
+
155
+        //
156
+        // 3) Remise en place des textes d'origine
157
+        //
158
+        // Correction Antiquotes et echappements
159
+        // ` => rien
160
+        if (str_contains($this->query, '`')) {
161
+            $this->query = str_replace('`', '', $this->query);
162
+        }
163
+
164
+        $this->query = query_reinjecte_textes($this->query, $textes);
165
+
166
+        return $this->query;
167
+    }
168
+
169
+    /**
170
+     * Callback pour remplacer `DATE_` / `INTERVAL`
171
+     * par `DATE ... strtotime`
172
+     *
173
+     * @param array $matches Captures
174
+     * @return string texte de date compris par SQLite
175
+     */
176
+    public function _remplacerDateParTime($matches) {
177
+        $op = strtoupper($matches[1] == 'ADD') ? '+' : '-';
178
+
179
+        return "datetime$matches[2] '$op$matches[3] $matches[4]')";
180
+    }
181
+
182
+    /**
183
+     * Callback pour remplacer `FIELD(table,i,j,k...)`
184
+     * par `CASE WHEN table=i THEN n ... ELSE 0 END`
185
+     *
186
+     * @param array $matches Captures
187
+     * @return string texte de liste ordonnée compris par SQLite
188
+     */
189
+    public function _remplacerFieldParCase($matches) {
190
+        $fields = substr((string) $matches[0], 6, -1); // ne recuperer que l'interieur X de field(X)
191
+        $t = explode(',', $fields);
192
+        $index = array_shift($t);
193
+
194
+        $res = '';
195
+        $n = 0;
196
+        foreach ($t as $v) {
197
+            $n++;
198
+            $res .= "\nWHEN $index=$v THEN $n";
199
+        }
200
+
201
+        return "CASE $res ELSE 0 END ";
202
+    }
203 203
 }
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Liens.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -15,98 +15,98 @@
 block discarded – undo
15 15
  *    Collecte les raccourcis liens [titre->url] de SPIP
16 16
  */
17 17
 class Liens extends AbstractCollecteur {
18
-	protected static string $markPrefix = 'LIEN';
19
-
20
-	/**
21
-	 * La preg pour découper et collecter les modèles
22
-	 * @var string
23
-	 */
24
-	protected string $preg_lien;
25
-
26
-	public function __construct(?string $preg = null) {
27
-
28
-		// Regexp des raccourcis, aussi utilisee pour la fusion de sauvegarde Spip
29
-		// Laisser passer des paires de crochets pour la balise multi
30
-		// mais refuser plus d'imbrications ou de mauvaises imbrications
31
-		// sinon les crochets ne peuvent plus servir qu'a ce type de raccourci
32
-		$this->preg_lien = ($preg ?: '/\[([^][]*?([[][^]>-]*[]][^][]*)*)->(>?)([^]]*)\]/msS');
33
-	}
34
-
35
-
36
-	/**
37
-	 * Sanitizer une collection d'occurences de liens : il faut sanitizer le href et le texte uniquement
38
-	 *
39
-	 * @param array $collection
40
-	 * @param string $sanitize_callback
41
-	 * @return array
42
-	 */
43
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
44
-		foreach ($collection as &$lien) {
45
-			$t = $sanitize_callback($lien['texte']);
46
-			if ($t !== $lien['texte']) {
47
-				$lien['raw'] = str_replace($lien['texte'], $t, (string) $lien['raw']);
48
-				$lien['texte'] = $t;
49
-			}
50
-			$href = $sanitize_callback($lien['href']);
51
-			if ($href !== $lien['href']) {
52
-				$lien['raw'] = str_replace($lien['href'], $href, (string) $lien['raw']);
53
-				$lien['href'] = $href;
54
-			}
55
-		}
56
-
57
-		return $collection;
58
-	}
59
-
60
-	/**
61
-	 * @param string $texte
62
-	 * @param array $options
63
-	 *   bool $collecter_liens
64
-	 * @return array
65
-	 */
66
-	public function collecter(string $texte, array $options = []): array {
67
-		if (!$texte) {
68
-			return [];
69
-		}
70
-
71
-		$liens = [];
72
-		if (str_contains($texte, '->')) {
73
-			$desechappe_crochets = false;
74
-			// si il y a un crochet ouvrant échappé ou un crochet fermant échappé, les substituer pour les ignorer
75
-			if (str_contains($texte, '\[') || str_contains($texte, '\]')) {
76
-				$texte = str_replace(['\[', '\]'], ["\x1\x5", "\x1\x6"], $texte);
77
-				$desechappe_crochets = true;
78
-			}
79
-
80
-			// collecter les matchs de la preg
81
-			$liens = static::collecteur($texte, '->', '[', $this->preg_lien, empty($options['detecter_presence']) ? 0 : 1);
82
-
83
-			// si on veut seulement detecter la présence, on peut retourner tel quel
84
-			if (empty($options['detecter_presence'])) {
85
-				foreach ($liens as $k => &$lien) {
86
-					$lien['href'] = end($lien['match']);
87
-					$lien['texte'] = $lien['match'][1];
88
-					$lien['ouvrant'] = $lien['match'][3] ?? '';
89
-
90
-					// la mise en lien automatique est passee par la a tort !
91
-					// corrigeons pour eviter d'avoir un <a...> dans un href...
92
-					if (str_starts_with((string) $lien['href'], '<a')) {
93
-						$href = extraire_attribut($lien['href'], 'href');
94
-						// remplacons dans la source qui peut etre reinjectee dans les arguments
95
-						// d'un modele
96
-						$lien['raw'] = str_replace($lien['href'], $href, (string) $lien['raw']);
97
-						// et prenons le href comme la vraie url a linker
98
-						$lien['href'] = $href;
99
-					}
100
-
101
-					if ($desechappe_crochets && str_contains((string) $lien['raw'], "\x1")) {
102
-						$lien['raw'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['raw']);
103
-						$lien['texte'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['texte']);
104
-						$lien['href'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['href']);
105
-					}
106
-				}
107
-			}
108
-		}
109
-
110
-		return $liens;
111
-	}
18
+    protected static string $markPrefix = 'LIEN';
19
+
20
+    /**
21
+     * La preg pour découper et collecter les modèles
22
+     * @var string
23
+     */
24
+    protected string $preg_lien;
25
+
26
+    public function __construct(?string $preg = null) {
27
+
28
+        // Regexp des raccourcis, aussi utilisee pour la fusion de sauvegarde Spip
29
+        // Laisser passer des paires de crochets pour la balise multi
30
+        // mais refuser plus d'imbrications ou de mauvaises imbrications
31
+        // sinon les crochets ne peuvent plus servir qu'a ce type de raccourci
32
+        $this->preg_lien = ($preg ?: '/\[([^][]*?([[][^]>-]*[]][^][]*)*)->(>?)([^]]*)\]/msS');
33
+    }
34
+
35
+
36
+    /**
37
+     * Sanitizer une collection d'occurences de liens : il faut sanitizer le href et le texte uniquement
38
+     *
39
+     * @param array $collection
40
+     * @param string $sanitize_callback
41
+     * @return array
42
+     */
43
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
44
+        foreach ($collection as &$lien) {
45
+            $t = $sanitize_callback($lien['texte']);
46
+            if ($t !== $lien['texte']) {
47
+                $lien['raw'] = str_replace($lien['texte'], $t, (string) $lien['raw']);
48
+                $lien['texte'] = $t;
49
+            }
50
+            $href = $sanitize_callback($lien['href']);
51
+            if ($href !== $lien['href']) {
52
+                $lien['raw'] = str_replace($lien['href'], $href, (string) $lien['raw']);
53
+                $lien['href'] = $href;
54
+            }
55
+        }
56
+
57
+        return $collection;
58
+    }
59
+
60
+    /**
61
+     * @param string $texte
62
+     * @param array $options
63
+     *   bool $collecter_liens
64
+     * @return array
65
+     */
66
+    public function collecter(string $texte, array $options = []): array {
67
+        if (!$texte) {
68
+            return [];
69
+        }
70
+
71
+        $liens = [];
72
+        if (str_contains($texte, '->')) {
73
+            $desechappe_crochets = false;
74
+            // si il y a un crochet ouvrant échappé ou un crochet fermant échappé, les substituer pour les ignorer
75
+            if (str_contains($texte, '\[') || str_contains($texte, '\]')) {
76
+                $texte = str_replace(['\[', '\]'], ["\x1\x5", "\x1\x6"], $texte);
77
+                $desechappe_crochets = true;
78
+            }
79
+
80
+            // collecter les matchs de la preg
81
+            $liens = static::collecteur($texte, '->', '[', $this->preg_lien, empty($options['detecter_presence']) ? 0 : 1);
82
+
83
+            // si on veut seulement detecter la présence, on peut retourner tel quel
84
+            if (empty($options['detecter_presence'])) {
85
+                foreach ($liens as $k => &$lien) {
86
+                    $lien['href'] = end($lien['match']);
87
+                    $lien['texte'] = $lien['match'][1];
88
+                    $lien['ouvrant'] = $lien['match'][3] ?? '';
89
+
90
+                    // la mise en lien automatique est passee par la a tort !
91
+                    // corrigeons pour eviter d'avoir un <a...> dans un href...
92
+                    if (str_starts_with((string) $lien['href'], '<a')) {
93
+                        $href = extraire_attribut($lien['href'], 'href');
94
+                        // remplacons dans la source qui peut etre reinjectee dans les arguments
95
+                        // d'un modele
96
+                        $lien['raw'] = str_replace($lien['href'], $href, (string) $lien['raw']);
97
+                        // et prenons le href comme la vraie url a linker
98
+                        $lien['href'] = $href;
99
+                    }
100
+
101
+                    if ($desechappe_crochets && str_contains((string) $lien['raw'], "\x1")) {
102
+                        $lien['raw'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['raw']);
103
+                        $lien['texte'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['texte']);
104
+                        $lien['href'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], (string) $lien['href']);
105
+                    }
106
+                }
107
+            }
108
+        }
109
+
110
+        return $liens;
111
+    }
112 112
 }
Please login to merge, or discard this patch.
ecrire/inc/layer.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -10,7 +10,7 @@  discard block
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 /**
@@ -25,68 +25,68 @@  discard block
 block discarded – undo
25 25
  * @return string Code HTML du cadre dépliable
26 26
  **/
27 27
 function cadre_depliable($icone, $titre, $deplie, $contenu, $ids = '', $style_cadre = 'r') {
28
-	$bouton = bouton_block_depliable($titre, $deplie, $ids);
28
+    $bouton = bouton_block_depliable($titre, $deplie, $ids);
29 29
 
30
-	return
31
-		debut_cadre($style_cadre, $icone, '', $bouton, '', '', false)
32
-		. debut_block_depliable($deplie, $ids)
33
-		. "<div class='cadre_padding'>\n"
34
-		. $contenu
35
-		. "</div>\n"
36
-		. fin_block()
37
-		. fin_cadre();
30
+    return
31
+        debut_cadre($style_cadre, $icone, '', $bouton, '', '', false)
32
+        . debut_block_depliable($deplie, $ids)
33
+        . "<div class='cadre_padding'>\n"
34
+        . $contenu
35
+        . "</div>\n"
36
+        . fin_block()
37
+        . fin_cadre();
38 38
 }
39 39
 
40 40
 function block_parfois_visible($nom, $invite, $masque, $style = '', $visible = false) {
41
-	return "\n"
42
-	. bouton_block_depliable($invite, $visible, $nom)
43
-	. debut_block_depliable($visible, $nom)
44
-	. $masque
45
-	. fin_block();
41
+    return "\n"
42
+    . bouton_block_depliable($invite, $visible, $nom)
43
+    . debut_block_depliable($visible, $nom)
44
+    . $masque
45
+    . fin_block();
46 46
 }
47 47
 
48 48
 function debut_block_depliable($deplie, $id = '') {
49
-	$class = ' blocdeplie';
50
-	// si on n'accepte pas js, ne pas fermer
51
-	if (!$deplie) {
52
-		$class = ' blocreplie';
53
-	}
49
+    $class = ' blocdeplie';
50
+    // si on n'accepte pas js, ne pas fermer
51
+    if (!$deplie) {
52
+        $class = ' blocreplie';
53
+    }
54 54
 
55
-	return '<div ' . ($id ? "id='$id' " : '') . "class='bloc_depliable$class'>";
55
+    return '<div ' . ($id ? "id='$id' " : '') . "class='bloc_depliable$class'>";
56 56
 }
57 57
 
58 58
 function fin_block() {
59
-	return "<div class='nettoyeur'></div>\n</div>";
59
+    return "<div class='nettoyeur'></div>\n</div>";
60 60
 }
61 61
 
62 62
 // $texte : texte du bouton
63 63
 // $deplie : true (deplie) ou false (plie) ou -1 (inactif) ou 'incertain' pour que le bouton s'auto init au chargement de la page
64 64
 // $ids : id des div lies au bouton (facultatif, par defaut c'est le div.bloc_depliable qui suit)
65 65
 function bouton_block_depliable($texte, $deplie, $ids = '') {
66
-	$bouton_id = 'b' . substr(md5($texte . microtime()), 0, 8);
66
+    $bouton_id = 'b' . substr(md5($texte . microtime()), 0, 8);
67 67
 
68
-	$class = ($deplie === true) ? ' deplie' : (($deplie == -1) ? ' impliable' : ' replie');
69
-	if (strlen((string) $ids)) {
70
-		$cible = explode(',', (string) $ids);
71
-		$cible = '#' . implode(',#', $cible);
72
-	} else {
73
-		$cible = "#$bouton_id + div.bloc_depliable";
74
-	}
68
+    $class = ($deplie === true) ? ' deplie' : (($deplie == -1) ? ' impliable' : ' replie');
69
+    if (strlen((string) $ids)) {
70
+        $cible = explode(',', (string) $ids);
71
+        $cible = '#' . implode(',#', $cible);
72
+    } else {
73
+        $cible = "#$bouton_id + div.bloc_depliable";
74
+    }
75 75
 
76
-	$b = (str_contains((string) $texte, '<h') ? 'div' : 'h3');
76
+    $b = (str_contains((string) $texte, '<h') ? 'div' : 'h3');
77 77
 
78
-	return "<$b "
79
-	. ($bouton_id ? "id='$bouton_id' " : '')
80
-	. "class='titrem$class'"
81
-	. (($deplie === -1)
82
-		? ''
83
-		: " onmouseover=\"jQuery(this).depliant('$cible');\""
84
-	)
85
-	. '>'
86
-	// une ancre pour rendre accessible au clavier le depliage du sous bloc
87
-	. "<a href='#' onclick=\"return jQuery(this).depliant_clicancre('$cible');\" class='titremancre'></a>"
88
-	. "$texte</$b>"
89
-	. http_script(($deplie === 'incertain')
90
-		? "jQuery(function($){if ($('$cible').is(':visible')) { $('#$bouton_id').addClass('deplie').removeClass('replie'); }});"
91
-		: '');
78
+    return "<$b "
79
+    . ($bouton_id ? "id='$bouton_id' " : '')
80
+    . "class='titrem$class'"
81
+    . (($deplie === -1)
82
+        ? ''
83
+        : " onmouseover=\"jQuery(this).depliant('$cible');\""
84
+    )
85
+    . '>'
86
+    // une ancre pour rendre accessible au clavier le depliage du sous bloc
87
+    . "<a href='#' onclick=\"return jQuery(this).depliant_clicancre('$cible');\" class='titremancre'></a>"
88
+    . "$texte</$b>"
89
+    . http_script(($deplie === 'incertain')
90
+        ? "jQuery(function($){if ($('$cible').is(':visible')) { $('#$bouton_id').addClass('deplie').removeClass('replie'); }});"
91
+        : '');
92 92
 }
Please login to merge, or discard this patch.
ecrire/public/cacher.php 1 patch
Indentation   +314 added lines, -314 removed lines patch added patch discarded remove patch
@@ -10,7 +10,7 @@  discard block
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 /**
@@ -24,9 +24,9 @@  discard block
 block discarded – undo
24 24
  * @return string
25 25
  */
26 26
 function generer_nom_fichier_cache($contexte, $page) {
27
-	$u = md5(var_export([$contexte, $page], true));
27
+    $u = md5(var_export([$contexte, $page], true));
28 28
 
29
-	return $u . '.cache';
29
+    return $u . '.cache';
30 30
 }
31 31
 
32 32
 /**
@@ -42,26 +42,26 @@  discard block
 block discarded – undo
42 42
  * @return string
43 43
  */
44 44
 function cache_chemin_fichier($nom_cache, $ecrire = false) {
45
-	static $l1, $l2;
46
-	if (is_null($l1)) {
47
-		$length = (defined('_CACHE_PROFONDEUR_STOCKAGE') ? min(8, max(_CACHE_PROFONDEUR_STOCKAGE, 2)) : 4);
48
-		$l1 = (int) floor($length / 2);
49
-		$l2 = $length - $l1;
50
-	}
51
-	$d = substr((string) $nom_cache, 0, $l1);
52
-	$u = substr((string) $nom_cache, $l1, $l2);
53
-
54
-	if ($ecrire) {
55
-		$rep = sous_repertoire(_DIR_CACHE, '', false, true);
56
-		$rep = sous_repertoire($rep, 'calcul/', false, true);
57
-		$rep = sous_repertoire($rep, $d, false, true);
58
-	}
59
-	else {
60
-		// en lecture on essaye pas de creer les repertoires, on va au plus vite
61
-		$rep = _DIR_CACHE . "calcul/$d/";
62
-	}
63
-
64
-	return $rep . $u . '.cache';
45
+    static $l1, $l2;
46
+    if (is_null($l1)) {
47
+        $length = (defined('_CACHE_PROFONDEUR_STOCKAGE') ? min(8, max(_CACHE_PROFONDEUR_STOCKAGE, 2)) : 4);
48
+        $l1 = (int) floor($length / 2);
49
+        $l2 = $length - $l1;
50
+    }
51
+    $d = substr((string) $nom_cache, 0, $l1);
52
+    $u = substr((string) $nom_cache, $l1, $l2);
53
+
54
+    if ($ecrire) {
55
+        $rep = sous_repertoire(_DIR_CACHE, '', false, true);
56
+        $rep = sous_repertoire($rep, 'calcul/', false, true);
57
+        $rep = sous_repertoire($rep, $d, false, true);
58
+    }
59
+    else {
60
+        // en lecture on essaye pas de creer les repertoires, on va au plus vite
61
+        $rep = _DIR_CACHE . "calcul/$d/";
62
+    }
63
+
64
+    return $rep . $u . '.cache';
65 65
 }
66 66
 
67 67
 /**
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
  * @return bool
73 73
  */
74 74
 function ecrire_cache($nom_cache, $valeur) {
75
-	return ecrire_fichier(cache_chemin_fichier($nom_cache, true), serialize(['nom_cache' => $nom_cache, 'valeur' => $valeur]));
75
+    return ecrire_fichier(cache_chemin_fichier($nom_cache, true), serialize(['nom_cache' => $nom_cache, 'valeur' => $valeur]));
76 76
 }
77 77
 
78 78
 /**
@@ -82,33 +82,33 @@  discard block
 block discarded – undo
82 82
  * @return mixed
83 83
  */
84 84
 function lire_cache($nom_cache) {
85
-	$tmp = [];
86
-	if (
87
-		file_exists($f = cache_chemin_fichier($nom_cache))
88
-		&& lire_fichier($f, $tmp)
89
-		&& ($tmp = unserialize($tmp))
90
-		&& $tmp['nom_cache'] == $nom_cache
91
-		&& isset($tmp['valeur'])
92
-	) {
93
-		return $tmp['valeur'];
94
-	}
95
-
96
-	return false;
85
+    $tmp = [];
86
+    if (
87
+        file_exists($f = cache_chemin_fichier($nom_cache))
88
+        && lire_fichier($f, $tmp)
89
+        && ($tmp = unserialize($tmp))
90
+        && $tmp['nom_cache'] == $nom_cache
91
+        && isset($tmp['valeur'])
92
+    ) {
93
+        return $tmp['valeur'];
94
+    }
95
+
96
+    return false;
97 97
 }
98 98
 
99 99
 // Parano : on signe le cache, afin d'interdire un hack d'injection
100 100
 // dans notre memcache
101 101
 function cache_signature(&$page) {
102
-	if (!isset($GLOBALS['meta']['cache_signature'])) {
103
-		include_spip('inc/acces');
104
-		ecrire_meta(
105
-			'cache_signature',
106
-			hash('sha256', $_SERVER['DOCUMENT_ROOT'] . ($_SERVER['SERVER_SIGNATURE'] ?? '') . creer_uniqid()),
107
-			'non'
108
-		);
109
-	}
110
-
111
-	return crc32($GLOBALS['meta']['cache_signature'] . $page['texte']);
102
+    if (!isset($GLOBALS['meta']['cache_signature'])) {
103
+        include_spip('inc/acces');
104
+        ecrire_meta(
105
+            'cache_signature',
106
+            hash('sha256', $_SERVER['DOCUMENT_ROOT'] . ($_SERVER['SERVER_SIGNATURE'] ?? '') . creer_uniqid()),
107
+            'non'
108
+        );
109
+    }
110
+
111
+    return crc32($GLOBALS['meta']['cache_signature'] . $page['texte']);
112 112
 }
113 113
 
114 114
 /**
@@ -121,14 +121,14 @@  discard block
 block discarded – undo
121 121
  * @return array
122 122
  */
123 123
 function gzip_page($page) {
124
-	if (function_exists('gzcompress') && strlen((string) $page['texte']) > 16 * 1024) {
125
-		$page['gz'] = true;
126
-		$page['texte'] = gzcompress((string) $page['texte']);
127
-	} else {
128
-		$page['gz'] = false;
129
-	}
130
-
131
-	return $page;
124
+    if (function_exists('gzcompress') && strlen((string) $page['texte']) > 16 * 1024) {
125
+        $page['gz'] = true;
126
+        $page['texte'] = gzcompress((string) $page['texte']);
127
+    } else {
128
+        $page['gz'] = false;
129
+    }
130
+
131
+    return $page;
132 132
 }
133 133
 
134 134
 /**
@@ -141,10 +141,10 @@  discard block
 block discarded – undo
141 141
  * @return void
142 142
  */
143 143
 function gunzip_page(&$page) {
144
-	if ($page['gz']) {
145
-		$page['texte'] = gzuncompress($page['texte']);
146
-		$page['gz'] = false; // ne pas gzuncompress deux fois une meme page
147
-	}
144
+    if ($page['gz']) {
145
+        $page['texte'] = gzuncompress($page['texte']);
146
+        $page['gz'] = false; // ne pas gzuncompress deux fois une meme page
147
+    }
148 148
 }
149 149
 
150 150
 /**
@@ -159,72 +159,72 @@  discard block
 block discarded – undo
159 159
  * -1 si il faut calculer sans stocker en cache
160 160
  */
161 161
 function cache_valide(&$page, $date) {
162
-	$now = $_SERVER['REQUEST_TIME'];
163
-
164
-	// Apparition d'un nouvel article post-date ?
165
-	if (
166
-		isset($GLOBALS['meta']['post_dates'])
167
-		&& $GLOBALS['meta']['post_dates'] == 'non'
168
-		&& isset($GLOBALS['meta']['date_prochain_postdate'])
169
-		&& $now > $GLOBALS['meta']['date_prochain_postdate']
170
-	) {
171
-		spip_log('Un article post-date invalide le cache');
172
-		include_spip('inc/rubriques');
173
-		calculer_prochain_postdate(true);
174
-	}
175
-
176
-	if (defined('_VAR_NOCACHE') && _VAR_NOCACHE) {
177
-		return -1;
178
-	}
179
-	if (isset($GLOBALS['meta']['cache_inhib']) && $_SERVER['REQUEST_TIME'] < $GLOBALS['meta']['cache_inhib']) {
180
-		return -1;
181
-	}
182
-	if (defined('_NO_CACHE')) {
183
-		return (_NO_CACHE == 0 && !isset($page['texte'])) ? 1 : _NO_CACHE;
184
-	}
185
-
186
-	// pas de cache ? on le met a jour, sauf pour les bots (on leur calcule la page sans mise en cache)
187
-	if (!$page || !isset($page['texte']) || !isset($page['entetes']['X-Spip-Cache'])) {
188
-		return _IS_BOT ? -1 : 1;
189
-	}
190
-
191
-	// controle de la signature
192
-	if ($page['sig'] !== cache_signature($page)) {
193
-		return _IS_BOT ? -1 : 1;
194
-	}
195
-
196
-	// #CACHE{n,statique} => on n'invalide pas avec derniere_modif
197
-	// cf. ecrire/public/balises.php, balise_CACHE_dist()
198
-	// Cache invalide par la meta 'derniere_modif'
199
-	// sauf pour les bots, qui utilisent toujours le cache
200
-	if (
201
-		(!isset($page['entetes']['X-Spip-Statique']) || $page['entetes']['X-Spip-Statique'] !== 'oui')
202
-		&& (
203
-			!_IS_BOT
204
-			&& $GLOBALS['derniere_modif_invalide']
205
-			&& isset($GLOBALS['meta']['derniere_modif'])
206
-			&& $date < $GLOBALS['meta']['derniere_modif']
207
-		)
208
-	) {
209
-		return 1;
210
-	}
211
-
212
-	// Sinon comparer l'age du fichier a sa duree de cache
213
-	$duree = (int) $page['entetes']['X-Spip-Cache'];
214
-	$cache_mark = ($GLOBALS['meta']['cache_mark'] ?? 0);
215
-	if ($duree == 0) {  #CACHE{0}
216
-	return -1;
217
-	} // sauf pour les bots, qui utilisent toujours le cache
218
-	else {
219
-		if (
220
-			!_IS_BOT && $date + $duree < $now
221
-			|| $date < $cache_mark
222
-		) {
223
-			return _IS_BOT ? -1 : 1;
224
-		} else {
225
-			return 0;
226
-		}
227
-	}
162
+    $now = $_SERVER['REQUEST_TIME'];
163
+
164
+    // Apparition d'un nouvel article post-date ?
165
+    if (
166
+        isset($GLOBALS['meta']['post_dates'])
167
+        && $GLOBALS['meta']['post_dates'] == 'non'
168
+        && isset($GLOBALS['meta']['date_prochain_postdate'])
169
+        && $now > $GLOBALS['meta']['date_prochain_postdate']
170
+    ) {
171
+        spip_log('Un article post-date invalide le cache');
172
+        include_spip('inc/rubriques');
173
+        calculer_prochain_postdate(true);
174
+    }
175
+
176
+    if (defined('_VAR_NOCACHE') && _VAR_NOCACHE) {
177
+        return -1;
178
+    }
179
+    if (isset($GLOBALS['meta']['cache_inhib']) && $_SERVER['REQUEST_TIME'] < $GLOBALS['meta']['cache_inhib']) {
180
+        return -1;
181
+    }
182
+    if (defined('_NO_CACHE')) {
183
+        return (_NO_CACHE == 0 && !isset($page['texte'])) ? 1 : _NO_CACHE;
184
+    }
185
+
186
+    // pas de cache ? on le met a jour, sauf pour les bots (on leur calcule la page sans mise en cache)
187
+    if (!$page || !isset($page['texte']) || !isset($page['entetes']['X-Spip-Cache'])) {
188
+        return _IS_BOT ? -1 : 1;
189
+    }
190
+
191
+    // controle de la signature
192
+    if ($page['sig'] !== cache_signature($page)) {
193
+        return _IS_BOT ? -1 : 1;
194
+    }
195
+
196
+    // #CACHE{n,statique} => on n'invalide pas avec derniere_modif
197
+    // cf. ecrire/public/balises.php, balise_CACHE_dist()
198
+    // Cache invalide par la meta 'derniere_modif'
199
+    // sauf pour les bots, qui utilisent toujours le cache
200
+    if (
201
+        (!isset($page['entetes']['X-Spip-Statique']) || $page['entetes']['X-Spip-Statique'] !== 'oui')
202
+        && (
203
+            !_IS_BOT
204
+            && $GLOBALS['derniere_modif_invalide']
205
+            && isset($GLOBALS['meta']['derniere_modif'])
206
+            && $date < $GLOBALS['meta']['derniere_modif']
207
+        )
208
+    ) {
209
+        return 1;
210
+    }
211
+
212
+    // Sinon comparer l'age du fichier a sa duree de cache
213
+    $duree = (int) $page['entetes']['X-Spip-Cache'];
214
+    $cache_mark = ($GLOBALS['meta']['cache_mark'] ?? 0);
215
+    if ($duree == 0) {  #CACHE{0}
216
+    return -1;
217
+    } // sauf pour les bots, qui utilisent toujours le cache
218
+    else {
219
+        if (
220
+            !_IS_BOT && $date + $duree < $now
221
+            || $date < $cache_mark
222
+        ) {
223
+            return _IS_BOT ? -1 : 1;
224
+        } else {
225
+            return 0;
226
+        }
227
+    }
228 228
 }
229 229
 
230 230
 /**
@@ -237,59 +237,59 @@  discard block
 block discarded – undo
237 237
  */
238 238
 function creer_cache(&$page, &$chemin_cache) {
239 239
 
240
-	// Ne rien faire si on est en preview, debug, ou si une erreur
241
-	// grave s'est presentee (compilation du squelette, MySQL, etc)
242
-	// le cas var_nocache ne devrait jamais arriver ici (securite)
243
-	// le cas spip_interdire_cache correspond a une ereur SQL grave non anticipable
244
-	if (
245
-		defined('_VAR_NOCACHE') && _VAR_NOCACHE
246
-		|| defined('spip_interdire_cache')
247
-	) {
248
-		return;
249
-	}
250
-
251
-	// Si la page c1234 a un invalideur de session 'zz', sauver dans
252
-	// 'tmp/cache/MD5(chemin_cache)_zz'
253
-	if (
254
-		isset($page['invalideurs'])
255
-		&& isset($page['invalideurs']['session'])
256
-	) {
257
-		// on verifie que le contenu du chemin cache indique seulement
258
-		// "cache sessionne" ; sa date indique la date de validite
259
-		// des caches sessionnes
260
-		if (!$tmp = lire_cache($chemin_cache)) {
261
-			spip_log('Creation cache sessionne ' . $chemin_cache);
262
-			$tmp = [
263
-				'invalideurs' => ['session' => ''],
264
-				'lastmodified' => $_SERVER['REQUEST_TIME']
265
-			];
266
-			ecrire_cache($chemin_cache, $tmp);
267
-		}
268
-		$chemin_cache = generer_nom_fichier_cache(
269
-			['chemin_cache' => $chemin_cache],
270
-			['session' => $page['invalideurs']['session']]
271
-		);
272
-	}
273
-
274
-	// ajouter la date de production dans le cache lui meme
275
-	// (qui contient deja sa duree de validite)
276
-	$page['lastmodified'] = $_SERVER['REQUEST_TIME'];
277
-
278
-	// compresser le contenu si besoin
279
-	$pagez = gzip_page($page);
280
-
281
-	// signer le contenu
282
-	$pagez['sig'] = cache_signature($pagez);
283
-
284
-	// l'enregistrer, compresse ou non...
285
-	$ok = ecrire_cache($chemin_cache, $pagez);
286
-
287
-	spip_log((_IS_BOT ? 'Bot:' : '') . "Creation du cache $chemin_cache pour "
288
-		. $page['entetes']['X-Spip-Cache'] . ' secondes' . ($ok ? '' : ' (erreur!)'), _LOG_INFO);
289
-
290
-	// Inserer ses invalideurs
291
-	include_spip('inc/invalideur');
292
-	maj_invalideurs($chemin_cache, $page);
240
+    // Ne rien faire si on est en preview, debug, ou si une erreur
241
+    // grave s'est presentee (compilation du squelette, MySQL, etc)
242
+    // le cas var_nocache ne devrait jamais arriver ici (securite)
243
+    // le cas spip_interdire_cache correspond a une ereur SQL grave non anticipable
244
+    if (
245
+        defined('_VAR_NOCACHE') && _VAR_NOCACHE
246
+        || defined('spip_interdire_cache')
247
+    ) {
248
+        return;
249
+    }
250
+
251
+    // Si la page c1234 a un invalideur de session 'zz', sauver dans
252
+    // 'tmp/cache/MD5(chemin_cache)_zz'
253
+    if (
254
+        isset($page['invalideurs'])
255
+        && isset($page['invalideurs']['session'])
256
+    ) {
257
+        // on verifie que le contenu du chemin cache indique seulement
258
+        // "cache sessionne" ; sa date indique la date de validite
259
+        // des caches sessionnes
260
+        if (!$tmp = lire_cache($chemin_cache)) {
261
+            spip_log('Creation cache sessionne ' . $chemin_cache);
262
+            $tmp = [
263
+                'invalideurs' => ['session' => ''],
264
+                'lastmodified' => $_SERVER['REQUEST_TIME']
265
+            ];
266
+            ecrire_cache($chemin_cache, $tmp);
267
+        }
268
+        $chemin_cache = generer_nom_fichier_cache(
269
+            ['chemin_cache' => $chemin_cache],
270
+            ['session' => $page['invalideurs']['session']]
271
+        );
272
+    }
273
+
274
+    // ajouter la date de production dans le cache lui meme
275
+    // (qui contient deja sa duree de validite)
276
+    $page['lastmodified'] = $_SERVER['REQUEST_TIME'];
277
+
278
+    // compresser le contenu si besoin
279
+    $pagez = gzip_page($page);
280
+
281
+    // signer le contenu
282
+    $pagez['sig'] = cache_signature($pagez);
283
+
284
+    // l'enregistrer, compresse ou non...
285
+    $ok = ecrire_cache($chemin_cache, $pagez);
286
+
287
+    spip_log((_IS_BOT ? 'Bot:' : '') . "Creation du cache $chemin_cache pour "
288
+        . $page['entetes']['X-Spip-Cache'] . ' secondes' . ($ok ? '' : ' (erreur!)'), _LOG_INFO);
289
+
290
+    // Inserer ses invalideurs
291
+    include_spip('inc/invalideur');
292
+    maj_invalideurs($chemin_cache, $page);
293 293
 }
294 294
 
295 295
 
@@ -302,15 +302,15 @@  discard block
 block discarded – undo
302 302
  * @return void
303 303
  */
304 304
 function nettoyer_petit_cache($prefix, $duree = 300) {
305
-	// determiner le repertoire a purger : 'tmp/CACHE/rech/'
306
-	$dircache = sous_repertoire(_DIR_CACHE, $prefix);
307
-	if (spip_touch($dircache . 'purger_' . $prefix, $duree, true)) {
308
-		foreach (preg_files($dircache, '[.]txt$') as $f) {
309
-			if ($_SERVER['REQUEST_TIME'] - (@file_exists($f) ? @filemtime($f) : 0) > $duree) {
310
-				spip_unlink($f);
311
-			}
312
-		}
313
-	}
305
+    // determiner le repertoire a purger : 'tmp/CACHE/rech/'
306
+    $dircache = sous_repertoire(_DIR_CACHE, $prefix);
307
+    if (spip_touch($dircache . 'purger_' . $prefix, $duree, true)) {
308
+        foreach (preg_files($dircache, '[.]txt$') as $f) {
309
+            if ($_SERVER['REQUEST_TIME'] - (@file_exists($f) ? @filemtime($f) : 0) > $duree) {
310
+                spip_unlink($f);
311
+            }
312
+        }
313
+    }
314 314
 }
315 315
 
316 316
 
@@ -338,132 +338,132 @@  discard block
 block discarded – undo
338 338
  */
339 339
 function public_cacher_dist($contexte, &$use_cache, &$chemin_cache, &$page, &$lastmodified) {
340 340
 
341
-	# fonction de cache minimale : dire "non on ne met rien en cache"
342
-	# $use_cache = -1; return;
343
-
344
-	// Second appel, destine a l'enregistrement du cache sur le disque
345
-	if (isset($chemin_cache)) {
346
-		creer_cache($page, $chemin_cache);
347
-		return;
348
-	}
349
-
350
-	// Toute la suite correspond au premier appel
351
-	$contexte_implicite = $page['contexte_implicite'];
352
-
353
-	// Cas ignorant le cache car completement dynamique
354
-	if (
355
-		!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST'
356
-		|| _request('connect')
357
-	) {
358
-		$use_cache = -1;
359
-		$lastmodified = 0;
360
-		$chemin_cache = '';
361
-		$page = [];
362
-
363
-		return;
364
-	}
365
-
366
-	// Controler l'existence d'un cache nous correspondant
367
-	$chemin_cache = generer_nom_fichier_cache($contexte, $page);
368
-	$lastmodified = 0;
369
-
370
-	// charger le cache s'il existe (et si il a bien le bon hash = anticollision)
371
-	if (!$page = lire_cache($chemin_cache)) {
372
-		$page = [];
373
-	}
374
-
375
-	// s'il est sessionne, charger celui correspondant a notre session
376
-	if (
377
-		isset($page['invalideurs'])
378
-		&& isset($page['invalideurs']['session'])
379
-	) {
380
-		$chemin_cache_session = generer_nom_fichier_cache(
381
-			['chemin_cache' => $chemin_cache],
382
-			['session' => spip_session()]
383
-		);
384
-		if (
385
-			($page_session = lire_cache($chemin_cache_session)) && $page_session['lastmodified'] >= $page['lastmodified']
386
-		) {
387
-			$page = $page_session;
388
-		} else {
389
-			$page = [];
390
-		}
391
-	}
392
-
393
-
394
-	// Faut-il effacer des pages invalidees (en particulier ce cache-ci) ?
395
-	// ne le faire que si la base est disponible
396
-	if (isset($GLOBALS['meta']['invalider']) && spip_connect()) {
397
-		include_spip('inc/invalideur');
398
-		retire_caches($chemin_cache);
399
-		# API invalideur inutile
400
-		supprimer_fichier(_DIR_CACHE . $chemin_cache);
401
-		if (isset($chemin_cache_session) && $chemin_cache_session) {
402
-			supprimer_fichier(_DIR_CACHE . $chemin_cache_session);
403
-		}
404
-	}
405
-
406
-	// Si un calcul, recalcul [ou preview, mais c'est recalcul] est demande,
407
-	// on supprime le cache
408
-	if (
409
-		defined('_VAR_MODE') &&
410
-		_VAR_MODE &&
411
-		(isset($_COOKIE['spip_session']) ||
412
-			isset($_COOKIE['spip_admin']) ||
413
-			@file_exists(_ACCESS_FILE_NAME))
414
-	) {
415
-		$page = ['contexte_implicite' => $contexte_implicite]; // ignorer le cache deja lu
416
-		include_spip('inc/invalideur');
417
-		retire_caches($chemin_cache); # API invalideur inutile
418
-		supprimer_fichier(_DIR_CACHE . $chemin_cache);
419
-		if (isset($chemin_cache_session) && $chemin_cache_session) {
420
-			supprimer_fichier(_DIR_CACHE . $chemin_cache_session);
421
-		}
422
-	}
423
-
424
-	// $delais par defaut
425
-	// pour toutes les pages sans #CACHE{} hors modeles/ et espace privé
426
-	// qui sont a cache nul par defaut
427
-	if (!isset($GLOBALS['delais'])) {
428
-		if (!defined('_DUREE_CACHE_DEFAUT')) {
429
-			define('_DUREE_CACHE_DEFAUT', 24 * 3600);
430
-		}
431
-		$GLOBALS['delais'] = _DUREE_CACHE_DEFAUT;
432
-	}
433
-
434
-	// determiner la validite de la page
435
-	if ($page) {
436
-		$use_cache = cache_valide($page, $page['lastmodified'] ?? 0);
437
-		// le contexte implicite n'est pas stocke dans le cache, mais il y a equivalence
438
-		// par le nom du cache. On le reinjecte donc ici pour utilisation eventuelle au calcul
439
-		$page['contexte_implicite'] = $contexte_implicite;
440
-		if (!$use_cache) {
441
-			// $page est un cache utilisable
442
-			gunzip_page($page);
443
-
444
-			return;
445
-		}
446
-	} else {
447
-		$page = ['contexte_implicite' => $contexte_implicite];
448
-		$use_cache = cache_valide($page, 0); // fichier cache absent : provoque le calcul
449
-	}
450
-
451
-	// Si pas valide mais pas de connexion a la base, le garder quand meme
452
-	if (!spip_connect()) {
453
-		if (isset($page['texte'])) {
454
-			gunzip_page($page);
455
-			$use_cache = 0;
456
-		} else {
457
-			spip_log("Erreur base de donnees, impossible utiliser $chemin_cache");
458
-			include_spip('inc/minipres');
459
-
460
-			return minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
461
-		}
462
-	}
463
-
464
-	if ($use_cache < 0) {
465
-		$chemin_cache = '';
466
-	}
467
-
468
-	return;
341
+    # fonction de cache minimale : dire "non on ne met rien en cache"
342
+    # $use_cache = -1; return;
343
+
344
+    // Second appel, destine a l'enregistrement du cache sur le disque
345
+    if (isset($chemin_cache)) {
346
+        creer_cache($page, $chemin_cache);
347
+        return;
348
+    }
349
+
350
+    // Toute la suite correspond au premier appel
351
+    $contexte_implicite = $page['contexte_implicite'];
352
+
353
+    // Cas ignorant le cache car completement dynamique
354
+    if (
355
+        !empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST'
356
+        || _request('connect')
357
+    ) {
358
+        $use_cache = -1;
359
+        $lastmodified = 0;
360
+        $chemin_cache = '';
361
+        $page = [];
362
+
363
+        return;
364
+    }
365
+
366
+    // Controler l'existence d'un cache nous correspondant
367
+    $chemin_cache = generer_nom_fichier_cache($contexte, $page);
368
+    $lastmodified = 0;
369
+
370
+    // charger le cache s'il existe (et si il a bien le bon hash = anticollision)
371
+    if (!$page = lire_cache($chemin_cache)) {
372
+        $page = [];
373
+    }
374
+
375
+    // s'il est sessionne, charger celui correspondant a notre session
376
+    if (
377
+        isset($page['invalideurs'])
378
+        && isset($page['invalideurs']['session'])
379
+    ) {
380
+        $chemin_cache_session = generer_nom_fichier_cache(
381
+            ['chemin_cache' => $chemin_cache],
382
+            ['session' => spip_session()]
383
+        );
384
+        if (
385
+            ($page_session = lire_cache($chemin_cache_session)) && $page_session['lastmodified'] >= $page['lastmodified']
386
+        ) {
387
+            $page = $page_session;
388
+        } else {
389
+            $page = [];
390
+        }
391
+    }
392
+
393
+
394
+    // Faut-il effacer des pages invalidees (en particulier ce cache-ci) ?
395
+    // ne le faire que si la base est disponible
396
+    if (isset($GLOBALS['meta']['invalider']) && spip_connect()) {
397
+        include_spip('inc/invalideur');
398
+        retire_caches($chemin_cache);
399
+        # API invalideur inutile
400
+        supprimer_fichier(_DIR_CACHE . $chemin_cache);
401
+        if (isset($chemin_cache_session) && $chemin_cache_session) {
402
+            supprimer_fichier(_DIR_CACHE . $chemin_cache_session);
403
+        }
404
+    }
405
+
406
+    // Si un calcul, recalcul [ou preview, mais c'est recalcul] est demande,
407
+    // on supprime le cache
408
+    if (
409
+        defined('_VAR_MODE') &&
410
+        _VAR_MODE &&
411
+        (isset($_COOKIE['spip_session']) ||
412
+            isset($_COOKIE['spip_admin']) ||
413
+            @file_exists(_ACCESS_FILE_NAME))
414
+    ) {
415
+        $page = ['contexte_implicite' => $contexte_implicite]; // ignorer le cache deja lu
416
+        include_spip('inc/invalideur');
417
+        retire_caches($chemin_cache); # API invalideur inutile
418
+        supprimer_fichier(_DIR_CACHE . $chemin_cache);
419
+        if (isset($chemin_cache_session) && $chemin_cache_session) {
420
+            supprimer_fichier(_DIR_CACHE . $chemin_cache_session);
421
+        }
422
+    }
423
+
424
+    // $delais par defaut
425
+    // pour toutes les pages sans #CACHE{} hors modeles/ et espace privé
426
+    // qui sont a cache nul par defaut
427
+    if (!isset($GLOBALS['delais'])) {
428
+        if (!defined('_DUREE_CACHE_DEFAUT')) {
429
+            define('_DUREE_CACHE_DEFAUT', 24 * 3600);
430
+        }
431
+        $GLOBALS['delais'] = _DUREE_CACHE_DEFAUT;
432
+    }
433
+
434
+    // determiner la validite de la page
435
+    if ($page) {
436
+        $use_cache = cache_valide($page, $page['lastmodified'] ?? 0);
437
+        // le contexte implicite n'est pas stocke dans le cache, mais il y a equivalence
438
+        // par le nom du cache. On le reinjecte donc ici pour utilisation eventuelle au calcul
439
+        $page['contexte_implicite'] = $contexte_implicite;
440
+        if (!$use_cache) {
441
+            // $page est un cache utilisable
442
+            gunzip_page($page);
443
+
444
+            return;
445
+        }
446
+    } else {
447
+        $page = ['contexte_implicite' => $contexte_implicite];
448
+        $use_cache = cache_valide($page, 0); // fichier cache absent : provoque le calcul
449
+    }
450
+
451
+    // Si pas valide mais pas de connexion a la base, le garder quand meme
452
+    if (!spip_connect()) {
453
+        if (isset($page['texte'])) {
454
+            gunzip_page($page);
455
+            $use_cache = 0;
456
+        } else {
457
+            spip_log("Erreur base de donnees, impossible utiliser $chemin_cache");
458
+            include_spip('inc/minipres');
459
+
460
+            return minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
461
+        }
462
+    }
463
+
464
+    if ($use_cache < 0) {
465
+        $chemin_cache = '';
466
+    }
467
+
468
+    return;
469 469
 }
Please login to merge, or discard this patch.
ecrire/public/quete.php 1 patch
Indentation   +421 added lines, -421 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
 
@@ -32,16 +32,16 @@  discard block
 block discarded – undo
32 32
  * @return array|bool|null
33 33
  */
34 34
 function quete_virtuel($id_article, $connect) {
35
-	return sql_getfetsel(
36
-		'virtuel',
37
-		'spip_articles',
38
-		['id_article=' . (int) $id_article, "statut='publie'"],
39
-		'',
40
-		'',
41
-		'',
42
-		'',
43
-		$connect
44
-	);
35
+    return sql_getfetsel(
36
+        'virtuel',
37
+        'spip_articles',
38
+        ['id_article=' . (int) $id_article, "statut='publie'"],
39
+        '',
40
+        '',
41
+        '',
42
+        '',
43
+        $connect
44
+    );
45 45
 }
46 46
 
47 47
 /**
@@ -56,39 +56,39 @@  discard block
 block discarded – undo
56 56
  * @return array
57 57
  */
58 58
 function quete_parent_lang($table, $id, string $connect = '') {
59
-	static $cache_quete = [];
60
-
61
-	if (!isset($cache_quete[$connect][$table][$id])) {
62
-		if (!isset($cache_quete[$connect][$table]['_select'])) {
63
-			$trouver_table = charger_fonction('trouver_table', 'base');
64
-			if (
65
-				!($desc = $trouver_table($table, $connect))
66
-				|| !isset($desc['field']['id_rubrique'])
67
-			) {
68
-				// pas de parent rubrique, on passe
69
-				$cache_quete[$connect][$table]['_select'] = false;
70
-			} else {
71
-				$select = ($table == 'spip_rubriques' ? 'id_parent' : 'id_rubrique');
72
-				$select .= isset($desc['field']['lang']) ? ', lang' : '';
73
-				$cache_quete[$connect][$table]['_select'] = $select;
74
-				$cache_quete[$connect][$table]['_id'] = id_table_objet(objet_type($table));
75
-			}
76
-		}
77
-		if ($cache_quete[$connect][$table]['_select']) {
78
-			$cache_quete[$connect][$table][$id] = sql_fetsel(
79
-				$cache_quete[$connect][$table]['_select'],
80
-				$table,
81
-				$cache_quete[$connect][$table]['_id'] . '=' . (int) $id,
82
-				'',
83
-				'',
84
-				'',
85
-				'',
86
-				$connect
87
-			);
88
-		}
89
-	}
90
-
91
-	return $cache_quete[$connect][$table][$id] ?? null;
59
+    static $cache_quete = [];
60
+
61
+    if (!isset($cache_quete[$connect][$table][$id])) {
62
+        if (!isset($cache_quete[$connect][$table]['_select'])) {
63
+            $trouver_table = charger_fonction('trouver_table', 'base');
64
+            if (
65
+                !($desc = $trouver_table($table, $connect))
66
+                || !isset($desc['field']['id_rubrique'])
67
+            ) {
68
+                // pas de parent rubrique, on passe
69
+                $cache_quete[$connect][$table]['_select'] = false;
70
+            } else {
71
+                $select = ($table == 'spip_rubriques' ? 'id_parent' : 'id_rubrique');
72
+                $select .= isset($desc['field']['lang']) ? ', lang' : '';
73
+                $cache_quete[$connect][$table]['_select'] = $select;
74
+                $cache_quete[$connect][$table]['_id'] = id_table_objet(objet_type($table));
75
+            }
76
+        }
77
+        if ($cache_quete[$connect][$table]['_select']) {
78
+            $cache_quete[$connect][$table][$id] = sql_fetsel(
79
+                $cache_quete[$connect][$table]['_select'],
80
+                $table,
81
+                $cache_quete[$connect][$table]['_id'] . '=' . (int) $id,
82
+                '',
83
+                '',
84
+                '',
85
+                '',
86
+                $connect
87
+            );
88
+        }
89
+    }
90
+
91
+    return $cache_quete[$connect][$table][$id] ?? null;
92 92
 }
93 93
 
94 94
 
@@ -105,11 +105,11 @@  discard block
 block discarded – undo
105 105
  * @return int
106 106
  */
107 107
 function quete_parent($id_rubrique, string $connect = '') {
108
-	if (!$id_rubrique = (int) $id_rubrique) {
109
-		return 0;
110
-	}
111
-	$id_parent = quete_parent_lang('spip_rubriques', $id_rubrique, $connect);
112
-	return $id_parent ? $id_parent['id_parent'] : 0;
108
+    if (!$id_rubrique = (int) $id_rubrique) {
109
+        return 0;
110
+    }
111
+    $id_parent = quete_parent_lang('spip_rubriques', $id_rubrique, $connect);
112
+    return $id_parent ? $id_parent['id_parent'] : 0;
113 113
 }
114 114
 
115 115
 /**
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
  * @return int
126 126
  */
127 127
 function quete_rubrique($id_article, $serveur) {
128
-	$id_parent = quete_parent_lang('spip_articles', $id_article, $serveur);
128
+    $id_parent = quete_parent_lang('spip_articles', $id_article, $serveur);
129 129
 
130
-	return $id_parent['id_rubrique'] ?? 0;
130
+    return $id_parent['id_rubrique'] ?? 0;
131 131
 }
132 132
 
133 133
 
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
  * @return int
141 141
  */
142 142
 function quete_profondeur($id, string $connect = '') {
143
-	$n = 0;
144
-	while ($id) {
145
-		$n++;
146
-		$id = quete_parent($id, $connect);
147
-	}
143
+    $n = 0;
144
+    while ($id) {
145
+        $n++;
146
+        $id = quete_parent($id, $connect);
147
+    }
148 148
 
149
-	return $n;
149
+    return $n;
150 150
 }
151 151
 
152 152
 
@@ -162,15 +162,15 @@  discard block
 block discarded – undo
162 162
  *     Morceau de la requête SQL testant la date
163 163
  */
164 164
 function quete_condition_postdates($champ_date, $serveur = '', $ignore_previsu = false) {
165
-	if (defined('_VAR_PREVIEW') && _VAR_PREVIEW && !$ignore_previsu) {
166
-		return '1=1';
167
-	}
168
-
169
-	return
170
-		(isset($GLOBALS['meta']['date_prochain_postdate'])
171
-			&& $GLOBALS['meta']['date_prochain_postdate'] > time())
172
-			? "$champ_date<" . sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
173
-			: '1=1';
165
+    if (defined('_VAR_PREVIEW') && _VAR_PREVIEW && !$ignore_previsu) {
166
+        return '1=1';
167
+    }
168
+
169
+    return
170
+        (isset($GLOBALS['meta']['date_prochain_postdate'])
171
+            && $GLOBALS['meta']['date_prochain_postdate'] > time())
172
+            ? "$champ_date<" . sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
173
+            : '1=1';
174 174
 }
175 175
 
176 176
 
@@ -190,101 +190,101 @@  discard block
 block discarded – undo
190 190
  * @return array|string
191 191
  */
192 192
 function quete_condition_statut($mstatut, $previsu, $publie, $serveur = '', $ignore_previsu = false) {
193
-	static $cond = [];
194
-	$key = func_get_args();
195
-	$key = implode('-', $key);
196
-	if (isset($cond[$key])) {
197
-		return $cond[$key];
198
-	}
199
-
200
-	$liste_statuts = $publie;
201
-	if (defined('_VAR_PREVIEW') && _VAR_PREVIEW && !$ignore_previsu) {
202
-		$liste_statuts = $previsu;
203
-	}
204
-	$not = false;
205
-	if (str_starts_with($liste_statuts, '!')) {
206
-		$not = true;
207
-		$liste_statuts = substr($liste_statuts, 1);
208
-	}
209
-	// '' => ne rien afficher, '!'=> ne rien filtrer
210
-	if (!strlen($liste_statuts)) {
211
-		return $cond[$key] = ($not ? '1=1' : '0=1');
212
-	}
213
-
214
-	$liste_statuts = explode(',', $liste_statuts);
215
-	$where = [];
216
-	foreach ($liste_statuts as $k => $v) {
217
-		// filtrage /auteur pour limiter les objets d'un statut (prepa en general)
218
-		// a ceux de l'auteur identifie
219
-		if (str_contains($v, '/')) {
220
-			$v = explode('/', $v);
221
-			$filtre = end($v);
222
-			$v = reset($v);
223
-			$v = preg_replace(',\W,', '', $v);
224
-			if (
225
-				$filtre == 'auteur'
226
-				&& str_contains($mstatut, '.')
227
-				&& ($objet = explode('.', $mstatut))
228
-				&& ($id_table = reset($objet))
229
-				&& ($objet = objet_type($id_table))
230
-			) {
231
-				$w = "$mstatut<>" . sql_quote($v);
232
-
233
-				// retrouver l’id_auteur qui a filé un lien de prévisu éventuellement,
234
-				// sinon l’auteur en session
235
-				include_spip('inc/securiser_action');
236
-				if ($desc = decrire_token_previsu()) {
237
-					$id_auteur = $desc['id_auteur'];
238
-				} elseif (isset($GLOBALS['visiteur_session']['id_auteur'])) {
239
-					$id_auteur = (int) $GLOBALS['visiteur_session']['id_auteur'];
240
-				} else {
241
-					$id_auteur = null;
242
-				}
243
-
244
-				// dans ce cas (admin en general), pas de filtrage sur ce statut
245
-				if (!autoriser('previsualiser' . $v, $objet, '', $id_auteur)) {
246
-					// si pas d'auteur identifie pas de sous-requete car pas d'article qui matche
247
-					if (!$id_auteur) {
248
-						$where[] = $w;
249
-					} else {
250
-						$primary = id_table_objet($objet);
251
-						$where[] = "($w OR $id_table.$primary IN (" . sql_get_select(
252
-							'ssss.id_objet',
253
-							'spip_auteurs_liens AS ssss',
254
-							'ssss.objet=' . sql_quote($objet) . ' AND ssss.id_auteur=' . (int) $id_auteur,
255
-							'',
256
-							'',
257
-							'',
258
-							'',
259
-							$serveur
260
-						) . '))';
261
-					}
262
-				}
263
-			} // ignorer ce statut si on ne sait pas comment le filtrer
264
-			else {
265
-				$v = '';
266
-			}
267
-		}
268
-		// securite
269
-		$liste_statuts[$k] = preg_replace(',\W,', '', $v);
270
-	}
271
-	$liste_statuts = array_filter($liste_statuts);
272
-	if (count($liste_statuts) == 1) {
273
-		$where[] = ['=', $mstatut, sql_quote(reset($liste_statuts), $serveur)];
274
-	} else {
275
-		$where[] = sql_in($mstatut, $liste_statuts, $not, $serveur);
276
-	}
277
-
278
-	while (count($where) > 1) {
279
-		$and = ['AND', array_pop($where), array_pop($where)];
280
-		$where[] = $and;
281
-	}
282
-	$cond[$key] = reset($where);
283
-	if ($not) {
284
-		$cond[$key] = ['NOT', $cond[$key]];
285
-	}
286
-
287
-	return $cond[$key];
193
+    static $cond = [];
194
+    $key = func_get_args();
195
+    $key = implode('-', $key);
196
+    if (isset($cond[$key])) {
197
+        return $cond[$key];
198
+    }
199
+
200
+    $liste_statuts = $publie;
201
+    if (defined('_VAR_PREVIEW') && _VAR_PREVIEW && !$ignore_previsu) {
202
+        $liste_statuts = $previsu;
203
+    }
204
+    $not = false;
205
+    if (str_starts_with($liste_statuts, '!')) {
206
+        $not = true;
207
+        $liste_statuts = substr($liste_statuts, 1);
208
+    }
209
+    // '' => ne rien afficher, '!'=> ne rien filtrer
210
+    if (!strlen($liste_statuts)) {
211
+        return $cond[$key] = ($not ? '1=1' : '0=1');
212
+    }
213
+
214
+    $liste_statuts = explode(',', $liste_statuts);
215
+    $where = [];
216
+    foreach ($liste_statuts as $k => $v) {
217
+        // filtrage /auteur pour limiter les objets d'un statut (prepa en general)
218
+        // a ceux de l'auteur identifie
219
+        if (str_contains($v, '/')) {
220
+            $v = explode('/', $v);
221
+            $filtre = end($v);
222
+            $v = reset($v);
223
+            $v = preg_replace(',\W,', '', $v);
224
+            if (
225
+                $filtre == 'auteur'
226
+                && str_contains($mstatut, '.')
227
+                && ($objet = explode('.', $mstatut))
228
+                && ($id_table = reset($objet))
229
+                && ($objet = objet_type($id_table))
230
+            ) {
231
+                $w = "$mstatut<>" . sql_quote($v);
232
+
233
+                // retrouver l’id_auteur qui a filé un lien de prévisu éventuellement,
234
+                // sinon l’auteur en session
235
+                include_spip('inc/securiser_action');
236
+                if ($desc = decrire_token_previsu()) {
237
+                    $id_auteur = $desc['id_auteur'];
238
+                } elseif (isset($GLOBALS['visiteur_session']['id_auteur'])) {
239
+                    $id_auteur = (int) $GLOBALS['visiteur_session']['id_auteur'];
240
+                } else {
241
+                    $id_auteur = null;
242
+                }
243
+
244
+                // dans ce cas (admin en general), pas de filtrage sur ce statut
245
+                if (!autoriser('previsualiser' . $v, $objet, '', $id_auteur)) {
246
+                    // si pas d'auteur identifie pas de sous-requete car pas d'article qui matche
247
+                    if (!$id_auteur) {
248
+                        $where[] = $w;
249
+                    } else {
250
+                        $primary = id_table_objet($objet);
251
+                        $where[] = "($w OR $id_table.$primary IN (" . sql_get_select(
252
+                            'ssss.id_objet',
253
+                            'spip_auteurs_liens AS ssss',
254
+                            'ssss.objet=' . sql_quote($objet) . ' AND ssss.id_auteur=' . (int) $id_auteur,
255
+                            '',
256
+                            '',
257
+                            '',
258
+                            '',
259
+                            $serveur
260
+                        ) . '))';
261
+                    }
262
+                }
263
+            } // ignorer ce statut si on ne sait pas comment le filtrer
264
+            else {
265
+                $v = '';
266
+            }
267
+        }
268
+        // securite
269
+        $liste_statuts[$k] = preg_replace(',\W,', '', $v);
270
+    }
271
+    $liste_statuts = array_filter($liste_statuts);
272
+    if (count($liste_statuts) == 1) {
273
+        $where[] = ['=', $mstatut, sql_quote(reset($liste_statuts), $serveur)];
274
+    } else {
275
+        $where[] = sql_in($mstatut, $liste_statuts, $not, $serveur);
276
+    }
277
+
278
+    while (count($where) > 1) {
279
+        $and = ['AND', array_pop($where), array_pop($where)];
280
+        $where[] = $and;
281
+    }
282
+    $cond[$key] = reset($where);
283
+    if ($not) {
284
+        $cond[$key] = ['NOT', $cond[$key]];
285
+    }
286
+
287
+    return $cond[$key];
288 288
 }
289 289
 
290 290
 /**
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
  * @return array|bool|null
296 296
  */
297 297
 function quete_fichier($id_document, $serveur = '') {
298
-	return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . (int) $id_document), '', [], '', '', $serveur);
298
+    return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . (int) $id_document), '', [], '', '', $serveur);
299 299
 }
300 300
 
301 301
 /**
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
  * @return array|bool
307 307
  */
308 308
 function quete_document($id_document, $serveur = '') {
309
-	return sql_fetsel('*', 'spip_documents', ('id_document=' . (int) $id_document), '', [], '', '', $serveur);
309
+    return sql_fetsel('*', 'spip_documents', ('id_document=' . (int) $id_document), '', [], '', '', $serveur);
310 310
 }
311 311
 
312 312
 /**
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
  * @return array|bool|null
318 318
  */
319 319
 function quete_meta($nom, $serveur) {
320
-	return sql_getfetsel('valeur', 'spip_meta', 'nom=' . sql_quote($nom), '', '', '', '', $serveur);
320
+    return sql_getfetsel('valeur', 'spip_meta', 'nom=' . sql_quote($nom), '', '', '', '', $serveur);
321 321
 }
322 322
 
323 323
 /**
@@ -343,67 +343,67 @@  discard block
 block discarded – undo
343 343
  *     Retourne soit un tableau, soit le chemin du fichier.
344 344
  */
345 345
 function quete_logo($cle_objet, $onoff, $id, $id_rubrique, $flag = false) {
346
-	include_spip('base/objets');
347
-	$nom = strtolower($onoff);
348
-
349
-	$cle_objet = id_table_objet($cle_objet);
350
-
351
-	while (1) {
352
-		$objet = objet_type($cle_objet);
353
-
354
-		$on = quete_logo_objet($id, $objet, $nom);
355
-
356
-		if ($on) {
357
-			if ($flag) {
358
-				return $on['fichier'];
359
-			} else {
360
-				$taille = @spip_getimagesize($on['chemin']);
361
-
362
-				// Si on a déjà demandé un survol directement ($onoff = off)
363
-				// ou qu'on a demandé uniquement le normal ($onoff = on)
364
-				// alors on ne cherche pas du tout le survol ici
365
-				$off = $onoff != 'ON' ? '' : quete_logo_objet($id, $objet, 'off');
366
-
367
-				// on retourne une url du type IMG/artonXX?timestamp
368
-				// qui permet de distinguer le changement de logo
369
-				// et placer un expire sur le dossier IMG/
370
-				$res = [
371
-					$on['chemin'] . ($on['timestamp'] ? "?{$on['timestamp']}" : ''),
372
-					($off ? $off['chemin'] . ($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
373
-					($taille ? ' ' . $taille[3] : (''))
374
-				];
375
-				$res['src'] = $res[0];
376
-				$res['logo_on'] = $res[0];
377
-				$res['logo_off'] = $res[1];
378
-				$res['width'] = ($taille ? $taille[0] : '');
379
-				$res['height'] = ($taille ? $taille[1] : '');
380
-				$res['fichier'] = $on['fichier'];
381
-				$res['titre'] = ($on['titre'] ?? '');
382
-				$res['descriptif'] = ($on['descriptif'] ?? '');
383
-				$res['credits'] = ($on['credits'] ?? '');
384
-				$res['alt'] = ($on['alt'] ?? '');
385
-				$res['id'] = ($on['id_document'] ?? 0);
386
-
387
-				return $res;
388
-			}
389
-		} else {
390
-			if (defined('_LOGO_RUBRIQUE_DESACTIVER_HERITAGE')) {
391
-				return '';
392
-			} else {
393
-				if ($id_rubrique) {
394
-					$cle_objet = 'id_rubrique';
395
-					$id = $id_rubrique;
396
-					$id_rubrique = 0;
397
-				} else {
398
-					if ($id && $cle_objet == 'id_rubrique') {
399
-						$id = quete_parent($id);
400
-					} else {
401
-						return '';
402
-					}
403
-				}
404
-			}
405
-		}
406
-	}
346
+    include_spip('base/objets');
347
+    $nom = strtolower($onoff);
348
+
349
+    $cle_objet = id_table_objet($cle_objet);
350
+
351
+    while (1) {
352
+        $objet = objet_type($cle_objet);
353
+
354
+        $on = quete_logo_objet($id, $objet, $nom);
355
+
356
+        if ($on) {
357
+            if ($flag) {
358
+                return $on['fichier'];
359
+            } else {
360
+                $taille = @spip_getimagesize($on['chemin']);
361
+
362
+                // Si on a déjà demandé un survol directement ($onoff = off)
363
+                // ou qu'on a demandé uniquement le normal ($onoff = on)
364
+                // alors on ne cherche pas du tout le survol ici
365
+                $off = $onoff != 'ON' ? '' : quete_logo_objet($id, $objet, 'off');
366
+
367
+                // on retourne une url du type IMG/artonXX?timestamp
368
+                // qui permet de distinguer le changement de logo
369
+                // et placer un expire sur le dossier IMG/
370
+                $res = [
371
+                    $on['chemin'] . ($on['timestamp'] ? "?{$on['timestamp']}" : ''),
372
+                    ($off ? $off['chemin'] . ($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
373
+                    ($taille ? ' ' . $taille[3] : (''))
374
+                ];
375
+                $res['src'] = $res[0];
376
+                $res['logo_on'] = $res[0];
377
+                $res['logo_off'] = $res[1];
378
+                $res['width'] = ($taille ? $taille[0] : '');
379
+                $res['height'] = ($taille ? $taille[1] : '');
380
+                $res['fichier'] = $on['fichier'];
381
+                $res['titre'] = ($on['titre'] ?? '');
382
+                $res['descriptif'] = ($on['descriptif'] ?? '');
383
+                $res['credits'] = ($on['credits'] ?? '');
384
+                $res['alt'] = ($on['alt'] ?? '');
385
+                $res['id'] = ($on['id_document'] ?? 0);
386
+
387
+                return $res;
388
+            }
389
+        } else {
390
+            if (defined('_LOGO_RUBRIQUE_DESACTIVER_HERITAGE')) {
391
+                return '';
392
+            } else {
393
+                if ($id_rubrique) {
394
+                    $cle_objet = 'id_rubrique';
395
+                    $id = $id_rubrique;
396
+                    $id_rubrique = 0;
397
+                } else {
398
+                    if ($id && $cle_objet == 'id_rubrique') {
399
+                        $id = quete_parent($id);
400
+                    } else {
401
+                        return '';
402
+                    }
403
+                }
404
+            }
405
+        }
406
+    }
407 407
 }
408 408
 
409 409
 /**
@@ -418,43 +418,43 @@  discard block
 block discarded – undo
418 418
  * @return bool|array
419 419
  **/
420 420
 function quete_logo_objet($id_objet, $objet, $mode) {
421
-	static $chercher_logo;
422
-	if (is_null($chercher_logo)) {
423
-		$chercher_logo = charger_fonction('chercher_logo', 'inc');
424
-	}
425
-	$cle_objet = id_table_objet($objet);
426
-
427
-	// On cherche pas la méthode classique
428
-	$infos_logo = $chercher_logo((int) $id_objet, $cle_objet, $mode);
429
-
430
-	// Si la méthode classique a trouvé quelque chose, on utilise le nouveau format
431
-	if (!empty($infos_logo)) {
432
-		$infos = [
433
-			'chemin' => $infos_logo[0],
434
-			'timestamp' => $infos_logo[4],
435
-			'id_document' => ($infos_logo[5]['id_document'] ?? ''),
436
-		];
437
-		foreach (['fichier', 'titre', 'descriptif', 'credits', 'alt'] as $champ) {
438
-			$infos[$champ] = ($infos_logo[5][$champ] ?? '');
439
-		}
440
-		$infos_logo = $infos;
441
-	}
442
-
443
-	// On passe cette recherche de logo dans un pipeline
444
-	$infos_logo = pipeline(
445
-		'quete_logo_objet',
446
-		[
447
-			'args' => [
448
-				'id_objet' => $id_objet,
449
-				'objet' => $objet,
450
-				'cle_objet' => $cle_objet,
451
-				'mode' => $mode,
452
-			],
453
-			'data' => $infos_logo,
454
-		]
455
-	);
456
-
457
-	return $infos_logo;
421
+    static $chercher_logo;
422
+    if (is_null($chercher_logo)) {
423
+        $chercher_logo = charger_fonction('chercher_logo', 'inc');
424
+    }
425
+    $cle_objet = id_table_objet($objet);
426
+
427
+    // On cherche pas la méthode classique
428
+    $infos_logo = $chercher_logo((int) $id_objet, $cle_objet, $mode);
429
+
430
+    // Si la méthode classique a trouvé quelque chose, on utilise le nouveau format
431
+    if (!empty($infos_logo)) {
432
+        $infos = [
433
+            'chemin' => $infos_logo[0],
434
+            'timestamp' => $infos_logo[4],
435
+            'id_document' => ($infos_logo[5]['id_document'] ?? ''),
436
+        ];
437
+        foreach (['fichier', 'titre', 'descriptif', 'credits', 'alt'] as $champ) {
438
+            $infos[$champ] = ($infos_logo[5][$champ] ?? '');
439
+        }
440
+        $infos_logo = $infos;
441
+    }
442
+
443
+    // On passe cette recherche de logo dans un pipeline
444
+    $infos_logo = pipeline(
445
+        'quete_logo_objet',
446
+        [
447
+            'args' => [
448
+                'id_objet' => $id_objet,
449
+                'objet' => $objet,
450
+                'cle_objet' => $cle_objet,
451
+                'mode' => $mode,
452
+            ],
453
+            'data' => $infos_logo,
454
+        ]
455
+    );
456
+
457
+    return $infos_logo;
458 458
 }
459 459
 
460 460
 /**
@@ -467,25 +467,25 @@  discard block
 block discarded – undo
467 467
  * @return bool|string
468 468
  */
469 469
 function quete_logo_file($row, $connect = null) {
470
-	include_spip('inc/documents');
471
-	$logo = vignette_logo_document($row, $connect);
472
-	if (!$logo) {
473
-		$logo = image_du_document($row, $connect);
474
-	}
475
-	if (!$logo) {
476
-		$f = charger_fonction('vignette', 'inc');
477
-		$logo = $f($row['extension'], false);
478
-	}
479
-	// si c'est une vignette type doc, la renvoyer direct
480
-	if (
481
-		strcmp((string) $logo, (string) _DIR_PLUGINS) == 0
482
-		|| strcmp((string) $logo, (string) _DIR_PLUGINS_DIST) == 0
483
-		|| strcmp((string) $logo, _DIR_RACINE . 'prive/') == 0
484
-	) {
485
-		return $logo;
486
-	}
487
-
488
-	return get_spip_doc($logo);
470
+    include_spip('inc/documents');
471
+    $logo = vignette_logo_document($row, $connect);
472
+    if (!$logo) {
473
+        $logo = image_du_document($row, $connect);
474
+    }
475
+    if (!$logo) {
476
+        $f = charger_fonction('vignette', 'inc');
477
+        $logo = $f($row['extension'], false);
478
+    }
479
+    // si c'est une vignette type doc, la renvoyer direct
480
+    if (
481
+        strcmp((string) $logo, (string) _DIR_PLUGINS) == 0
482
+        || strcmp((string) $logo, (string) _DIR_PLUGINS_DIST) == 0
483
+        || strcmp((string) $logo, _DIR_RACINE . 'prive/') == 0
484
+    ) {
485
+        return $logo;
486
+    }
487
+
488
+    return get_spip_doc($logo);
489 489
 }
490 490
 
491 491
 /**
@@ -513,20 +513,20 @@  discard block
 block discarded – undo
513 513
  */
514 514
 function quete_logo_document($row, $lien, $align, $mode_logo, $x, $y, string $connect = '') {
515 515
 
516
-	include_spip('inc/documents');
517
-	$logo = '';
518
-	if (!in_array($mode_logo, ['icone', 'apercu'])) {
519
-		$logo = vignette_logo_document($row, $connect);
520
-	}
521
-	// si on veut explicitement la vignette, ne rien renvoyer si il n'y en a pas
522
-	if ($mode_logo == 'vignette' && !$logo) {
523
-		return '';
524
-	}
525
-	if ($mode_logo == 'icone') {
526
-		$row['fichier'] = '';
527
-	}
528
-
529
-	return vignette_automatique($logo, $row, $lien, $x, $y, $align, null, $connect);
516
+    include_spip('inc/documents');
517
+    $logo = '';
518
+    if (!in_array($mode_logo, ['icone', 'apercu'])) {
519
+        $logo = vignette_logo_document($row, $connect);
520
+    }
521
+    // si on veut explicitement la vignette, ne rien renvoyer si il n'y en a pas
522
+    if ($mode_logo == 'vignette' && !$logo) {
523
+        return '';
524
+    }
525
+    if ($mode_logo == 'icone') {
526
+        $row['fichier'] = '';
527
+    }
528
+
529
+    return vignette_automatique($logo, $row, $lien, $x, $y, $align, null, $connect);
530 530
 }
531 531
 
532 532
 /**
@@ -538,26 +538,26 @@  discard block
 block discarded – undo
538 538
  */
539 539
 function quete_html_logo($logo, $align, $lien) {
540 540
 
541
-	if (!is_array($logo)) {
542
-		return '';
543
-	}
544
-
545
-	$contexte = [];
546
-	foreach ($logo as $k => $v) {
547
-		if (!is_numeric($k)) {
548
-			$contexte[$k] = $v;
549
-		}
550
-	}
551
-
552
-	foreach (['titre', 'descriptif', 'credits', 'alt'] as $champ) {
553
-		if (!empty($contexte[$champ])) {
554
-			$contexte[$champ] = appliquer_traitement_champ($contexte[$champ], $champ, 'document');
555
-		}
556
-	}
557
-
558
-	$contexte['align'] = $align;
559
-	$contexte['lien'] = $lien;
560
-	return recuperer_fond('modeles/logo', $contexte);
541
+    if (!is_array($logo)) {
542
+        return '';
543
+    }
544
+
545
+    $contexte = [];
546
+    foreach ($logo as $k => $v) {
547
+        if (!is_numeric($k)) {
548
+            $contexte[$k] = $v;
549
+        }
550
+    }
551
+
552
+    foreach (['titre', 'descriptif', 'credits', 'alt'] as $champ) {
553
+        if (!empty($contexte[$champ])) {
554
+            $contexte[$champ] = appliquer_traitement_champ($contexte[$champ], $champ, 'document');
555
+        }
556
+    }
557
+
558
+    $contexte['align'] = $align;
559
+    $contexte['lien'] = $lien;
560
+    return recuperer_fond('modeles/logo', $contexte);
561 561
 }
562 562
 
563 563
 /**
@@ -571,14 +571,14 @@  discard block
 block discarded – undo
571 571
  * @return string|false
572 572
  */
573 573
 function document_spip_externe($fichier, $connect) {
574
-	if ($connect) {
575
-		$site = quete_meta('adresse_site', $connect);
576
-		if ($site) {
577
-			$dir = quete_meta('dir_img', $connect);
578
-			return "$site/$dir$fichier";
579
-		}
580
-	}
581
-	return false;
574
+    if ($connect) {
575
+        $site = quete_meta('adresse_site', $connect);
576
+        if ($site) {
577
+            $dir = quete_meta('dir_img', $connect);
578
+            return "$site/$dir$fichier";
579
+        }
580
+    }
581
+    return false;
582 582
 }
583 583
 
584 584
 /**
@@ -591,23 +591,23 @@  discard block
 block discarded – undo
591 591
  */
592 592
 function vignette_logo_document($row, string $connect = '') {
593 593
 
594
-	if (!$row || empty($row['id_vignette'])) {
595
-		return '';
596
-	}
597
-	$fichier = quete_fichier($row['id_vignette'], $connect);
598
-	if ($url = document_spip_externe($fichier, $connect)) {
599
-		return $url;
600
-	}
601
-
602
-	$f = get_spip_doc($fichier);
603
-	if ($f && @file_exists($f)) {
604
-		return $f;
605
-	}
606
-	if ($row['mode'] !== 'vignette') {
607
-		return '';
608
-	}
609
-
610
-	return generer_objet_url($row['id_document'], 'document', '', '', null, '', $connect);
594
+    if (!$row || empty($row['id_vignette'])) {
595
+        return '';
596
+    }
597
+    $fichier = quete_fichier($row['id_vignette'], $connect);
598
+    if ($url = document_spip_externe($fichier, $connect)) {
599
+        return $url;
600
+    }
601
+
602
+    $f = get_spip_doc($fichier);
603
+    if ($f && @file_exists($f)) {
604
+        return $f;
605
+    }
606
+    if ($row['mode'] !== 'vignette') {
607
+        return '';
608
+    }
609
+
610
+    return generer_objet_url($row['id_document'], 'document', '', '', null, '', $connect);
611 611
 }
612 612
 
613 613
 /**
@@ -622,66 +622,66 @@  discard block
 block discarded – undo
622 622
  * @return bool|string
623 623
  */
624 624
 function calcul_exposer($id, $prim, $reference, $parent, $type, string $connect = '') {
625
-	static $exposer = [];
626
-
627
-	// Que faut-il exposer ? Tous les elements de $reference
628
-	// ainsi que leur hierarchie ; on ne fait donc ce calcul
629
-	// qu'une fois (par squelette) et on conserve le resultat
630
-	// en static.
631
-	if (!isset($exposer[$m = md5(serialize($reference))][$prim])) {
632
-		$principal = $reference[$type] ?? $reference["@$type"] ?? '';
633
-		// le parent fournit en argument est le parent de $id, pas celui de $principal
634
-		// il n'est donc pas utile
635
-		$parent = 0;
636
-		if (!$principal) { // regarder si un enfant est dans le contexte, auquel cas il expose peut etre le parent courant
637
-			$enfants = ['id_rubrique' => ['id_article'], 'id_groupe' => ['id_mot']];
638
-			if (isset($enfants[$type])) {
639
-				foreach ($enfants[$type] as $t) {
640
-					if (
641
-						isset($reference[$t])
642
-						// cas de la reference donnee dynamiquement par la pagination
643
-						|| isset($reference["@$t"])
644
-					) {
645
-						$type = $t;
646
-						$principal = $reference[$type] ?? $reference["@$type"];
647
-						continue;
648
-					}
649
-				}
650
-			}
651
-		}
652
-		$exposer[$m][$type] = [];
653
-		if ($principal) {
654
-			$principaux = is_array($principal) ? $principal : [$principal];
655
-			foreach ($principaux as $principal) {
656
-				$exposer[$m][$type][$principal] = true;
657
-				if ($type == 'id_mot') {
658
-					if (!$parent) {
659
-						$parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot=' . (int) $principal, '', '', '', '', $connect);
660
-					}
661
-					if ($parent) {
662
-						$exposer[$m]['id_groupe'][$parent] = true;
663
-					}
664
-				} else {
665
-					if ($type != 'id_groupe') {
666
-						if (!$parent) {
667
-							if ($type == 'id_rubrique') {
668
-								$parent = $principal;
669
-							}
670
-							if ($type == 'id_article') {
671
-								$parent = quete_rubrique($principal, $connect);
672
-							}
673
-						}
674
-						do {
675
-							$exposer[$m]['id_rubrique'][$parent] = true;
676
-						} while ($parent = quete_parent($parent, $connect));
677
-					}
678
-				}
679
-			}
680
-		}
681
-	}
682
-
683
-	// And the winner is...
684
-	return isset($exposer[$m][$prim]) ? isset($exposer[$m][$prim][$id]) : '';
625
+    static $exposer = [];
626
+
627
+    // Que faut-il exposer ? Tous les elements de $reference
628
+    // ainsi que leur hierarchie ; on ne fait donc ce calcul
629
+    // qu'une fois (par squelette) et on conserve le resultat
630
+    // en static.
631
+    if (!isset($exposer[$m = md5(serialize($reference))][$prim])) {
632
+        $principal = $reference[$type] ?? $reference["@$type"] ?? '';
633
+        // le parent fournit en argument est le parent de $id, pas celui de $principal
634
+        // il n'est donc pas utile
635
+        $parent = 0;
636
+        if (!$principal) { // regarder si un enfant est dans le contexte, auquel cas il expose peut etre le parent courant
637
+            $enfants = ['id_rubrique' => ['id_article'], 'id_groupe' => ['id_mot']];
638
+            if (isset($enfants[$type])) {
639
+                foreach ($enfants[$type] as $t) {
640
+                    if (
641
+                        isset($reference[$t])
642
+                        // cas de la reference donnee dynamiquement par la pagination
643
+                        || isset($reference["@$t"])
644
+                    ) {
645
+                        $type = $t;
646
+                        $principal = $reference[$type] ?? $reference["@$type"];
647
+                        continue;
648
+                    }
649
+                }
650
+            }
651
+        }
652
+        $exposer[$m][$type] = [];
653
+        if ($principal) {
654
+            $principaux = is_array($principal) ? $principal : [$principal];
655
+            foreach ($principaux as $principal) {
656
+                $exposer[$m][$type][$principal] = true;
657
+                if ($type == 'id_mot') {
658
+                    if (!$parent) {
659
+                        $parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot=' . (int) $principal, '', '', '', '', $connect);
660
+                    }
661
+                    if ($parent) {
662
+                        $exposer[$m]['id_groupe'][$parent] = true;
663
+                    }
664
+                } else {
665
+                    if ($type != 'id_groupe') {
666
+                        if (!$parent) {
667
+                            if ($type == 'id_rubrique') {
668
+                                $parent = $principal;
669
+                            }
670
+                            if ($type == 'id_article') {
671
+                                $parent = quete_rubrique($principal, $connect);
672
+                            }
673
+                        }
674
+                        do {
675
+                            $exposer[$m]['id_rubrique'][$parent] = true;
676
+                        } while ($parent = quete_parent($parent, $connect));
677
+                    }
678
+                }
679
+            }
680
+        }
681
+    }
682
+
683
+    // And the winner is...
684
+    return isset($exposer[$m][$prim]) ? isset($exposer[$m][$prim][$id]) : '';
685 685
 }
686 686
 
687 687
 /**
@@ -696,23 +696,23 @@  discard block
 block discarded – undo
696 696
  * @return int
697 697
  */
698 698
 function quete_debut_pagination($primary, $valeur, $pas, $iter) {
699
-	// on ne devrait pas arriver ici si la cle primaire est inexistante
700
-	// ou composee, mais verifions
701
-	if (!$primary || preg_match('/[,\s]/', $primary)) {
702
-		return 0;
703
-	}
704
-
705
-	$pos = 0;
706
-	while (($row = $iter->fetch()) && $row[$primary] != $valeur) {
707
-		$pos++;
708
-	}
709
-	// si on a pas trouve
710
-	if (!$row || $row[$primary] != $valeur) {
711
-		return 0;
712
-	}
713
-
714
-	// sinon, calculer le bon numero de page
715
-	return floor($pos / $pas) * $pas;
699
+    // on ne devrait pas arriver ici si la cle primaire est inexistante
700
+    // ou composee, mais verifions
701
+    if (!$primary || preg_match('/[,\s]/', $primary)) {
702
+        return 0;
703
+    }
704
+
705
+    $pos = 0;
706
+    while (($row = $iter->fetch()) && $row[$primary] != $valeur) {
707
+        $pos++;
708
+    }
709
+    // si on a pas trouve
710
+    if (!$row || $row[$primary] != $valeur) {
711
+        return 0;
712
+    }
713
+
714
+    // sinon, calculer le bon numero de page
715
+    return floor($pos / $pas) * $pas;
716 716
 }
717 717
 
718 718
 /**
@@ -722,8 +722,8 @@  discard block
 block discarded – undo
722 722
  * @return boolean
723 723
  */
724 724
 function is_whereable(mixed $value): bool {
725
-	if (is_array($value) && count($value)) {
726
-		return true;
727
-	}
728
-	return is_scalar($value) && strlen($value);
725
+    if (is_array($value) && count($value)) {
726
+        return true;
727
+    }
728
+    return is_scalar($value) && strlen($value);
729 729
 }
Please login to merge, or discard this patch.
ecrire/base/connect_sql.php 1 patch
Indentation   +319 added lines, -319 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * @package SPIP\Core\SQL
16 16
  **/
17 17
 if (!defined('_ECRIRE_INC_VERSION')) {
18
-	return;
18
+    return;
19 19
 }
20 20
 require_once _ROOT_RESTREINT . 'base/objets.php';
21 21
 
@@ -41,125 +41,125 @@  discard block
 block discarded – undo
41 41
  **/
42 42
 function spip_connect($serveur = '', $version = '') {
43 43
 
44
-	$serveur = is_string($serveur) ? strtolower($serveur) : '';
45
-	$index = $serveur ?: 0;
46
-	if (!$version) {
47
-		$version = $GLOBALS['spip_sql_version'];
48
-	}
49
-	if (isset($GLOBALS['connexions'][$index][$version])) {
50
-		return $GLOBALS['connexions'][$index];
51
-	}
52
-
53
-	include_spip('base/abstract_sql');
54
-	$install = (_request('exec') == 'install');
55
-
56
-	// Premiere connexion ?
57
-	if (!($old = isset($GLOBALS['connexions'][$index]))) {
58
-		$f = '';
59
-		if ($serveur) {
60
-			// serveur externe et nom de serveur bien ecrit ?
61
-			if (
62
-				defined('_DIR_CONNECT')
63
-				&& preg_match('/^[\w\.]*$/', $serveur)
64
-			) {
65
-				$f = _DIR_CONNECT . $serveur . '.php';
66
-				if (!is_readable($f) && !$install) {
67
-					// chercher une declaration de serveur dans le path
68
-					// qui peut servir à des plugins à declarer des connexions à une base sqlite
69
-					// Ex: sert aux boucles POUR et au plugin-dist dump pour se connecter sur le sqlite du dump
70
-					$f = find_in_path("$serveur.php", 'connect/');
71
-				}
72
-			}
73
-		} else {
74
-			if (defined('_FILE_CONNECT') && _FILE_CONNECT) {
75
-				// init du serveur principal
76
-				$f = _FILE_CONNECT;
77
-			} elseif ($install && defined('_FILE_CONNECT_TMP')) {
78
-				// installation en cours
79
-				$f = _FILE_CONNECT_TMP;
80
-			}
81
-		}
82
-
83
-		unset($GLOBALS['db_ok']);
84
-		unset($GLOBALS['spip_connect_version']);
85
-		if ($f && is_readable($f)) {
86
-			include($f);
87
-			if (!isset($GLOBALS['db_ok'])) {
88
-				spip_log("spip_connect: fichier de connexion '$f' OK mais echec connexion au serveur", _LOG_HS);
89
-			}
90
-		}
91
-		else {
92
-			spip_log("spip_connect: fichier de connexion '$f' non trouve, pas de connexion serveur", _LOG_HS);
93
-		}
94
-		if (!isset($GLOBALS['db_ok'])) {
95
-			// fera mieux la prochaine fois
96
-			if ($install) {
97
-				return false;
98
-			}
99
-			// ne plus reessayer si ce n'est pas l'install
100
-			return $GLOBALS['connexions'][$index] = false;
101
-		}
102
-		$GLOBALS['connexions'][$index] = $GLOBALS['db_ok'];
103
-	}
104
-	// si la connexion a deja ete tentee mais a echoue, le dire!
105
-	if (!$GLOBALS['connexions'][$index]) {
106
-		return false;
107
-	}
108
-
109
-	// la connexion a reussi ou etait deja faite.
110
-	// chargement de la version du jeu de fonctions
111
-	// si pas dans le fichier par defaut
112
-	$type = $GLOBALS['db_ok']['type'];
113
-	$jeu = 'spip_' . $type . '_functions_' . $version;
114
-	if (!isset($GLOBALS[$jeu]) && !find_in_path($type . '_' . $version . '.php', 'req/', true)) {
115
-		spip_log("spip_connect: serveur $index version '$version' non defini pour '$type'", _LOG_HS);
116
-		// ne plus reessayer
117
-		return $GLOBALS['connexions'][$index][$version] = [];
118
-	}
119
-	$GLOBALS['connexions'][$index][$version] = $GLOBALS[$jeu];
120
-	if ($old) {
121
-		return $GLOBALS['connexions'][$index];
122
-	}
123
-
124
-	$GLOBALS['connexions'][$index]['spip_connect_version'] = $GLOBALS['spip_connect_version'] ?? 0;
125
-
126
-	// initialisation de l'alphabet utilise dans les connexions SQL
127
-	// si l'installation l'a determine.
128
-	// Celui du serveur principal l'impose aux serveurs secondaires
129
-	// s'ils le connaissent
130
-
131
-	if (!$serveur) {
132
-		$charset = spip_connect_main($GLOBALS[$jeu], $GLOBALS['db_ok']['charset']);
133
-		if (!$charset) {
134
-			unset($GLOBALS['connexions'][$index]);
135
-			spip_log('spip_connect: absence de charset', _LOG_AVERTISSEMENT);
136
-
137
-			return false;
138
-		}
139
-	} else {
140
-		if ($GLOBALS['db_ok']['charset']) {
141
-			$charset = $GLOBALS['db_ok']['charset'];
142
-		}
143
-		// spip_meta n'existe pas toujours dans la base
144
-		// C'est le cas d'un dump sqlite par exemple
145
-		elseif (
146
-			$GLOBALS['connexions'][$index]['spip_connect_version']
147
-			&& sql_showtable('spip_meta', true, $serveur)
148
-			&& ($r = sql_getfetsel('valeur', 'spip_meta', "nom='charset_sql_connexion'", '', '', '', '', $serveur))
149
-		) {
150
-			$charset = $r;
151
-		} else {
152
-			$charset = -1;
153
-		}
154
-	}
155
-	if ($charset != -1) {
156
-		$f = $GLOBALS[$jeu]['set_charset'];
157
-		if (function_exists($f)) {
158
-			$f($charset, $serveur);
159
-		}
160
-	}
161
-
162
-	return $GLOBALS['connexions'][$index];
44
+    $serveur = is_string($serveur) ? strtolower($serveur) : '';
45
+    $index = $serveur ?: 0;
46
+    if (!$version) {
47
+        $version = $GLOBALS['spip_sql_version'];
48
+    }
49
+    if (isset($GLOBALS['connexions'][$index][$version])) {
50
+        return $GLOBALS['connexions'][$index];
51
+    }
52
+
53
+    include_spip('base/abstract_sql');
54
+    $install = (_request('exec') == 'install');
55
+
56
+    // Premiere connexion ?
57
+    if (!($old = isset($GLOBALS['connexions'][$index]))) {
58
+        $f = '';
59
+        if ($serveur) {
60
+            // serveur externe et nom de serveur bien ecrit ?
61
+            if (
62
+                defined('_DIR_CONNECT')
63
+                && preg_match('/^[\w\.]*$/', $serveur)
64
+            ) {
65
+                $f = _DIR_CONNECT . $serveur . '.php';
66
+                if (!is_readable($f) && !$install) {
67
+                    // chercher une declaration de serveur dans le path
68
+                    // qui peut servir à des plugins à declarer des connexions à une base sqlite
69
+                    // Ex: sert aux boucles POUR et au plugin-dist dump pour se connecter sur le sqlite du dump
70
+                    $f = find_in_path("$serveur.php", 'connect/');
71
+                }
72
+            }
73
+        } else {
74
+            if (defined('_FILE_CONNECT') && _FILE_CONNECT) {
75
+                // init du serveur principal
76
+                $f = _FILE_CONNECT;
77
+            } elseif ($install && defined('_FILE_CONNECT_TMP')) {
78
+                // installation en cours
79
+                $f = _FILE_CONNECT_TMP;
80
+            }
81
+        }
82
+
83
+        unset($GLOBALS['db_ok']);
84
+        unset($GLOBALS['spip_connect_version']);
85
+        if ($f && is_readable($f)) {
86
+            include($f);
87
+            if (!isset($GLOBALS['db_ok'])) {
88
+                spip_log("spip_connect: fichier de connexion '$f' OK mais echec connexion au serveur", _LOG_HS);
89
+            }
90
+        }
91
+        else {
92
+            spip_log("spip_connect: fichier de connexion '$f' non trouve, pas de connexion serveur", _LOG_HS);
93
+        }
94
+        if (!isset($GLOBALS['db_ok'])) {
95
+            // fera mieux la prochaine fois
96
+            if ($install) {
97
+                return false;
98
+            }
99
+            // ne plus reessayer si ce n'est pas l'install
100
+            return $GLOBALS['connexions'][$index] = false;
101
+        }
102
+        $GLOBALS['connexions'][$index] = $GLOBALS['db_ok'];
103
+    }
104
+    // si la connexion a deja ete tentee mais a echoue, le dire!
105
+    if (!$GLOBALS['connexions'][$index]) {
106
+        return false;
107
+    }
108
+
109
+    // la connexion a reussi ou etait deja faite.
110
+    // chargement de la version du jeu de fonctions
111
+    // si pas dans le fichier par defaut
112
+    $type = $GLOBALS['db_ok']['type'];
113
+    $jeu = 'spip_' . $type . '_functions_' . $version;
114
+    if (!isset($GLOBALS[$jeu]) && !find_in_path($type . '_' . $version . '.php', 'req/', true)) {
115
+        spip_log("spip_connect: serveur $index version '$version' non defini pour '$type'", _LOG_HS);
116
+        // ne plus reessayer
117
+        return $GLOBALS['connexions'][$index][$version] = [];
118
+    }
119
+    $GLOBALS['connexions'][$index][$version] = $GLOBALS[$jeu];
120
+    if ($old) {
121
+        return $GLOBALS['connexions'][$index];
122
+    }
123
+
124
+    $GLOBALS['connexions'][$index]['spip_connect_version'] = $GLOBALS['spip_connect_version'] ?? 0;
125
+
126
+    // initialisation de l'alphabet utilise dans les connexions SQL
127
+    // si l'installation l'a determine.
128
+    // Celui du serveur principal l'impose aux serveurs secondaires
129
+    // s'ils le connaissent
130
+
131
+    if (!$serveur) {
132
+        $charset = spip_connect_main($GLOBALS[$jeu], $GLOBALS['db_ok']['charset']);
133
+        if (!$charset) {
134
+            unset($GLOBALS['connexions'][$index]);
135
+            spip_log('spip_connect: absence de charset', _LOG_AVERTISSEMENT);
136
+
137
+            return false;
138
+        }
139
+    } else {
140
+        if ($GLOBALS['db_ok']['charset']) {
141
+            $charset = $GLOBALS['db_ok']['charset'];
142
+        }
143
+        // spip_meta n'existe pas toujours dans la base
144
+        // C'est le cas d'un dump sqlite par exemple
145
+        elseif (
146
+            $GLOBALS['connexions'][$index]['spip_connect_version']
147
+            && sql_showtable('spip_meta', true, $serveur)
148
+            && ($r = sql_getfetsel('valeur', 'spip_meta', "nom='charset_sql_connexion'", '', '', '', '', $serveur))
149
+        ) {
150
+            $charset = $r;
151
+        } else {
152
+            $charset = -1;
153
+        }
154
+    }
155
+    if ($charset != -1) {
156
+        $f = $GLOBALS[$jeu]['set_charset'];
157
+        if (function_exists($f)) {
158
+            $f($charset, $serveur);
159
+        }
160
+    }
161
+
162
+    return $GLOBALS['connexions'][$index];
163 163
 }
164 164
 
165 165
 /**
@@ -168,12 +168,12 @@  discard block
 block discarded – undo
168 168
  * @param string $serveur Nom du connecteur de bdd utilisé
169 169
  **/
170 170
 function spip_sql_erreur($serveur = '') {
171
-	$connexion = spip_connect($serveur);
172
-	$e = sql_errno($serveur);
173
-	$t = ($connexion['type'] ?? 'sql');
174
-	$m = "Erreur $e de $t: " . sql_error($serveur) . "\nin " . sql_error_backtrace() . "\n" . trim((string) $connexion['last']);
175
-	$f = $t . $serveur;
176
-	spip_log($m, $f . '.' . _LOG_ERREUR);
171
+    $connexion = spip_connect($serveur);
172
+    $e = sql_errno($serveur);
173
+    $t = ($connexion['type'] ?? 'sql');
174
+    $m = "Erreur $e de $t: " . sql_error($serveur) . "\nin " . sql_error_backtrace() . "\n" . trim((string) $connexion['last']);
175
+    $f = $t . $serveur;
176
+    spip_log($m, $f . '.' . _LOG_ERREUR);
177 177
 }
178 178
 
179 179
 /**
@@ -195,23 +195,23 @@  discard block
 block discarded – undo
195 195
  *     - array : description de la connexion, si l'instruction sql est indisponible pour cette connexion
196 196
  **/
197 197
 function spip_connect_sql($version, $ins = '', $serveur = '', $continue = false) {
198
-	$desc = spip_connect($serveur, $version);
199
-	if (
200
-		$desc
201
-		&& ($f = ($desc[$version][$ins] ?? ''))
202
-		&& function_exists($f)
203
-	) {
204
-		return $f;
205
-	}
206
-	if ($continue) {
207
-		return $desc;
208
-	}
209
-	if ($ins) {
210
-		spip_log("Le serveur '$serveur' version $version n'a pas '$ins'", _LOG_ERREUR);
211
-	}
212
-	include_spip('inc/minipres');
213
-	echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
214
-	exit;
198
+    $desc = spip_connect($serveur, $version);
199
+    if (
200
+        $desc
201
+        && ($f = ($desc[$version][$ins] ?? ''))
202
+        && function_exists($f)
203
+    ) {
204
+        return $f;
205
+    }
206
+    if ($continue) {
207
+        return $desc;
208
+    }
209
+    if ($ins) {
210
+        spip_log("Le serveur '$serveur' version $version n'a pas '$ins'", _LOG_ERREUR);
211
+    }
212
+    include_spip('inc/minipres');
213
+    echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
214
+    exit;
215 215
 }
216 216
 
217 217
 /**
@@ -237,70 +237,70 @@  discard block
 block discarded – undo
237 237
  * @return array|null Description de la connexion
238 238
  */
239 239
 function spip_connect_db(
240
-	$host,
241
-	$port,
242
-	$login,
243
-	#[\SensitiveParameter] $pass,
244
-	$db = '',
245
-	$type = 'mysql',
246
-	$prefixe = '',
247
-	$auth = '',
248
-	$charset = ''
240
+    $host,
241
+    $port,
242
+    $login,
243
+    #[\SensitiveParameter] $pass,
244
+    $db = '',
245
+    $type = 'mysql',
246
+    $prefixe = '',
247
+    $auth = '',
248
+    $charset = ''
249 249
 ) {
250
-	// temps avant nouvelle tentative de connexion
251
-	// suite a une connection echouee
252
-	if (!defined('_CONNECT_RETRY_DELAY')) {
253
-		define('_CONNECT_RETRY_DELAY', 30);
254
-	}
255
-
256
-	$f = '';
257
-	// un fichier de identifiant par combinaison (type,host,port,db)
258
-	// pour ne pas declarer tout indisponible d'un coup
259
-	// si en cours d'installation ou si db=@test@ on ne pose rien
260
-	// car c'est un test de connexion
261
-	if (!defined('_ECRIRE_INSTALL') && $db !== '@test@') {
262
-		$f = _DIR_TMP . $type . '.' . substr(md5($host . $port . $db), 0, 8) . '.out';
263
-	} elseif ($db == '@test@') {
264
-		$db = '';
265
-	}
266
-
267
-	if (
268
-		$f
269
-		&& @file_exists($f)
270
-		&& (time() - @filemtime($f) < _CONNECT_RETRY_DELAY)
271
-	) {
272
-		spip_log("Echec : $f recent. Pas de tentative de connexion", _LOG_HS);
273
-
274
-		return null;
275
-	}
276
-
277
-	if (!$prefixe) {
278
-		$prefixe = $GLOBALS['table_prefix'] ?? $db;
279
-	}
280
-	$h = charger_fonction($type, 'req', true);
281
-	if (!$h) {
282
-		spip_log("les requetes $type ne sont pas fournies", _LOG_HS);
283
-
284
-		return null;
285
-	}
286
-	if ($g = $h($host, $port, $login, $pass, $db, $prefixe)) {
287
-		if (!is_array($auth)) {
288
-			// compatibilite version 0.7 initiale
289
-			$g['ldap'] = $auth;
290
-			$auth = ['ldap' => $auth];
291
-		}
292
-		$g['authentification'] = $auth;
293
-		$g['type'] = $type;
294
-		$g['charset'] = $charset;
295
-
296
-		return $GLOBALS['db_ok'] = $g;
297
-	}
298
-	// En cas d'indisponibilite du serveur, eviter de le bombarder
299
-	if ($f) {
300
-		@touch($f);
301
-		spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type . '.' . _LOG_HS);
302
-	}
303
-	return null;
250
+    // temps avant nouvelle tentative de connexion
251
+    // suite a une connection echouee
252
+    if (!defined('_CONNECT_RETRY_DELAY')) {
253
+        define('_CONNECT_RETRY_DELAY', 30);
254
+    }
255
+
256
+    $f = '';
257
+    // un fichier de identifiant par combinaison (type,host,port,db)
258
+    // pour ne pas declarer tout indisponible d'un coup
259
+    // si en cours d'installation ou si db=@test@ on ne pose rien
260
+    // car c'est un test de connexion
261
+    if (!defined('_ECRIRE_INSTALL') && $db !== '@test@') {
262
+        $f = _DIR_TMP . $type . '.' . substr(md5($host . $port . $db), 0, 8) . '.out';
263
+    } elseif ($db == '@test@') {
264
+        $db = '';
265
+    }
266
+
267
+    if (
268
+        $f
269
+        && @file_exists($f)
270
+        && (time() - @filemtime($f) < _CONNECT_RETRY_DELAY)
271
+    ) {
272
+        spip_log("Echec : $f recent. Pas de tentative de connexion", _LOG_HS);
273
+
274
+        return null;
275
+    }
276
+
277
+    if (!$prefixe) {
278
+        $prefixe = $GLOBALS['table_prefix'] ?? $db;
279
+    }
280
+    $h = charger_fonction($type, 'req', true);
281
+    if (!$h) {
282
+        spip_log("les requetes $type ne sont pas fournies", _LOG_HS);
283
+
284
+        return null;
285
+    }
286
+    if ($g = $h($host, $port, $login, $pass, $db, $prefixe)) {
287
+        if (!is_array($auth)) {
288
+            // compatibilite version 0.7 initiale
289
+            $g['ldap'] = $auth;
290
+            $auth = ['ldap' => $auth];
291
+        }
292
+        $g['authentification'] = $auth;
293
+        $g['type'] = $type;
294
+        $g['charset'] = $charset;
295
+
296
+        return $GLOBALS['db_ok'] = $g;
297
+    }
298
+    // En cas d'indisponibilite du serveur, eviter de le bombarder
299
+    if ($f) {
300
+        @touch($f);
301
+        spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type . '.' . _LOG_HS);
302
+    }
303
+    return null;
304 304
 }
305 305
 
306 306
 
@@ -332,32 +332,32 @@  discard block
 block discarded – undo
332 332
  *     - nom du charset sinon
333 333
  **/
334 334
 function spip_connect_main($connexion, $charset_sql_connexion = '') {
335
-	if ($GLOBALS['spip_connect_version'] < 0.1 && _DIR_RESTREINT) {
336
-		include_spip('inc/headers');
337
-		redirige_url_ecrire('upgrade', 'reinstall=oui');
338
-	}
339
-
340
-	if (!($f = $connexion['select'])) {
341
-		return false;
342
-	}
343
-	// si le charset est fourni, l'utiliser
344
-	if ($charset_sql_connexion) {
345
-		return $charset_sql_connexion;
346
-	}
347
-	// sinon on regarde la table spip_meta
348
-	// en cas d'erreur select retourne la requette (is_string=true donc)
349
-	if (
350
-		!($r = $f('valeur', 'spip_meta', "nom='charset_sql_connexion'"))
351
-		|| is_string($r)
352
-	) {
353
-		return false;
354
-	}
355
-	if (!($f = $connexion['fetch'])) {
356
-		return false;
357
-	}
358
-	$r = $f($r);
359
-
360
-	return (isset($r['valeur']) && $r['valeur']) ? $r['valeur'] : -1;
335
+    if ($GLOBALS['spip_connect_version'] < 0.1 && _DIR_RESTREINT) {
336
+        include_spip('inc/headers');
337
+        redirige_url_ecrire('upgrade', 'reinstall=oui');
338
+    }
339
+
340
+    if (!($f = $connexion['select'])) {
341
+        return false;
342
+    }
343
+    // si le charset est fourni, l'utiliser
344
+    if ($charset_sql_connexion) {
345
+        return $charset_sql_connexion;
346
+    }
347
+    // sinon on regarde la table spip_meta
348
+    // en cas d'erreur select retourne la requette (is_string=true donc)
349
+    if (
350
+        !($r = $f('valeur', 'spip_meta', "nom='charset_sql_connexion'"))
351
+        || is_string($r)
352
+    ) {
353
+        return false;
354
+    }
355
+    if (!($f = $connexion['fetch'])) {
356
+        return false;
357
+    }
358
+    $r = $f($r);
359
+
360
+    return (isset($r['valeur']) && $r['valeur']) ? $r['valeur'] : -1;
361 361
 }
362 362
 
363 363
 /**
@@ -373,16 +373,16 @@  discard block
 block discarded – undo
373 373
  * @return string Valeur échappée.
374 374
  **/
375 375
 function _q($a): string {
376
-	if (is_numeric($a)) {
377
-		return (string) $a;
378
-	} elseif (is_array($a)) {
379
-		return implode(',', array_map('_q', $a));
380
-	} elseif (is_scalar($a)) {
381
-		return ("'" . addslashes($a) . "'");
382
-	} elseif ($a === null) {
383
-		return "''";
384
-	}
385
-	throw new \RuntimeException('Can’t use _q with ' . gettype($a));
376
+    if (is_numeric($a)) {
377
+        return (string) $a;
378
+    } elseif (is_array($a)) {
379
+        return implode(',', array_map('_q', $a));
380
+    } elseif (is_scalar($a)) {
381
+        return ("'" . addslashes($a) . "'");
382
+    } elseif ($a === null) {
383
+        return "''";
384
+    }
385
+    throw new \RuntimeException('Can’t use _q with ' . gettype($a));
386 386
 }
387 387
 
388 388
 /**
@@ -398,75 +398,75 @@  discard block
 block discarded – undo
398 398
  * @return array
399 399
  */
400 400
 function query_echappe_textes($query, $uniqid = null) {
401
-	static $codeEchappements = null;
402
-	if (is_null($codeEchappements) || $uniqid) {
403
-		if (is_null($uniqid)) {
404
-			$uniqid = uniqid();
405
-		}
406
-		$uniqid = substr(md5((string) $uniqid), 0, 4);
407
-		$codeEchappements = ['\\\\' => "\x1@#{$uniqid}#@\x1", "\\'" => "\x2@#{$uniqid}#@\x2", '\\"' => "\x3@#{$uniqid}#@\x3", '%' => "\x4@#{$uniqid}#@\x4"];
408
-	}
409
-	if ($query === null) {
410
-		return $codeEchappements;
411
-	}
412
-
413
-	// si la query contient deja des codes d'echappement on va s'emmeler les pinceaux et donc on ne touche a rien
414
-	// ce n'est pas un cas legitime
415
-	foreach ($codeEchappements as $codeEchappement) {
416
-		if (str_contains($query, (string) $codeEchappement)) {
417
-			return [$query, []];
418
-		}
419
-	}
420
-
421
-	$query_echappees = str_replace(array_keys($codeEchappements), array_values($codeEchappements), $query);
422
-	if (preg_match_all("/('[^']*')|(\"[^\"]*\")/S", $query_echappees, $textes)) {
423
-		$textes = reset($textes);
424
-
425
-		$parts = [];
426
-		$currentpos = 0;
427
-		$k = 0;
428
-		while (count($textes)) {
429
-			$part = array_shift($textes);
430
-			$nextpos = strpos($query_echappees, (string) $part, $currentpos);
431
-			// si besoin recoller ensemble les doubles '' de sqlite (echappement des ')
432
-			while (count($textes) && str_ends_with((string) $part, "'")) {
433
-				$next = reset($textes);
434
-				if (
435
-					str_starts_with((string) $next, "'")
436
-					&& strpos($query_echappees, $part . $next, $currentpos) === $nextpos
437
-				) {
438
-					$part .= array_shift($textes);
439
-				}
440
-				else {
441
-					break;
442
-				}
443
-			}
444
-			$k++;
445
-			$parts[$k] = [
446
-				'texte' => $part,
447
-				'position' => $nextpos,
448
-				'placeholder' => '%' . $k . '$s',
449
-			];
450
-			$currentpos = $nextpos + strlen((string) $part);
451
-		}
452
-
453
-		// et on replace les parts une par une en commencant par la fin
454
-		while ($k > 0) {
455
-			$query_echappees = substr_replace($query_echappees, $parts[$k]['placeholder'], $parts[$k]['position'], strlen((string) $parts[$k]['texte']));
456
-			$k--;
457
-		}
458
-		$textes = array_column($parts, 'texte');
459
-	} else {
460
-		$textes = [];
461
-	}
462
-
463
-	// si il reste des quotes simples ou doubles, c'est qu'on s'est emmelle les pinceaux
464
-	// dans le doute on ne touche a rien
465
-	if (strpbrk($query_echappees, "'\"") !== false) {
466
-		return [$query, []];
467
-	}
468
-
469
-	return [$query_echappees, $textes];
401
+    static $codeEchappements = null;
402
+    if (is_null($codeEchappements) || $uniqid) {
403
+        if (is_null($uniqid)) {
404
+            $uniqid = uniqid();
405
+        }
406
+        $uniqid = substr(md5((string) $uniqid), 0, 4);
407
+        $codeEchappements = ['\\\\' => "\x1@#{$uniqid}#@\x1", "\\'" => "\x2@#{$uniqid}#@\x2", '\\"' => "\x3@#{$uniqid}#@\x3", '%' => "\x4@#{$uniqid}#@\x4"];
408
+    }
409
+    if ($query === null) {
410
+        return $codeEchappements;
411
+    }
412
+
413
+    // si la query contient deja des codes d'echappement on va s'emmeler les pinceaux et donc on ne touche a rien
414
+    // ce n'est pas un cas legitime
415
+    foreach ($codeEchappements as $codeEchappement) {
416
+        if (str_contains($query, (string) $codeEchappement)) {
417
+            return [$query, []];
418
+        }
419
+    }
420
+
421
+    $query_echappees = str_replace(array_keys($codeEchappements), array_values($codeEchappements), $query);
422
+    if (preg_match_all("/('[^']*')|(\"[^\"]*\")/S", $query_echappees, $textes)) {
423
+        $textes = reset($textes);
424
+
425
+        $parts = [];
426
+        $currentpos = 0;
427
+        $k = 0;
428
+        while (count($textes)) {
429
+            $part = array_shift($textes);
430
+            $nextpos = strpos($query_echappees, (string) $part, $currentpos);
431
+            // si besoin recoller ensemble les doubles '' de sqlite (echappement des ')
432
+            while (count($textes) && str_ends_with((string) $part, "'")) {
433
+                $next = reset($textes);
434
+                if (
435
+                    str_starts_with((string) $next, "'")
436
+                    && strpos($query_echappees, $part . $next, $currentpos) === $nextpos
437
+                ) {
438
+                    $part .= array_shift($textes);
439
+                }
440
+                else {
441
+                    break;
442
+                }
443
+            }
444
+            $k++;
445
+            $parts[$k] = [
446
+                'texte' => $part,
447
+                'position' => $nextpos,
448
+                'placeholder' => '%' . $k . '$s',
449
+            ];
450
+            $currentpos = $nextpos + strlen((string) $part);
451
+        }
452
+
453
+        // et on replace les parts une par une en commencant par la fin
454
+        while ($k > 0) {
455
+            $query_echappees = substr_replace($query_echappees, $parts[$k]['placeholder'], $parts[$k]['position'], strlen((string) $parts[$k]['texte']));
456
+            $k--;
457
+        }
458
+        $textes = array_column($parts, 'texte');
459
+    } else {
460
+        $textes = [];
461
+    }
462
+
463
+    // si il reste des quotes simples ou doubles, c'est qu'on s'est emmelle les pinceaux
464
+    // dans le doute on ne touche a rien
465
+    if (strpbrk($query_echappees, "'\"") !== false) {
466
+        return [$query, []];
467
+    }
468
+
469
+    return [$query_echappees, $textes];
470 470
 }
471 471
 
472 472
 /**
@@ -480,14 +480,14 @@  discard block
 block discarded – undo
480 480
  * @return string
481 481
  */
482 482
 function query_reinjecte_textes($query, $textes) {
483
-	// recuperer les codes echappements
484
-	$codeEchappements = query_echappe_textes(null);
483
+    // recuperer les codes echappements
484
+    $codeEchappements = query_echappe_textes(null);
485 485
 
486
-	if (!empty($textes)) {
487
-		$query = sprintf($query, ...$textes);
488
-	}
486
+    if (!empty($textes)) {
487
+        $query = sprintf($query, ...$textes);
488
+    }
489 489
 
490
-	return str_replace(array_values($codeEchappements), array_keys($codeEchappements), $query);
490
+    return str_replace(array_values($codeEchappements), array_keys($codeEchappements), $query);
491 491
 }
492 492
 
493 493
 
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
  **/
507 507
 function spip_query($query, $serveur = '') {
508 508
 
509
-	$f = spip_connect_sql($GLOBALS['spip_sql_version'], 'query', $serveur, true);
509
+    $f = spip_connect_sql($GLOBALS['spip_sql_version'], 'query', $serveur, true);
510 510
 
511
-	return function_exists($f) ? $f($query, $serveur) : false;
511
+    return function_exists($f) ? $f($query, $serveur) : false;
512 512
 }
Please login to merge, or discard this patch.