Completed
Push — master ( 6ed852...137dab )
by cam
01:45
created
ecrire/inc/modifier.php 1 patch
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -39,28 +39,28 @@  discard block
 block discarded – undo
39 39
  *     Tableau des champs et valeurs collectées
40 40
  */
41 41
 function collecter_requests($include_list, $exclude_list = [], $set = null, $tous = false) {
42
-	$c = $set;
43
-	if (!$c) {
44
-		$c = [];
45
-		foreach ($include_list as $champ) {
46
-			// on ne collecte que les champs reellement envoyes par defaut.
47
-			// le cas d'un envoi de valeur NULL peut du coup poser probleme.
48
-			$val = _request($champ);
49
-			if ($tous or $val !== null) {
50
-				$c[$champ] = $val;
51
-			}
52
-		}
53
-		// on ajoute toujours la lang en saisie possible
54
-		// meme si pas prevu au depart pour l'objet concerne
55
-		if ($l = _request('changer_lang')) {
56
-			$c['lang'] = $l;
57
-		}
58
-	}
59
-	foreach ($exclude_list as $champ) {
60
-		unset($c[$champ]);
61
-	}
62
-
63
-	return $c;
42
+    $c = $set;
43
+    if (!$c) {
44
+        $c = [];
45
+        foreach ($include_list as $champ) {
46
+            // on ne collecte que les champs reellement envoyes par defaut.
47
+            // le cas d'un envoi de valeur NULL peut du coup poser probleme.
48
+            $val = _request($champ);
49
+            if ($tous or $val !== null) {
50
+                $c[$champ] = $val;
51
+            }
52
+        }
53
+        // on ajoute toujours la lang en saisie possible
54
+        // meme si pas prevu au depart pour l'objet concerne
55
+        if ($l = _request('changer_lang')) {
56
+            $c['lang'] = $l;
57
+        }
58
+    }
59
+    foreach ($exclude_list as $champ) {
60
+        unset($c[$champ]);
61
+    }
62
+
63
+    return $c;
64 64
 }
65 65
 
66 66
 /**
@@ -97,242 +97,242 @@  discard block
 block discarded – undo
97 97
  *     - chaîne : texte d'un message d'erreur
98 98
  */
99 99
 function objet_modifier_champs($objet, $id_objet, $options, $c = null, $serveur = '') {
100
-	if (!$id_objet = intval($id_objet)) {
101
-		spip_log('Erreur $id_objet non defini', 'warn');
102
-
103
-		return _T('erreur_technique_enregistrement_impossible');
104
-	}
105
-
106
-	include_spip('inc/filtres');
107
-
108
-	$table_objet = table_objet($objet, $serveur);
109
-	$spip_table_objet = table_objet_sql($objet, $serveur);
110
-	$id_table_objet = id_table_objet($objet, $serveur);
111
-	$trouver_table = charger_fonction('trouver_table', 'base');
112
-	$desc = $trouver_table($spip_table_objet, $serveur);
113
-
114
-	// Appels incomplets (sans $c)
115
-	if (!is_array($c)) {
116
-		spip_log('erreur appel objet_modifier_champs(' . $objet . '), manque $c');
117
-
118
-		return _T('erreur_technique_enregistrement_impossible');
119
-	}
120
-
121
-	// Securite : certaines variables ne sont jamais acceptees ici
122
-	// car elles ne relevent pas de autoriser(xxx, modifier) ;
123
-	// il faut passer par instituer_XX()
124
-	// TODO: faut-il passer ces variables interdites
125
-	// dans un fichier de description separe ?
126
-	unset($c['statut']);
127
-	unset($c['id_parent']);
128
-	unset($c['id_rubrique']);
129
-	unset($c['id_secteur']);
130
-
131
-	// Gerer les champs non vides
132
-	if (isset($options['nonvide']) and is_array($options['nonvide'])) {
133
-		foreach ($options['nonvide'] as $champ => $sinon) {
134
-			if (isset($c[$champ]) and $c[$champ] === '') {
135
-				$c[$champ] = $sinon;
136
-			}
137
-		}
138
-	}
139
-
140
-	// N'accepter que les champs qui existent dans la table
141
-	$champs = array_intersect_key($c, $desc['field']);
142
-	// et dont la valeur n'est pas null
143
-	$champs = array_filter($champs, static function ($var) {
144
-		return $var !== null;
145
-	});
146
-	// TODO: ici aussi on peut valider les contenus
147
-	// en fonction du type
148
-
149
-	// Nettoyer les valeurs
150
-	$champs = array_map('corriger_caracteres', $champs);
151
-
152
-	// On récupère l'état avant toute modification
153
-	$row = sql_fetsel('*', $spip_table_objet, $id_table_objet . '=' . $id_objet);
154
-
155
-	// Envoyer aux plugins
156
-	$champs = pipeline(
157
-		'pre_edition',
158
-		[
159
-			'args' => [
160
-				'table' => $spip_table_objet, // compatibilite
161
-				'table_objet' => $table_objet,
162
-				'spip_table_objet' => $spip_table_objet,
163
-				'desc' => $desc,
164
-				'type' => $objet,
165
-				'id_objet' => $id_objet,
166
-				'data' => $options['data'] ?? null,
167
-				'champs' => $options['champs'] ?? [], // [doc] c'est quoi ?
168
-				'champs_anciens' => $row, // état du contenu avant modif
169
-				'serveur' => $serveur,
170
-				'action' => $options['action'] ?? 'modifier'
171
-			],
172
-			'data' => $champs
173
-		]
174
-	);
175
-
176
-	if (!$champs) {
177
-		return false;
178
-	}
179
-
180
-
181
-	// marquer le fait que l'objet est travaille par toto a telle date
182
-	include_spip('inc/config');
183
-	if (lire_config('articles_modif', 'non') !== 'non') {
184
-		include_spip('inc/drapeau_edition');
185
-		signale_edition($id_objet, $GLOBALS['visiteur_session'], $objet);
186
-	}
187
-
188
-	// Verifier si les mises a jour sont pertinentes, datees, en conflit etc
189
-	include_spip('inc/editer');
190
-	if (!isset($options['data']) or is_null($options['data'])) {
191
-		$options['data'] = &$_POST;
192
-	}
193
-	$conflits = controler_md5($champs, $options['data'], $objet, $id_objet, $serveur);
194
-	// cas hypothetique : normalement inc/editer verifie en amont le conflit edition
195
-	// et gere l'interface
196
-	// ici on ne renvoie donc qu'un messsage d'erreur, au cas ou on y arrive quand meme
197
-	if ($conflits) {
198
-		return _T('titre_conflit_edition');
199
-	}
200
-
201
-	if ($champs) {
202
-		// cas particulier de la langue : passer par instituer_langue_objet
203
-		if (isset($champs['lang'])) {
204
-			if ($changer_lang = $champs['lang']) {
205
-				$id_rubrique = 0;
206
-				if (isset($desc['field']['id_rubrique'])) {
207
-					$parent = ($objet == 'rubrique') ? 'id_parent' : 'id_rubrique';
208
-					$id_rubrique = sql_getfetsel($parent, $spip_table_objet, "$id_table_objet=" . intval($id_objet));
209
-				}
210
-				$instituer_langue_objet = charger_fonction('instituer_langue_objet', 'action');
211
-				$champs['lang'] = $instituer_langue_objet($objet, $id_objet, $id_rubrique, $changer_lang, $serveur);
212
-			}
213
-			// on laisse 'lang' dans $champs,
214
-			// ca permet de passer dans le pipeline post_edition et de journaliser
215
-			// et ca ne gene pas qu'on refasse un sql_updateq dessus apres l'avoir
216
-			// deja pris en compte
217
-		}
218
-
219
-		// la modif peut avoir lieu
220
-
221
-		// faut-il ajouter date_modif ?
222
-		if (
223
-			!empty($options['date_modif'])
224
-			and !isset($champs[$options['date_modif']])
225
-		) {
226
-			$champs[$options['date_modif']] = date('Y-m-d H:i:s');
227
-		}
228
-
229
-		// allez on commit la modif
230
-		sql_updateq($spip_table_objet, $champs, "$id_table_objet=" . intval($id_objet), [], $serveur);
231
-
232
-		// on verifie si elle est bien passee
233
-		$moof = sql_fetsel(
234
-			array_keys($champs),
235
-			$spip_table_objet,
236
-			"$id_table_objet=" . intval($id_objet),
237
-			[],
238
-			[],
239
-			'',
240
-			[],
241
-			$serveur
242
-		);
243
-		// si difference entre les champs, reperer les champs mal enregistres
244
-		if ($moof != $champs) {
245
-			$liste = [];
246
-			foreach ($moof as $k => $v) {
247
-				if (
248
-					$v !== $champs[$k]
249
-					// ne pas alerter si le champ est numerique est que les valeurs sont equivalentes
250
-					and (!is_numeric($v) or intval($v) !== intval($champs[$k]))
251
-					// ne pas alerter si le champ est date, qu'on a envoye une valeur vide et qu'on recupere une date nulle
252
-					and (strlen($champs[$k]) or !in_array($v, ['0000-00-00 00:00:00', '0000-00-00']))
253
-				) {
254
-					$liste[] = $k;
255
-					$conflits[$k]['post'] = $champs[$k];
256
-					$conflits[$k]['save'] = $v;
257
-
258
-					// cas specifique MySQL+emoji : si l'un est la
259
-					// conversion utf8_noplanes de l'autre alors c'est OK
260
-					if (defined('_MYSQL_NOPLANES') && _MYSQL_NOPLANES) {
261
-						include_spip('inc/charsets');
262
-						if ($v == utf8_noplanes($champs[$k])) {
263
-							array_pop($liste);
264
-						}
265
-					}
266
-				}
267
-			}
268
-			// si un champ n'a pas ete correctement enregistre, loger et retourner une erreur
269
-			// c'est un cas exceptionnel
270
-			if (count($liste)) {
271
-				spip_log(
272
-					"Erreur enregistrement en base $objet/$id_objet champs :" . var_export($conflits, true),
273
-					'modifier.' . _LOG_CRITIQUE
274
-				);
275
-
276
-				return _T(
277
-					'erreur_technique_enregistrement_champs',
278
-					['champs' => "<i>'" . implode("'</i>,<i>'", $liste) . "'</i>"]
279
-				);
280
-			}
281
-		}
282
-
283
-		// Invalider les caches
284
-		if (isset($options['invalideur']) and $options['invalideur']) {
285
-			include_spip('inc/invalideur');
286
-			if (is_array($options['invalideur'])) {
287
-				array_map('suivre_invalideur', $options['invalideur']);
288
-			} else {
289
-				suivre_invalideur($options['invalideur']);
290
-			}
291
-		}
292
-
293
-		// Notifications, gestion des revisions...
294
-		// en standard, appelle |nouvelle_revision ci-dessous
295
-		pipeline(
296
-			'post_edition',
297
-			[
298
-				'args' => [
299
-					'table' => $spip_table_objet,
300
-					'table_objet' => $table_objet,
301
-					'spip_table_objet' => $spip_table_objet,
302
-					'desc' => $desc,
303
-					'type' => $objet,
304
-					'id_objet' => $id_objet,
305
-					'champs' => $options['champs'] ?? [], // [doc] kesako ?
306
-					'champs_anciens' => $row, // état du contenu avant modif
307
-					'serveur' => $serveur,
308
-					'action' => $options['action'] ?? 'modifier'
309
-				],
310
-				'data' => $champs
311
-			]
312
-		);
313
-	}
314
-
315
-	// journaliser l'affaire
316
-	// message a affiner :-)
317
-	include_spip('inc/filtres_mini');
318
-	$qui = '';
319
-	if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
320
-		$qui .= ' #id_auteur:' . $GLOBALS['visiteur_session']['id_auteur'] . '#';
321
-	}
322
-	if (!empty($GLOBALS['visiteur_session']['nom'])) {
323
-		$qui .= ' #nom:' . $GLOBALS['visiteur_session']['nom'] . '#';
324
-	}
325
-	if ($qui == '') {
326
-		$qui = '#ip:' . $GLOBALS['ip'] . '#';
327
-	}
328
-	journal(_L($qui . ' a édité ' . $objet . ' ' . $id_objet . ' (' . join(
329
-		'+',
330
-		array_diff(array_keys($champs), ['date_modif'])
331
-	) . ')'), [
332
-		'faire' => 'modifier',
333
-		'quoi' => $objet,
334
-		'id' => $id_objet
335
-	]);
336
-
337
-	return '';
100
+    if (!$id_objet = intval($id_objet)) {
101
+        spip_log('Erreur $id_objet non defini', 'warn');
102
+
103
+        return _T('erreur_technique_enregistrement_impossible');
104
+    }
105
+
106
+    include_spip('inc/filtres');
107
+
108
+    $table_objet = table_objet($objet, $serveur);
109
+    $spip_table_objet = table_objet_sql($objet, $serveur);
110
+    $id_table_objet = id_table_objet($objet, $serveur);
111
+    $trouver_table = charger_fonction('trouver_table', 'base');
112
+    $desc = $trouver_table($spip_table_objet, $serveur);
113
+
114
+    // Appels incomplets (sans $c)
115
+    if (!is_array($c)) {
116
+        spip_log('erreur appel objet_modifier_champs(' . $objet . '), manque $c');
117
+
118
+        return _T('erreur_technique_enregistrement_impossible');
119
+    }
120
+
121
+    // Securite : certaines variables ne sont jamais acceptees ici
122
+    // car elles ne relevent pas de autoriser(xxx, modifier) ;
123
+    // il faut passer par instituer_XX()
124
+    // TODO: faut-il passer ces variables interdites
125
+    // dans un fichier de description separe ?
126
+    unset($c['statut']);
127
+    unset($c['id_parent']);
128
+    unset($c['id_rubrique']);
129
+    unset($c['id_secteur']);
130
+
131
+    // Gerer les champs non vides
132
+    if (isset($options['nonvide']) and is_array($options['nonvide'])) {
133
+        foreach ($options['nonvide'] as $champ => $sinon) {
134
+            if (isset($c[$champ]) and $c[$champ] === '') {
135
+                $c[$champ] = $sinon;
136
+            }
137
+        }
138
+    }
139
+
140
+    // N'accepter que les champs qui existent dans la table
141
+    $champs = array_intersect_key($c, $desc['field']);
142
+    // et dont la valeur n'est pas null
143
+    $champs = array_filter($champs, static function ($var) {
144
+        return $var !== null;
145
+    });
146
+    // TODO: ici aussi on peut valider les contenus
147
+    // en fonction du type
148
+
149
+    // Nettoyer les valeurs
150
+    $champs = array_map('corriger_caracteres', $champs);
151
+
152
+    // On récupère l'état avant toute modification
153
+    $row = sql_fetsel('*', $spip_table_objet, $id_table_objet . '=' . $id_objet);
154
+
155
+    // Envoyer aux plugins
156
+    $champs = pipeline(
157
+        'pre_edition',
158
+        [
159
+            'args' => [
160
+                'table' => $spip_table_objet, // compatibilite
161
+                'table_objet' => $table_objet,
162
+                'spip_table_objet' => $spip_table_objet,
163
+                'desc' => $desc,
164
+                'type' => $objet,
165
+                'id_objet' => $id_objet,
166
+                'data' => $options['data'] ?? null,
167
+                'champs' => $options['champs'] ?? [], // [doc] c'est quoi ?
168
+                'champs_anciens' => $row, // état du contenu avant modif
169
+                'serveur' => $serveur,
170
+                'action' => $options['action'] ?? 'modifier'
171
+            ],
172
+            'data' => $champs
173
+        ]
174
+    );
175
+
176
+    if (!$champs) {
177
+        return false;
178
+    }
179
+
180
+
181
+    // marquer le fait que l'objet est travaille par toto a telle date
182
+    include_spip('inc/config');
183
+    if (lire_config('articles_modif', 'non') !== 'non') {
184
+        include_spip('inc/drapeau_edition');
185
+        signale_edition($id_objet, $GLOBALS['visiteur_session'], $objet);
186
+    }
187
+
188
+    // Verifier si les mises a jour sont pertinentes, datees, en conflit etc
189
+    include_spip('inc/editer');
190
+    if (!isset($options['data']) or is_null($options['data'])) {
191
+        $options['data'] = &$_POST;
192
+    }
193
+    $conflits = controler_md5($champs, $options['data'], $objet, $id_objet, $serveur);
194
+    // cas hypothetique : normalement inc/editer verifie en amont le conflit edition
195
+    // et gere l'interface
196
+    // ici on ne renvoie donc qu'un messsage d'erreur, au cas ou on y arrive quand meme
197
+    if ($conflits) {
198
+        return _T('titre_conflit_edition');
199
+    }
200
+
201
+    if ($champs) {
202
+        // cas particulier de la langue : passer par instituer_langue_objet
203
+        if (isset($champs['lang'])) {
204
+            if ($changer_lang = $champs['lang']) {
205
+                $id_rubrique = 0;
206
+                if (isset($desc['field']['id_rubrique'])) {
207
+                    $parent = ($objet == 'rubrique') ? 'id_parent' : 'id_rubrique';
208
+                    $id_rubrique = sql_getfetsel($parent, $spip_table_objet, "$id_table_objet=" . intval($id_objet));
209
+                }
210
+                $instituer_langue_objet = charger_fonction('instituer_langue_objet', 'action');
211
+                $champs['lang'] = $instituer_langue_objet($objet, $id_objet, $id_rubrique, $changer_lang, $serveur);
212
+            }
213
+            // on laisse 'lang' dans $champs,
214
+            // ca permet de passer dans le pipeline post_edition et de journaliser
215
+            // et ca ne gene pas qu'on refasse un sql_updateq dessus apres l'avoir
216
+            // deja pris en compte
217
+        }
218
+
219
+        // la modif peut avoir lieu
220
+
221
+        // faut-il ajouter date_modif ?
222
+        if (
223
+            !empty($options['date_modif'])
224
+            and !isset($champs[$options['date_modif']])
225
+        ) {
226
+            $champs[$options['date_modif']] = date('Y-m-d H:i:s');
227
+        }
228
+
229
+        // allez on commit la modif
230
+        sql_updateq($spip_table_objet, $champs, "$id_table_objet=" . intval($id_objet), [], $serveur);
231
+
232
+        // on verifie si elle est bien passee
233
+        $moof = sql_fetsel(
234
+            array_keys($champs),
235
+            $spip_table_objet,
236
+            "$id_table_objet=" . intval($id_objet),
237
+            [],
238
+            [],
239
+            '',
240
+            [],
241
+            $serveur
242
+        );
243
+        // si difference entre les champs, reperer les champs mal enregistres
244
+        if ($moof != $champs) {
245
+            $liste = [];
246
+            foreach ($moof as $k => $v) {
247
+                if (
248
+                    $v !== $champs[$k]
249
+                    // ne pas alerter si le champ est numerique est que les valeurs sont equivalentes
250
+                    and (!is_numeric($v) or intval($v) !== intval($champs[$k]))
251
+                    // ne pas alerter si le champ est date, qu'on a envoye une valeur vide et qu'on recupere une date nulle
252
+                    and (strlen($champs[$k]) or !in_array($v, ['0000-00-00 00:00:00', '0000-00-00']))
253
+                ) {
254
+                    $liste[] = $k;
255
+                    $conflits[$k]['post'] = $champs[$k];
256
+                    $conflits[$k]['save'] = $v;
257
+
258
+                    // cas specifique MySQL+emoji : si l'un est la
259
+                    // conversion utf8_noplanes de l'autre alors c'est OK
260
+                    if (defined('_MYSQL_NOPLANES') && _MYSQL_NOPLANES) {
261
+                        include_spip('inc/charsets');
262
+                        if ($v == utf8_noplanes($champs[$k])) {
263
+                            array_pop($liste);
264
+                        }
265
+                    }
266
+                }
267
+            }
268
+            // si un champ n'a pas ete correctement enregistre, loger et retourner une erreur
269
+            // c'est un cas exceptionnel
270
+            if (count($liste)) {
271
+                spip_log(
272
+                    "Erreur enregistrement en base $objet/$id_objet champs :" . var_export($conflits, true),
273
+                    'modifier.' . _LOG_CRITIQUE
274
+                );
275
+
276
+                return _T(
277
+                    'erreur_technique_enregistrement_champs',
278
+                    ['champs' => "<i>'" . implode("'</i>,<i>'", $liste) . "'</i>"]
279
+                );
280
+            }
281
+        }
282
+
283
+        // Invalider les caches
284
+        if (isset($options['invalideur']) and $options['invalideur']) {
285
+            include_spip('inc/invalideur');
286
+            if (is_array($options['invalideur'])) {
287
+                array_map('suivre_invalideur', $options['invalideur']);
288
+            } else {
289
+                suivre_invalideur($options['invalideur']);
290
+            }
291
+        }
292
+
293
+        // Notifications, gestion des revisions...
294
+        // en standard, appelle |nouvelle_revision ci-dessous
295
+        pipeline(
296
+            'post_edition',
297
+            [
298
+                'args' => [
299
+                    'table' => $spip_table_objet,
300
+                    'table_objet' => $table_objet,
301
+                    'spip_table_objet' => $spip_table_objet,
302
+                    'desc' => $desc,
303
+                    'type' => $objet,
304
+                    'id_objet' => $id_objet,
305
+                    'champs' => $options['champs'] ?? [], // [doc] kesako ?
306
+                    'champs_anciens' => $row, // état du contenu avant modif
307
+                    'serveur' => $serveur,
308
+                    'action' => $options['action'] ?? 'modifier'
309
+                ],
310
+                'data' => $champs
311
+            ]
312
+        );
313
+    }
314
+
315
+    // journaliser l'affaire
316
+    // message a affiner :-)
317
+    include_spip('inc/filtres_mini');
318
+    $qui = '';
319
+    if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
320
+        $qui .= ' #id_auteur:' . $GLOBALS['visiteur_session']['id_auteur'] . '#';
321
+    }
322
+    if (!empty($GLOBALS['visiteur_session']['nom'])) {
323
+        $qui .= ' #nom:' . $GLOBALS['visiteur_session']['nom'] . '#';
324
+    }
325
+    if ($qui == '') {
326
+        $qui = '#ip:' . $GLOBALS['ip'] . '#';
327
+    }
328
+    journal(_L($qui . ' a édité ' . $objet . ' ' . $id_objet . ' (' . join(
329
+        '+',
330
+        array_diff(array_keys($champs), ['date_modif'])
331
+    ) . ')'), [
332
+        'faire' => 'modifier',
333
+        'quoi' => $objet,
334
+        'id' => $id_objet
335
+    ]);
336
+
337
+    return '';
338 338
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_mini.php 1 patch
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -35,20 +35,20 @@  discard block
 block discarded – undo
35 35
  * @return string URL nettoyée
36 36
  **/
37 37
 function resolve_path($url) {
38
-	[$url, $query] = array_pad(explode('?', $url, 2), 2, null);
39
-	while (
40
-		preg_match(',/\.?/,', $url, $regs)    # supprime // et /./
41
-		or preg_match(',/[^/]*/\.\./,S', $url, $regs)  # supprime /toto/../
42
-		or preg_match(',^/\.\./,S', $url, $regs) # supprime les /../ du haut
43
-	) {
44
-		$url = str_replace($regs[0], '/', $url);
45
-	}
38
+    [$url, $query] = array_pad(explode('?', $url, 2), 2, null);
39
+    while (
40
+        preg_match(',/\.?/,', $url, $regs)    # supprime // et /./
41
+        or preg_match(',/[^/]*/\.\./,S', $url, $regs)  # supprime /toto/../
42
+        or preg_match(',^/\.\./,S', $url, $regs) # supprime les /../ du haut
43
+    ) {
44
+        $url = str_replace($regs[0], '/', $url);
45
+    }
46 46
 
47
-	if ($query) {
48
-		$url .= '?' . $query;
49
-	}
47
+    if ($query) {
48
+        $url .= '?' . $query;
49
+    }
50 50
 
51
-	return '/' . preg_replace(',^/,S', '', $url);
51
+    return '/' . preg_replace(',^/,S', '', $url);
52 52
 }
53 53
 
54 54
 
@@ -69,44 +69,44 @@  discard block
 block discarded – undo
69 69
  **/
70 70
 function suivre_lien($url, $lien) {
71 71
 
72
-	$mot = null;
73
-	$get = null;
74
-	$hash = null;
75
-	if (preg_match(',^(mailto|javascript|data|tel|callto|file|ftp):,iS', $lien)) {
76
-		return $lien;
77
-	}
78
-	if (preg_match(';^((?:[a-z]{3,33}:)?//.*?)(/.*)?$;iS', $lien, $r)) {
79
-		$r = array_pad($r, 3, '');
72
+    $mot = null;
73
+    $get = null;
74
+    $hash = null;
75
+    if (preg_match(',^(mailto|javascript|data|tel|callto|file|ftp):,iS', $lien)) {
76
+        return $lien;
77
+    }
78
+    if (preg_match(';^((?:[a-z]{3,33}:)?//.*?)(/.*)?$;iS', $lien, $r)) {
79
+        $r = array_pad($r, 3, '');
80 80
 
81
-		return $r[1] . resolve_path($r[2]);
82
-	}
81
+        return $r[1] . resolve_path($r[2]);
82
+    }
83 83
 
84
-	# L'url site spip est un lien absolu aussi
85
-	if (isset($GLOBALS['meta']['adresse_site']) and $lien == $GLOBALS['meta']['adresse_site']) {
86
-		return $lien;
87
-	}
84
+    # L'url site spip est un lien absolu aussi
85
+    if (isset($GLOBALS['meta']['adresse_site']) and $lien == $GLOBALS['meta']['adresse_site']) {
86
+        return $lien;
87
+    }
88 88
 
89
-	# lien relatif, il faut verifier l'url de base
90
-	# commencer par virer la chaine de get de l'url de base
91
-	$dir = '/';
92
-	$debut = '';
93
-	if (preg_match(';^((?:[a-z]{3,7}:)?//[^/]+)(/.*?/?)?([^/#?]*)([?][^#]*)?(#.*)?$;S', $url, $regs)) {
94
-		$debut = $regs[1];
95
-		$dir = !strlen($regs[2]) ? '/' : $regs[2];
96
-		$mot = $regs[3];
97
-		$get = $regs[4] ?? '';
98
-		$hash = $regs[5] ?? '';
99
-	}
100
-	switch (substr($lien, 0, 1)) {
101
-		case '/':
102
-			return $debut . resolve_path($lien);
103
-		case '#':
104
-			return $debut . resolve_path($dir . $mot . $get . $lien);
105
-		case '':
106
-			return $debut . resolve_path($dir . $mot . $get . $hash);
107
-		default:
108
-			return $debut . resolve_path($dir . $lien);
109
-	}
89
+    # lien relatif, il faut verifier l'url de base
90
+    # commencer par virer la chaine de get de l'url de base
91
+    $dir = '/';
92
+    $debut = '';
93
+    if (preg_match(';^((?:[a-z]{3,7}:)?//[^/]+)(/.*?/?)?([^/#?]*)([?][^#]*)?(#.*)?$;S', $url, $regs)) {
94
+        $debut = $regs[1];
95
+        $dir = !strlen($regs[2]) ? '/' : $regs[2];
96
+        $mot = $regs[3];
97
+        $get = $regs[4] ?? '';
98
+        $hash = $regs[5] ?? '';
99
+    }
100
+    switch (substr($lien, 0, 1)) {
101
+        case '/':
102
+            return $debut . resolve_path($lien);
103
+        case '#':
104
+            return $debut . resolve_path($dir . $mot . $get . $lien);
105
+        case '':
106
+            return $debut . resolve_path($dir . $mot . $get . $hash);
107
+        default:
108
+            return $debut . resolve_path($dir . $lien);
109
+    }
110 110
 }
111 111
 
112 112
 
@@ -129,15 +129,15 @@  discard block
 block discarded – undo
129 129
  * @return string texte ou URL (en absolus)
130 130
  **/
131 131
 function url_absolue($url, $base = '') {
132
-	$url = trim((string) $url);
133
-	if (strlen($url = trim($url)) == 0) {
134
-		return '';
135
-	}
136
-	if (!$base) {
137
-		$base = url_de_base() . (_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
138
-	}
132
+    $url = trim((string) $url);
133
+    if (strlen($url = trim($url)) == 0) {
134
+        return '';
135
+    }
136
+    if (!$base) {
137
+        $base = url_de_base() . (_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
138
+    }
139 139
 
140
-	return suivre_lien($base, $url);
140
+    return suivre_lien($base, $url);
141 141
 }
142 142
 
143 143
 /**
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
  * @return string
149 149
  */
150 150
 function protocole_implicite($url_absolue) {
151
-	return preg_replace(';^[a-z]{3,7}://;i', '//', $url_absolue);
151
+    return preg_replace(';^[a-z]{3,7}://;i', '//', $url_absolue);
152 152
 }
153 153
 
154 154
 /**
@@ -159,16 +159,16 @@  discard block
 block discarded – undo
159 159
  */
160 160
 function protocole_verifier($url_absolue, $protocoles_autorises = ['http','https']) {
161 161
 
162
-	if (preg_match(';^([a-z]{3,7})://;i', $url_absolue, $m)) {
163
-		$protocole = $m[1];
164
-		if (
165
-			in_array($protocole, $protocoles_autorises)
166
-			or in_array(strtolower($protocole), array_map('strtolower', $protocoles_autorises))
167
-		) {
168
-			return true;
169
-		}
170
-	}
171
-	return false;
162
+    if (preg_match(';^([a-z]{3,7})://;i', $url_absolue, $m)) {
163
+        $protocole = $m[1];
164
+        if (
165
+            in_array($protocole, $protocoles_autorises)
166
+            or in_array(strtolower($protocole), array_map('strtolower', $protocoles_autorises))
167
+        ) {
168
+            return true;
169
+        }
170
+    }
171
+    return false;
172 172
 }
173 173
 
174 174
 /**
@@ -185,27 +185,27 @@  discard block
 block discarded – undo
185 185
  * @return string texte avec des URLs absolues
186 186
  **/
187 187
 function liens_absolus($texte, $base = '') {
188
-	if (preg_match_all(',(<(a|link|image|img|script)\s[^<>]*(href|src)=[^<>]*>),imsS', $texte, $liens, PREG_SET_ORDER)) {
189
-		if (!function_exists('extraire_attribut')) {
190
-			include_spip('inc/filtres');
191
-		}
192
-		foreach ($liens as $lien) {
193
-			foreach (['href', 'src'] as $attr) {
194
-				$href = extraire_attribut($lien[0], $attr) ?? '';
195
-				if (strlen($href) > 0) {
196
-					if (!preg_match(';^((?:[a-z]{3,7}:)?//);iS', $href)) {
197
-						$abs = url_absolue($href, $base);
198
-						if (rtrim($href, '/') !== rtrim($abs, '/') and !preg_match('/^#/', $href)) {
199
-							$texte_lien = inserer_attribut($lien[0], $attr, $abs);
200
-							$texte = str_replace($lien[0], $texte_lien, $texte);
201
-						}
202
-					}
203
-				}
204
-			}
205
-		}
206
-	}
188
+    if (preg_match_all(',(<(a|link|image|img|script)\s[^<>]*(href|src)=[^<>]*>),imsS', $texte, $liens, PREG_SET_ORDER)) {
189
+        if (!function_exists('extraire_attribut')) {
190
+            include_spip('inc/filtres');
191
+        }
192
+        foreach ($liens as $lien) {
193
+            foreach (['href', 'src'] as $attr) {
194
+                $href = extraire_attribut($lien[0], $attr) ?? '';
195
+                if (strlen($href) > 0) {
196
+                    if (!preg_match(';^((?:[a-z]{3,7}:)?//);iS', $href)) {
197
+                        $abs = url_absolue($href, $base);
198
+                        if (rtrim($href, '/') !== rtrim($abs, '/') and !preg_match('/^#/', $href)) {
199
+                            $texte_lien = inserer_attribut($lien[0], $attr, $abs);
200
+                            $texte = str_replace($lien[0], $texte_lien, $texte);
201
+                        }
202
+                    }
203
+                }
204
+            }
205
+        }
206
+    }
207 207
 
208
-	return $texte;
208
+    return $texte;
209 209
 }
210 210
 
211 211
 
@@ -221,11 +221,11 @@  discard block
 block discarded – undo
221 221
  * @return string texte ou URL (en absolus)
222 222
  **/
223 223
 function abs_url($texte, $base = '') {
224
-	if ($GLOBALS['mode_abs_url'] == 'url') {
225
-		return url_absolue($texte, $base);
226
-	} else {
227
-		return liens_absolus($texte, $base);
228
-	}
224
+    if ($GLOBALS['mode_abs_url'] == 'url') {
225
+        return url_absolue($texte, $base);
226
+    } else {
227
+        return liens_absolus($texte, $base);
228
+    }
229 229
 }
230 230
 
231 231
 /**
@@ -238,11 +238,11 @@  discard block
 block discarded – undo
238 238
  * @return string
239 239
  */
240 240
 function spip_htmlspecialchars($string, $flags = null, $encoding = 'UTF-8', $double_encode = true) {
241
-	if (is_null($flags)) {
242
-		$flags = ENT_COMPAT | ENT_HTML401;
243
-	}
241
+    if (is_null($flags)) {
242
+        $flags = ENT_COMPAT | ENT_HTML401;
243
+    }
244 244
 
245
-	return htmlspecialchars($string, $flags, $encoding, $double_encode);
245
+    return htmlspecialchars($string, $flags, $encoding, $double_encode);
246 246
 }
247 247
 
248 248
 /**
@@ -255,9 +255,9 @@  discard block
 block discarded – undo
255 255
  * @return string
256 256
  */
257 257
 function spip_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = true) {
258
-	if (is_null($flags)) {
259
-		$flags = ENT_COMPAT | ENT_HTML401;
260
-	}
258
+    if (is_null($flags)) {
259
+        $flags = ENT_COMPAT | ENT_HTML401;
260
+    }
261 261
 
262
-	return htmlentities($string, $flags, $encoding, $double_encode);
262
+    return htmlentities($string, $flags, $encoding, $double_encode);
263 263
 }
Please login to merge, or discard this patch.
ecrire/inc/plugin.php 1 patch
Indentation   +984 added lines, -984 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /** l'adresse du repertoire de telechargement et de decompactage des plugins */
24 24
 if (!defined('_DIR_PLUGINS_AUTO')) {
25
-	define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS . 'auto/');
25
+    define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS . 'auto/');
26 26
 }
27 27
 
28 28
 #include_spip('inc/texte'); // ????? Appelle public/parametrer trop tot avant la reconstruction du chemin des plugins.
@@ -47,27 +47,27 @@  discard block
 block discarded – undo
47 47
  * @return array
48 48
 **/
49 49
 function liste_plugin_files($dir_plugins = null) {
50
-	static $plugin_files = [];
51
-	if (is_null($dir_plugins)) {
52
-		$dir_plugins = _DIR_PLUGINS;
53
-	}
54
-	if (
55
-		!isset($plugin_files[$dir_plugins])
56
-		or (is_countable($plugin_files[$dir_plugins]) ? count($plugin_files[$dir_plugins]) : 0) == 0
57
-	) {
58
-		$plugin_files[$dir_plugins] = [];
59
-		foreach (fast_find_plugin_dirs($dir_plugins) as $plugin) {
60
-			$plugin_files[$dir_plugins][] = substr($plugin, strlen($dir_plugins));
61
-		}
62
-
63
-		sort($plugin_files[$dir_plugins]);
64
-		// et on lit le XML de tous les plugins pour le mettre en cache
65
-		// et en profiter pour nettoyer ceux qui n'existent plus du cache
66
-		$get_infos = charger_fonction('get_infos', 'plugins');
67
-		$get_infos($plugin_files[$dir_plugins], false, $dir_plugins, true);
68
-	}
69
-
70
-	return $plugin_files[$dir_plugins];
50
+    static $plugin_files = [];
51
+    if (is_null($dir_plugins)) {
52
+        $dir_plugins = _DIR_PLUGINS;
53
+    }
54
+    if (
55
+        !isset($plugin_files[$dir_plugins])
56
+        or (is_countable($plugin_files[$dir_plugins]) ? count($plugin_files[$dir_plugins]) : 0) == 0
57
+    ) {
58
+        $plugin_files[$dir_plugins] = [];
59
+        foreach (fast_find_plugin_dirs($dir_plugins) as $plugin) {
60
+            $plugin_files[$dir_plugins][] = substr($plugin, strlen($dir_plugins));
61
+        }
62
+
63
+        sort($plugin_files[$dir_plugins]);
64
+        // et on lit le XML de tous les plugins pour le mettre en cache
65
+        // et en profiter pour nettoyer ceux qui n'existent plus du cache
66
+        $get_infos = charger_fonction('get_infos', 'plugins');
67
+        $get_infos($plugin_files[$dir_plugins], false, $dir_plugins, true);
68
+    }
69
+
70
+    return $plugin_files[$dir_plugins];
71 71
 }
72 72
 
73 73
 /**
@@ -83,45 +83,45 @@  discard block
 block discarded – undo
83 83
  *     Liste complète des répeertoires
84 84
 **/
85 85
 function fast_find_plugin_dirs($dir, $max_prof = 100) {
86
-	$fichiers = [];
87
-	// revenir au repertoire racine si on a recu dossier/truc
88
-	// pour regarder dossier/truc/ ne pas oublier le / final
89
-	$dir = preg_replace(',/[^/]*$,', '', $dir);
90
-	if ($dir == '') {
91
-		$dir = '.';
92
-	}
93
-
94
-	if (!is_dir($dir)) {
95
-		return $fichiers;
96
-	}
97
-	if (is_plugin_dir($dir, '')) {
98
-		$fichiers[] = $dir;
99
-
100
-		return $fichiers;
101
-	}
102
-	if ($max_prof <= 0) {
103
-		return $fichiers;
104
-	}
105
-
106
-	$subdirs = [];
107
-	if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
108
-		while (($f = readdir($d)) !== false) {
109
-			if (
110
-				$f[0] != '.' # ignorer . .. .svn etc
111
-				and $f != 'CVS'
112
-				and is_dir($f = "$dir/$f")
113
-			) {
114
-				$subdirs[] = $f;
115
-			}
116
-		}
117
-		closedir($d);
118
-	}
119
-
120
-	foreach ($subdirs as $d) {
121
-		$fichiers = array_merge($fichiers, fast_find_plugin_dirs("$d/", $max_prof - 1));
122
-	}
123
-
124
-	return $fichiers;
86
+    $fichiers = [];
87
+    // revenir au repertoire racine si on a recu dossier/truc
88
+    // pour regarder dossier/truc/ ne pas oublier le / final
89
+    $dir = preg_replace(',/[^/]*$,', '', $dir);
90
+    if ($dir == '') {
91
+        $dir = '.';
92
+    }
93
+
94
+    if (!is_dir($dir)) {
95
+        return $fichiers;
96
+    }
97
+    if (is_plugin_dir($dir, '')) {
98
+        $fichiers[] = $dir;
99
+
100
+        return $fichiers;
101
+    }
102
+    if ($max_prof <= 0) {
103
+        return $fichiers;
104
+    }
105
+
106
+    $subdirs = [];
107
+    if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
108
+        while (($f = readdir($d)) !== false) {
109
+            if (
110
+                $f[0] != '.' # ignorer . .. .svn etc
111
+                and $f != 'CVS'
112
+                and is_dir($f = "$dir/$f")
113
+            ) {
114
+                $subdirs[] = $f;
115
+            }
116
+        }
117
+        closedir($d);
118
+    }
119
+
120
+    foreach ($subdirs as $d) {
121
+        $fichiers = array_merge($fichiers, fast_find_plugin_dirs("$d/", $max_prof - 1));
122
+    }
123
+
124
+    return $fichiers;
125 125
 }
126 126
 
127 127
 /**
@@ -142,27 +142,27 @@  discard block
 block discarded – undo
142 142
 **/
143 143
 function is_plugin_dir($dir, $dir_plugins = null) {
144 144
 
145
-	if (is_array($dir)) {
146
-		foreach ($dir as $k => $d) {
147
-			if (!is_plugin_dir($d, $dir_plugins)) {
148
-				unset($dir[$k]);
149
-			}
150
-		}
151
-
152
-		return $dir;
153
-	}
154
-	if (is_null($dir_plugins)) {
155
-		$dir_plugins = _DIR_PLUGINS;
156
-	}
157
-	$search = ["$dir_plugins$dir/paquet.xml"];
158
-
159
-	foreach ($search as $s) {
160
-		if (file_exists($s)) {
161
-			return $dir;
162
-		}
163
-	}
164
-
165
-	return '';
145
+    if (is_array($dir)) {
146
+        foreach ($dir as $k => $d) {
147
+            if (!is_plugin_dir($d, $dir_plugins)) {
148
+                unset($dir[$k]);
149
+            }
150
+        }
151
+
152
+        return $dir;
153
+    }
154
+    if (is_null($dir_plugins)) {
155
+        $dir_plugins = _DIR_PLUGINS;
156
+    }
157
+    $search = ["$dir_plugins$dir/paquet.xml"];
158
+
159
+    foreach ($search as $s) {
160
+        if (file_exists($s)) {
161
+            return $dir;
162
+        }
163
+    }
164
+
165
+    return '';
166 166
 }
167 167
 
168 168
 /** Regexp d'extraction des informations d'un intervalle de compatibilité */
@@ -189,51 +189,51 @@  discard block
 block discarded – undo
189 189
  **/
190 190
 function plugin_version_compatible($intervalle, $version, $avec_quoi = '') {
191 191
 
192
-	if (!strlen($intervalle)) {
193
-		return true;
194
-	}
195
-	if (!preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
196
-		return false;
197
-	}
198
-	// Extraction des bornes et traitement de * pour la borne sup :
199
-	// -- on autorise uniquement les ecritures 3.0.*, 3.*
200
-	$minimum = $regs[1];
201
-	$maximum = $regs[2];
202
-
203
-	//  si une version SPIP de compatibilité a été définie (dans
204
-	//  mes_options.php, sous la forme : define('_DEV_VERSION_SPIP_COMPAT', '3.1.0');
205
-	//  on l'utilise (phase de dev, de test...) mais *que* en cas de comparaison
206
-	//  avec la version de SPIP (ne nuit donc pas aux tests de necessite
207
-	//  entre plugins)
208
-	if (defined('_DEV_VERSION_SPIP_COMPAT') and $avec_quoi == 'spip' and $version !== _DEV_VERSION_SPIP_COMPAT) {
209
-		if (plugin_version_compatible($intervalle, _DEV_VERSION_SPIP_COMPAT, $avec_quoi)) {
210
-			return true;
211
-		}
212
-		// si pas de compatibilite avec _DEV_VERSION_SPIP_COMPAT, on essaye quand meme avec la vrai version
213
-		// cas du plugin qui n'est compatible qu'avec cette nouvelle version
214
-	}
215
-
216
-	$minimum_inc = $intervalle[0] == '[';
217
-	$maximum_inc = substr($intervalle, -1) == ']';
218
-
219
-	if (strlen($minimum)) {
220
-		if ($minimum_inc and spip_version_compare($version, $minimum, '<')) {
221
-			return false;
222
-		}
223
-		if (!$minimum_inc and spip_version_compare($version, $minimum, '<=')) {
224
-			return false;
225
-		}
226
-	}
227
-	if (strlen($maximum)) {
228
-		if ($maximum_inc and spip_version_compare($version, $maximum, '>')) {
229
-			return false;
230
-		}
231
-		if (!$maximum_inc and spip_version_compare($version, $maximum, '>=')) {
232
-			return false;
233
-		}
234
-	}
235
-
236
-	return true;
192
+    if (!strlen($intervalle)) {
193
+        return true;
194
+    }
195
+    if (!preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
196
+        return false;
197
+    }
198
+    // Extraction des bornes et traitement de * pour la borne sup :
199
+    // -- on autorise uniquement les ecritures 3.0.*, 3.*
200
+    $minimum = $regs[1];
201
+    $maximum = $regs[2];
202
+
203
+    //  si une version SPIP de compatibilité a été définie (dans
204
+    //  mes_options.php, sous la forme : define('_DEV_VERSION_SPIP_COMPAT', '3.1.0');
205
+    //  on l'utilise (phase de dev, de test...) mais *que* en cas de comparaison
206
+    //  avec la version de SPIP (ne nuit donc pas aux tests de necessite
207
+    //  entre plugins)
208
+    if (defined('_DEV_VERSION_SPIP_COMPAT') and $avec_quoi == 'spip' and $version !== _DEV_VERSION_SPIP_COMPAT) {
209
+        if (plugin_version_compatible($intervalle, _DEV_VERSION_SPIP_COMPAT, $avec_quoi)) {
210
+            return true;
211
+        }
212
+        // si pas de compatibilite avec _DEV_VERSION_SPIP_COMPAT, on essaye quand meme avec la vrai version
213
+        // cas du plugin qui n'est compatible qu'avec cette nouvelle version
214
+    }
215
+
216
+    $minimum_inc = $intervalle[0] == '[';
217
+    $maximum_inc = substr($intervalle, -1) == ']';
218
+
219
+    if (strlen($minimum)) {
220
+        if ($minimum_inc and spip_version_compare($version, $minimum, '<')) {
221
+            return false;
222
+        }
223
+        if (!$minimum_inc and spip_version_compare($version, $minimum, '<=')) {
224
+            return false;
225
+        }
226
+    }
227
+    if (strlen($maximum)) {
228
+        if ($maximum_inc and spip_version_compare($version, $maximum, '>')) {
229
+            return false;
230
+        }
231
+        if (!$maximum_inc and spip_version_compare($version, $maximum, '>=')) {
232
+            return false;
233
+        }
234
+    }
235
+
236
+    return true;
237 237
 }
238 238
 
239 239
 /**
@@ -250,62 +250,62 @@  discard block
 block discarded – undo
250 250
  * @return array
251 251
  */
252 252
 function liste_plugin_valides($liste_plug, $force = false) {
253
-	$liste_ext = liste_plugin_files(_DIR_PLUGINS_DIST);
254
-	$get_infos = charger_fonction('get_infos', 'plugins');
255
-	$infos = [
256
-		// lister les extensions qui sont automatiquement actives
257
-		'_DIR_PLUGINS_DIST' => $get_infos($liste_ext, $force, _DIR_PLUGINS_DIST),
258
-		'_DIR_PLUGINS' => $get_infos($liste_plug, $force, _DIR_PLUGINS)
259
-	];
260
-
261
-	// creer une premiere liste non ordonnee mais qui ne retient
262
-	// que les plugins valides, et dans leur derniere version en cas de doublon
263
-	$infos['_DIR_RESTREINT'][''] = $get_infos('./', $force, _DIR_RESTREINT);
264
-	$infos['_DIR_RESTREINT']['SPIP']['version'] = $GLOBALS['spip_version_branche'];
265
-	$infos['_DIR_RESTREINT']['SPIP']['chemin'] = [];
266
-	$liste_non_classee = [
267
-		'SPIP' => [
268
-			'nom' => 'SPIP',
269
-			'etat' => 'stable',
270
-			'version' => $GLOBALS['spip_version_branche'],
271
-			'dir_type' => '_DIR_RESTREINT',
272
-			'dir' => '',
273
-		]
274
-	];
275
-
276
-	$invalides = [];
277
-	foreach ($liste_ext as $plug) {
278
-		if (isset($infos['_DIR_PLUGINS_DIST'][$plug])) {
279
-			plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_DIST');
280
-		}
281
-	}
282
-	foreach ($liste_plug as $plug) {
283
-		if (isset($infos['_DIR_PLUGINS'][$plug])) {
284
-			$r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS');
285
-			if (is_array($r)) {
286
-				$invalides = array_merge($invalides, $r);
287
-			}
288
-		}
289
-	}
290
-
291
-	if (defined('_DIR_PLUGINS_SUPPL') and _DIR_PLUGINS_SUPPL) {
292
-		$infos['_DIR_PLUGINS_SUPPL'] = $get_infos($liste_plug, false, _DIR_PLUGINS_SUPPL);
293
-		foreach ($liste_plug as $plug) {
294
-			if (isset($infos['_DIR_PLUGINS_SUPPL'][$plug])) {
295
-				$r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_SUPPL');
296
-				if (is_array($r)) {
297
-					$invalides = array_merge($invalides, $r);
298
-				}
299
-			}
300
-		}
301
-	}
302
-
303
-	plugin_fixer_procure($liste_non_classee, $infos);
304
-
305
-	// les plugins qui sont dans $liste_non_classee ne sont pas invalides (on a trouve un autre version valide)
306
-	$invalides = array_diff_key($invalides, $liste_non_classee);
307
-
308
-	return [$infos, $liste_non_classee, $invalides];
253
+    $liste_ext = liste_plugin_files(_DIR_PLUGINS_DIST);
254
+    $get_infos = charger_fonction('get_infos', 'plugins');
255
+    $infos = [
256
+        // lister les extensions qui sont automatiquement actives
257
+        '_DIR_PLUGINS_DIST' => $get_infos($liste_ext, $force, _DIR_PLUGINS_DIST),
258
+        '_DIR_PLUGINS' => $get_infos($liste_plug, $force, _DIR_PLUGINS)
259
+    ];
260
+
261
+    // creer une premiere liste non ordonnee mais qui ne retient
262
+    // que les plugins valides, et dans leur derniere version en cas de doublon
263
+    $infos['_DIR_RESTREINT'][''] = $get_infos('./', $force, _DIR_RESTREINT);
264
+    $infos['_DIR_RESTREINT']['SPIP']['version'] = $GLOBALS['spip_version_branche'];
265
+    $infos['_DIR_RESTREINT']['SPIP']['chemin'] = [];
266
+    $liste_non_classee = [
267
+        'SPIP' => [
268
+            'nom' => 'SPIP',
269
+            'etat' => 'stable',
270
+            'version' => $GLOBALS['spip_version_branche'],
271
+            'dir_type' => '_DIR_RESTREINT',
272
+            'dir' => '',
273
+        ]
274
+    ];
275
+
276
+    $invalides = [];
277
+    foreach ($liste_ext as $plug) {
278
+        if (isset($infos['_DIR_PLUGINS_DIST'][$plug])) {
279
+            plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_DIST');
280
+        }
281
+    }
282
+    foreach ($liste_plug as $plug) {
283
+        if (isset($infos['_DIR_PLUGINS'][$plug])) {
284
+            $r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS');
285
+            if (is_array($r)) {
286
+                $invalides = array_merge($invalides, $r);
287
+            }
288
+        }
289
+    }
290
+
291
+    if (defined('_DIR_PLUGINS_SUPPL') and _DIR_PLUGINS_SUPPL) {
292
+        $infos['_DIR_PLUGINS_SUPPL'] = $get_infos($liste_plug, false, _DIR_PLUGINS_SUPPL);
293
+        foreach ($liste_plug as $plug) {
294
+            if (isset($infos['_DIR_PLUGINS_SUPPL'][$plug])) {
295
+                $r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_SUPPL');
296
+                if (is_array($r)) {
297
+                    $invalides = array_merge($invalides, $r);
298
+                }
299
+            }
300
+        }
301
+    }
302
+
303
+    plugin_fixer_procure($liste_non_classee, $infos);
304
+
305
+    // les plugins qui sont dans $liste_non_classee ne sont pas invalides (on a trouve un autre version valide)
306
+    $invalides = array_diff_key($invalides, $liste_non_classee);
307
+
308
+    return [$infos, $liste_non_classee, $invalides];
309 309
 }
310 310
 
311 311
 /**
@@ -325,38 +325,38 @@  discard block
 block discarded – undo
325 325
  *   array description short si on ne le retient pas (pour memorisation dans une table des erreurs)
326 326
  */
327 327
 function plugin_valide_resume(&$liste, $plug, $infos, $dir_type) {
328
-	$i = $infos[$dir_type][$plug];
329
-	// minimum syndical pour afficher si le xml avait des erreurs éventuelles
330
-	$short_desc = [
331
-		'dir' => $plug,
332
-		'dir_type' => $dir_type
333
-	];
334
-	if (empty($i['prefix'])) {
335
-		// erreur xml ? mais sans connaissance du prefix, on retourne le chemin…
336
-		$short_desc['erreur'] = $i['erreur'] ?? ['?'];
337
-		return [$plug => $short_desc];
338
-	}
339
-
340
-	$p = strtoupper($i['prefix']);
341
-	$short_desc['nom'] = $i['nom'];
342
-	$short_desc['etat'] = $i['etat'];
343
-	$short_desc['version'] = $i['version'];
344
-
345
-	if (isset($i['erreur']) and $i['erreur']) {
346
-		$short_desc['erreur'] = $i['erreur'];
347
-		return [$p => $short_desc];
348
-	}
349
-	if (!plugin_version_compatible($i['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
350
-		return [$p => $short_desc];
351
-	}
352
-	if (
353
-		!isset($liste[$p])
354
-		or spip_version_compare($i['version'], $liste[$p]['version'], '>')
355
-	) {
356
-		$liste[$p] = $short_desc;
357
-	}
358
-	// ok le plugin etait deja dans la liste ou on a choisi une version plus recente
359
-	return $p;
328
+    $i = $infos[$dir_type][$plug];
329
+    // minimum syndical pour afficher si le xml avait des erreurs éventuelles
330
+    $short_desc = [
331
+        'dir' => $plug,
332
+        'dir_type' => $dir_type
333
+    ];
334
+    if (empty($i['prefix'])) {
335
+        // erreur xml ? mais sans connaissance du prefix, on retourne le chemin…
336
+        $short_desc['erreur'] = $i['erreur'] ?? ['?'];
337
+        return [$plug => $short_desc];
338
+    }
339
+
340
+    $p = strtoupper($i['prefix']);
341
+    $short_desc['nom'] = $i['nom'];
342
+    $short_desc['etat'] = $i['etat'];
343
+    $short_desc['version'] = $i['version'];
344
+
345
+    if (isset($i['erreur']) and $i['erreur']) {
346
+        $short_desc['erreur'] = $i['erreur'];
347
+        return [$p => $short_desc];
348
+    }
349
+    if (!plugin_version_compatible($i['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
350
+        return [$p => $short_desc];
351
+    }
352
+    if (
353
+        !isset($liste[$p])
354
+        or spip_version_compare($i['version'], $liste[$p]['version'], '>')
355
+    ) {
356
+        $liste[$p] = $short_desc;
357
+    }
358
+    // ok le plugin etait deja dans la liste ou on a choisi une version plus recente
359
+    return $p;
360 360
 }
361 361
 
362 362
 /**
@@ -372,47 +372,47 @@  discard block
 block discarded – undo
372 372
  * @param array $infos
373 373
  */
374 374
 function plugin_fixer_procure(&$liste, &$infos) {
375
-	foreach ($liste as $p => $resume) {
376
-		$i = $infos[$resume['dir_type']][$resume['dir']];
377
-		if (isset($i['procure']) and $i['procure']) {
378
-			foreach ($i['procure'] as $procure) {
379
-				$p = strtoupper($procure['nom']);
380
-				$dir = $resume['dir'];
381
-				if ($dir) {
382
-					$dir .= '/';
383
-				}
384
-				$dir .= 'procure:' . $procure['nom'];
385
-
386
-				$procure['etat'] = '?';
387
-				$procure['dir_type'] = $resume['dir_type'];
388
-				$procure['dir'] = $dir;
389
-
390
-				// si ce plugin n'est pas deja procure, ou dans une version plus ancienne
391
-				// on ajoute cette version a la liste
392
-				if (
393
-					!isset($liste[$p])
394
-					or spip_version_compare($procure['version'], $liste[$p]['version'], '>')
395
-				) {
396
-					$liste[$p] = $procure;
397
-
398
-					// on fournit une information minimale pour ne pas perturber la compilation
399
-					$infos[$resume['dir_type']][$dir] = [
400
-						'prefix' => $procure['nom'],
401
-						'nom' => $procure['nom'],
402
-						'etat' => $procure['etat'],
403
-						'version' => $procure['version'],
404
-						'chemin' => [],
405
-						'necessite' => [],
406
-						'utilise' => [],
407
-						'lib' => [],
408
-						'menu' => [],
409
-						'onglet' => [],
410
-						'procure' => [],
411
-					];
412
-				}
413
-			}
414
-		}
415
-	}
375
+    foreach ($liste as $p => $resume) {
376
+        $i = $infos[$resume['dir_type']][$resume['dir']];
377
+        if (isset($i['procure']) and $i['procure']) {
378
+            foreach ($i['procure'] as $procure) {
379
+                $p = strtoupper($procure['nom']);
380
+                $dir = $resume['dir'];
381
+                if ($dir) {
382
+                    $dir .= '/';
383
+                }
384
+                $dir .= 'procure:' . $procure['nom'];
385
+
386
+                $procure['etat'] = '?';
387
+                $procure['dir_type'] = $resume['dir_type'];
388
+                $procure['dir'] = $dir;
389
+
390
+                // si ce plugin n'est pas deja procure, ou dans une version plus ancienne
391
+                // on ajoute cette version a la liste
392
+                if (
393
+                    !isset($liste[$p])
394
+                    or spip_version_compare($procure['version'], $liste[$p]['version'], '>')
395
+                ) {
396
+                    $liste[$p] = $procure;
397
+
398
+                    // on fournit une information minimale pour ne pas perturber la compilation
399
+                    $infos[$resume['dir_type']][$dir] = [
400
+                        'prefix' => $procure['nom'],
401
+                        'nom' => $procure['nom'],
402
+                        'etat' => $procure['etat'],
403
+                        'version' => $procure['version'],
404
+                        'chemin' => [],
405
+                        'necessite' => [],
406
+                        'utilise' => [],
407
+                        'lib' => [],
408
+                        'menu' => [],
409
+                        'onglet' => [],
410
+                        'procure' => [],
411
+                    ];
412
+                }
413
+            }
414
+        }
415
+    }
416 416
 }
417 417
 
418 418
 /**
@@ -426,20 +426,20 @@  discard block
 block discarded – undo
426 426
  * @return array
427 427
  */
428 428
 function liste_chemin_plugin($liste, $dir_plugins = _DIR_PLUGINS) {
429
-	foreach ($liste as $prefix => $infos) {
430
-		if (
431
-			!$dir_plugins
432
-			or (
433
-				defined($infos['dir_type'])
434
-				and constant($infos['dir_type']) == $dir_plugins)
435
-		) {
436
-			$liste[$prefix] = $infos['dir'];
437
-		} else {
438
-			unset($liste[$prefix]);
439
-		}
440
-	}
441
-
442
-	return $liste;
429
+    foreach ($liste as $prefix => $infos) {
430
+        if (
431
+            !$dir_plugins
432
+            or (
433
+                defined($infos['dir_type'])
434
+                and constant($infos['dir_type']) == $dir_plugins)
435
+        ) {
436
+            $liste[$prefix] = $infos['dir'];
437
+        } else {
438
+            unset($liste[$prefix]);
439
+        }
440
+    }
441
+
442
+    return $liste;
443 443
 }
444 444
 
445 445
 /**
@@ -454,9 +454,9 @@  discard block
 block discarded – undo
454 454
  * @return array
455 455
  */
456 456
 function liste_chemin_plugin_actifs($dir_plugins = _DIR_PLUGINS) {
457
-	include_spip('plugins/installer');
457
+    include_spip('plugins/installer');
458 458
 
459
-	return liste_chemin_plugin(liste_plugin_actifs(), $dir_plugins);
459
+    return liste_chemin_plugin(liste_plugin_actifs(), $dir_plugins);
460 460
 }
461 461
 
462 462
 /**
@@ -487,54 +487,54 @@  discard block
 block discarded – undo
487 487
  *                qui n'ont pas satisfait leurs dépendances
488 488
 **/
489 489
 function plugin_trier($infos, $liste_non_classee) {
490
-	$toute_la_liste = $liste_non_classee;
491
-	$liste = $ordre = [];
492
-	$count = 0;
493
-
494
-	while ($c = count($liste_non_classee) and $c != $count) { // tant qu'il reste des plugins a classer, et qu'on ne stagne pas
495
-		#echo "tour::";var_dump($liste_non_classee);
496
-		$count = $c;
497
-		foreach ($liste_non_classee as $p => $resume) {
498
-			$plug = $resume['dir'];
499
-			$dir_type = $resume['dir_type'];
500
-			$info1 = $infos[$dir_type][$plug];
501
-			// si des plugins sont necessaires,
502
-			// on ne peut inserer qu'apres eux
503
-			foreach ($info1['necessite'] as $need) {
504
-				$nom = strtoupper($need['nom']);
505
-				$compat = $need['compatibilite'] ?? '';
506
-				if (!isset($liste[$nom]) or !plugin_version_compatible($compat, $liste[$nom]['version'])) {
507
-					$info1 = false;
508
-					break;
509
-				}
510
-			}
511
-			if (!$info1) {
512
-				continue;
513
-			}
514
-			// idem si des plugins sont utiles,
515
-			// sauf si ils sont de toute facon absents de la liste
516
-			foreach ($info1['utilise'] as $need) {
517
-				$nom = strtoupper($need['nom']);
518
-				$compat = $need['compatibilite'] ?? '';
519
-				if (isset($toute_la_liste[$nom])) {
520
-					if (
521
-						!isset($liste[$nom]) or
522
-						!plugin_version_compatible($compat, $liste[$nom]['version'])
523
-					) {
524
-						$info1 = false;
525
-						break;
526
-					}
527
-				}
528
-			}
529
-			if ($info1) {
530
-				$ordre[$p] = $info1;
531
-				$liste[$p] = $liste_non_classee[$p];
532
-				unset($liste_non_classee[$p]);
533
-			}
534
-		}
535
-	}
536
-
537
-	return [$liste, $ordre, $liste_non_classee];
490
+    $toute_la_liste = $liste_non_classee;
491
+    $liste = $ordre = [];
492
+    $count = 0;
493
+
494
+    while ($c = count($liste_non_classee) and $c != $count) { // tant qu'il reste des plugins a classer, et qu'on ne stagne pas
495
+        #echo "tour::";var_dump($liste_non_classee);
496
+        $count = $c;
497
+        foreach ($liste_non_classee as $p => $resume) {
498
+            $plug = $resume['dir'];
499
+            $dir_type = $resume['dir_type'];
500
+            $info1 = $infos[$dir_type][$plug];
501
+            // si des plugins sont necessaires,
502
+            // on ne peut inserer qu'apres eux
503
+            foreach ($info1['necessite'] as $need) {
504
+                $nom = strtoupper($need['nom']);
505
+                $compat = $need['compatibilite'] ?? '';
506
+                if (!isset($liste[$nom]) or !plugin_version_compatible($compat, $liste[$nom]['version'])) {
507
+                    $info1 = false;
508
+                    break;
509
+                }
510
+            }
511
+            if (!$info1) {
512
+                continue;
513
+            }
514
+            // idem si des plugins sont utiles,
515
+            // sauf si ils sont de toute facon absents de la liste
516
+            foreach ($info1['utilise'] as $need) {
517
+                $nom = strtoupper($need['nom']);
518
+                $compat = $need['compatibilite'] ?? '';
519
+                if (isset($toute_la_liste[$nom])) {
520
+                    if (
521
+                        !isset($liste[$nom]) or
522
+                        !plugin_version_compatible($compat, $liste[$nom]['version'])
523
+                    ) {
524
+                        $info1 = false;
525
+                        break;
526
+                    }
527
+                }
528
+            }
529
+            if ($info1) {
530
+                $ordre[$p] = $info1;
531
+                $liste[$p] = $liste_non_classee[$p];
532
+                unset($liste_non_classee[$p]);
533
+            }
534
+        }
535
+    }
536
+
537
+    return [$liste, $ordre, $liste_non_classee];
538 538
 }
539 539
 
540 540
 /**
@@ -551,40 +551,40 @@  discard block
 block discarded – undo
551 551
  *     Répertoire (plugins, plugins-dist, ...) => Couples (prefixes => infos completes) des plugins qu'ils contiennent
552 552
 **/
553 553
 function plugins_erreurs($liste_non_classee, $liste, $infos, $msg = []) {
554
-	static $erreurs = [];
555
-
556
-	if (!is_array($liste)) {
557
-		$liste = [];
558
-	}
559
-
560
-	// les plugins en erreur ne sont pas actifs ; ils ne doivent pas être dans la liste
561
-	$liste = array_diff_key($liste, $liste_non_classee);
562
-
563
-	foreach ($liste_non_classee as $p => $resume) {
564
-		$dir_type = $resume['dir_type'];
565
-		$plug = $resume['dir'];
566
-		$k = $infos[$dir_type][$plug];
567
-
568
-		$plug = constant($dir_type) . $plug;
569
-		if (!isset($msg[$p])) {
570
-			if (isset($resume['erreur']) and $resume['erreur']) {
571
-				$msg[$p] = [$resume['erreur']];
572
-			}
573
-			elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
574
-				$msg[$p] = [plugin_message_incompatibilite($k['compatibilite'], $GLOBALS['spip_version_branche'], 'SPIP', 'necessite')];
575
-			}
576
-			elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
577
-				$msg[$p] = plugin_necessite($k['utilise'], $liste, 'utilise');
578
-			}
579
-		} else {
580
-			foreach ($msg[$p] as $c => $l) {
581
-				$msg[$p][$c] = plugin_controler_lib($l['nom'], $l['lien']);
582
-			}
583
-		}
584
-		$erreurs[$plug] = $msg[$p];
585
-	}
586
-
587
-	ecrire_meta('plugin_erreur_activation', serialize($erreurs));
554
+    static $erreurs = [];
555
+
556
+    if (!is_array($liste)) {
557
+        $liste = [];
558
+    }
559
+
560
+    // les plugins en erreur ne sont pas actifs ; ils ne doivent pas être dans la liste
561
+    $liste = array_diff_key($liste, $liste_non_classee);
562
+
563
+    foreach ($liste_non_classee as $p => $resume) {
564
+        $dir_type = $resume['dir_type'];
565
+        $plug = $resume['dir'];
566
+        $k = $infos[$dir_type][$plug];
567
+
568
+        $plug = constant($dir_type) . $plug;
569
+        if (!isset($msg[$p])) {
570
+            if (isset($resume['erreur']) and $resume['erreur']) {
571
+                $msg[$p] = [$resume['erreur']];
572
+            }
573
+            elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
574
+                $msg[$p] = [plugin_message_incompatibilite($k['compatibilite'], $GLOBALS['spip_version_branche'], 'SPIP', 'necessite')];
575
+            }
576
+            elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
577
+                $msg[$p] = plugin_necessite($k['utilise'], $liste, 'utilise');
578
+            }
579
+        } else {
580
+            foreach ($msg[$p] as $c => $l) {
581
+                $msg[$p][$c] = plugin_controler_lib($l['nom'], $l['lien']);
582
+            }
583
+        }
584
+        $erreurs[$plug] = $msg[$p];
585
+    }
586
+
587
+    ecrire_meta('plugin_erreur_activation', serialize($erreurs));
588 588
 }
589 589
 
590 590
 /**
@@ -599,25 +599,25 @@  discard block
 block discarded – undo
599 599
  *     - Liste des erreurs ou code HTML des erreurs
600 600
 **/
601 601
 function plugin_donne_erreurs($raw = false, $raz = true) {
602
-	if (!isset($GLOBALS['meta']['plugin_erreur_activation'])) {
603
-		return $raw ? [] : '';
604
-	}
605
-	$list = @unserialize($GLOBALS['meta']['plugin_erreur_activation']);
606
-	// Compat ancienne version
607
-	if (!$list) {
608
-		$list = $raw ? [] : $GLOBALS['meta']['plugin_erreur_activation'];
609
-	} elseif (!$raw) {
610
-		foreach ($list as $plug => $msg) {
611
-			$list[$plug] = '<li>' . _T('plugin_impossible_activer', ['plugin' => $plug])
612
-				. '<ul><li>' . implode('</li><li>', $msg) . '</li></ul></li>';
613
-		}
614
-		$list = '<ul>' . join("\n", $list) . '</ul>';
615
-	}
616
-	if ($raz) {
617
-		effacer_meta('plugin_erreur_activation');
618
-	}
619
-
620
-	return $list;
602
+    if (!isset($GLOBALS['meta']['plugin_erreur_activation'])) {
603
+        return $raw ? [] : '';
604
+    }
605
+    $list = @unserialize($GLOBALS['meta']['plugin_erreur_activation']);
606
+    // Compat ancienne version
607
+    if (!$list) {
608
+        $list = $raw ? [] : $GLOBALS['meta']['plugin_erreur_activation'];
609
+    } elseif (!$raw) {
610
+        foreach ($list as $plug => $msg) {
611
+            $list[$plug] = '<li>' . _T('plugin_impossible_activer', ['plugin' => $plug])
612
+                . '<ul><li>' . implode('</li><li>', $msg) . '</li></ul></li>';
613
+        }
614
+        $list = '<ul>' . join("\n", $list) . '</ul>';
615
+    }
616
+    if ($raz) {
617
+        effacer_meta('plugin_erreur_activation');
618
+    }
619
+
620
+    return $list;
621 621
 }
622 622
 
623 623
 /**
@@ -637,21 +637,21 @@  discard block
 block discarded – undo
637 637
  *
638 638
  **/
639 639
 function plugin_necessite($n, $liste, $balise = 'necessite') {
640
-	$msg = [];
641
-	foreach ($n as $need) {
642
-		$id = strtoupper($need['nom']);
643
-		$r = plugin_controler_necessite(
644
-			$liste,
645
-			$id,
646
-			$need['compatibilite'] ?? '',
647
-			$balise
648
-		);
649
-		if ($r) {
650
-			$msg[] = $r;
651
-		}
652
-	}
653
-
654
-	return $msg;
640
+    $msg = [];
641
+    foreach ($n as $need) {
642
+        $id = strtoupper($need['nom']);
643
+        $r = plugin_controler_necessite(
644
+            $liste,
645
+            $id,
646
+            $need['compatibilite'] ?? '',
647
+            $balise
648
+        );
649
+        if ($r) {
650
+            $msg[] = $r;
651
+        }
652
+    }
653
+
654
+    return $msg;
655 655
 }
656 656
 
657 657
 /**
@@ -673,19 +673,19 @@  discard block
 block discarded – undo
673 673
  *    Message d'erreur lorsque la dépendance est absente.
674 674
  **/
675 675
 function plugin_controler_necessite($liste, $nom, $intervalle, $balise) {
676
-	if (isset($liste[$nom]) and plugin_version_compatible($intervalle, $liste[$nom]['version'])) {
677
-		return '';
678
-	}
679
-	// Si l'on a un <utilise="plugin non actif" />, ne pas renvoyer d'erreur
680
-	if ($balise === 'utilise' and !isset($liste[$nom])) {
681
-		return '';
682
-	}
683
-	return plugin_message_incompatibilite(
684
-		$intervalle,
685
-		(isset($liste[$nom]) ? $liste[$nom]['version'] : ''),
686
-		$nom,
687
-		$balise
688
-	);
676
+    if (isset($liste[$nom]) and plugin_version_compatible($intervalle, $liste[$nom]['version'])) {
677
+        return '';
678
+    }
679
+    // Si l'on a un <utilise="plugin non actif" />, ne pas renvoyer d'erreur
680
+    if ($balise === 'utilise' and !isset($liste[$nom])) {
681
+        return '';
682
+    }
683
+    return plugin_message_incompatibilite(
684
+        $intervalle,
685
+        (isset($liste[$nom]) ? $liste[$nom]['version'] : ''),
686
+        $nom,
687
+        $balise
688
+    );
689 689
 }
690 690
 
691 691
 /**
@@ -702,70 +702,70 @@  discard block
 block discarded – undo
702 702
  */
703 703
 function plugin_message_incompatibilite($intervalle, $version, $nom, $balise) {
704 704
 
705
-	// prendre en compte les erreurs de dépendances à PHP
706
-	// ou à une extension PHP avec des messages d'erreurs dédiés.
707
-	$type = 'plugin';
708
-	if ($nom === 'SPIP') {
709
-		$type = 'spip';
710
-	} elseif ($nom === 'PHP') {
711
-		$type = 'php';
712
-	} elseif (strncmp($nom, 'PHP:', 4) === 0) {
713
-		$type = 'extension_php';
714
-		[, $nom] = explode(':', $nom, 2);
715
-	}
716
-
717
-	if (preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
718
-		$minimum = $regs[1];
719
-		$maximum = $regs[2];
720
-
721
-		$minimum_inclus = $intervalle[0] == '[';
722
-		$maximum_inclus = substr($intervalle, -1) == ']';
723
-
724
-		if (strlen($minimum)) {
725
-			if ($minimum_inclus and spip_version_compare($version, $minimum, '<')) {
726
-				return _T("plugin_{$balise}_{$type}", [
727
-					'plugin' => $nom,
728
-					'version' => ' &ge; ' . $minimum
729
-				]);
730
-			}
731
-			if (!$minimum_inclus and spip_version_compare($version, $minimum, '<=')) {
732
-				return _T("plugin_{$balise}_{$type}", [
733
-					'plugin' => $nom,
734
-					'version' => ' &gt; ' . $minimum
735
-				]);
736
-			}
737
-		}
738
-
739
-		if (strlen($maximum)) {
740
-			if ($maximum_inclus and spip_version_compare($version, $maximum, '>')) {
741
-				return _T("plugin_{$balise}_{$type}", [
742
-					'plugin' => $nom,
743
-					'version' => ' &le; ' . $maximum
744
-				]);
745
-			}
746
-			if (!$maximum_inclus and spip_version_compare($version, $maximum, '>=')) {
747
-				return _T("plugin_{$balise}_plugin", [
748
-					'plugin' => $nom,
749
-					'version' => ' &lt; ' . $maximum
750
-				]);
751
-			}
752
-		}
753
-	}
754
-
755
-	// note : il ne peut pas y avoir d'erreur sur
756
-	// - un 'utilise' sans version.
757
-	// - un 'php' sans version.
758
-	return _T("plugin_necessite_{$type}_sans_version", ['plugin' => $nom]);
705
+    // prendre en compte les erreurs de dépendances à PHP
706
+    // ou à une extension PHP avec des messages d'erreurs dédiés.
707
+    $type = 'plugin';
708
+    if ($nom === 'SPIP') {
709
+        $type = 'spip';
710
+    } elseif ($nom === 'PHP') {
711
+        $type = 'php';
712
+    } elseif (strncmp($nom, 'PHP:', 4) === 0) {
713
+        $type = 'extension_php';
714
+        [, $nom] = explode(':', $nom, 2);
715
+    }
716
+
717
+    if (preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
718
+        $minimum = $regs[1];
719
+        $maximum = $regs[2];
720
+
721
+        $minimum_inclus = $intervalle[0] == '[';
722
+        $maximum_inclus = substr($intervalle, -1) == ']';
723
+
724
+        if (strlen($minimum)) {
725
+            if ($minimum_inclus and spip_version_compare($version, $minimum, '<')) {
726
+                return _T("plugin_{$balise}_{$type}", [
727
+                    'plugin' => $nom,
728
+                    'version' => ' &ge; ' . $minimum
729
+                ]);
730
+            }
731
+            if (!$minimum_inclus and spip_version_compare($version, $minimum, '<=')) {
732
+                return _T("plugin_{$balise}_{$type}", [
733
+                    'plugin' => $nom,
734
+                    'version' => ' &gt; ' . $minimum
735
+                ]);
736
+            }
737
+        }
738
+
739
+        if (strlen($maximum)) {
740
+            if ($maximum_inclus and spip_version_compare($version, $maximum, '>')) {
741
+                return _T("plugin_{$balise}_{$type}", [
742
+                    'plugin' => $nom,
743
+                    'version' => ' &le; ' . $maximum
744
+                ]);
745
+            }
746
+            if (!$maximum_inclus and spip_version_compare($version, $maximum, '>=')) {
747
+                return _T("plugin_{$balise}_plugin", [
748
+                    'plugin' => $nom,
749
+                    'version' => ' &lt; ' . $maximum
750
+                ]);
751
+            }
752
+        }
753
+    }
754
+
755
+    // note : il ne peut pas y avoir d'erreur sur
756
+    // - un 'utilise' sans version.
757
+    // - un 'php' sans version.
758
+    return _T("plugin_necessite_{$type}_sans_version", ['plugin' => $nom]);
759 759
 }
760 760
 
761 761
 
762 762
 function plugin_controler_lib($lib, $url) {
763
-	/* Feature sortie du core, voir STP
763
+    /* Feature sortie du core, voir STP
764 764
 	 * if ($url) {
765 765
 		include_spip('inc/charger_plugin');
766 766
 		$url = '<br />'	. bouton_telechargement_plugin($url, 'lib');
767 767
 	}*/
768
-	return _T('plugin_necessite_lib', ['lib' => $lib]) . " <a href='$url'>$url</a>";
768
+    return _T('plugin_necessite_lib', ['lib' => $lib]) . " <a href='$url'>$url</a>";
769 769
 }
770 770
 
771 771
 
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
  *     true si il y a eu des modifications sur la liste des plugins actifs, false sinon
781 781
  **/
782 782
 function actualise_plugins_actifs($pipe_recherche = false) {
783
-	return ecrire_plugin_actifs('', $pipe_recherche, 'force');
783
+    return ecrire_plugin_actifs('', $pipe_recherche, 'force');
784 784
 }
785 785
 
786 786
 
@@ -807,116 +807,116 @@  discard block
 block discarded – undo
807 807
  **/
808 808
 function ecrire_plugin_actifs($plugin, $pipe_recherche = false, $operation = 'raz') {
809 809
 
810
-	// creer le repertoire cache/ si necessaire ! (installation notamment)
811
-	$cache = sous_repertoire(_DIR_CACHE, '', false, true);
812
-
813
-	// Si on n'a ni cache accessible, ni connexion SQL, on ne peut pas faire grand chose encore.
814
-	if (!$cache and !spip_connect()) {
815
-		return false;
816
-	}
817
-
818
-	if ($operation != 'raz') {
819
-		$plugin_valides = liste_chemin_plugin_actifs();
820
-		$plugin_valides = is_plugin_dir($plugin_valides);
821
-		if (defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
822
-			$plugin_valides_supp = liste_chemin_plugin_actifs(_DIR_PLUGINS_SUPPL);
823
-			$plugin_valides_supp = is_plugin_dir($plugin_valides_supp, _DIR_PLUGINS_SUPPL);
824
-			$plugin_valides = array_merge($plugin_valides, $plugin_valides_supp);
825
-		}
826
-		// si des plugins sont en attentes (coches mais impossible a activer)
827
-		// on les reinjecte ici
828
-		if (
829
-			isset($GLOBALS['meta']['plugin_attente'])
830
-			and $a = unserialize($GLOBALS['meta']['plugin_attente'])
831
-		) {
832
-			$plugin_valides = $plugin_valides + liste_chemin_plugin($a);
833
-		}
834
-
835
-		if ($operation == 'ajoute') {
836
-			$plugin = array_merge($plugin_valides, $plugin);
837
-		} elseif ($operation == 'enleve') {
838
-			$plugin = array_diff($plugin_valides, $plugin);
839
-		} else {
840
-			$plugin = $plugin_valides;
841
-		}
842
-	}
843
-	$actifs_avant = $GLOBALS['meta']['plugin'] ?? '';
844
-
845
-	// si une fonction de gestion de dependances existe, l'appeler ici
846
-	if ($ajouter_dependances = charger_fonction('ajouter_dependances', 'plugins', true)) {
847
-		$plugin = $ajouter_dependances($plugin);
848
-	}
849
-
850
-	// recharger le xml des plugins a activer
851
-	// on force le reload ici, meme si le fichier xml n'a pas change
852
-	// pour ne pas rater l'ajout ou la suppression d'un fichier fonctions/options/administrations
853
-	// pourra etre evite quand on ne supportera plus les plugin.xml
854
-	// en deplacant la detection de ces fichiers dans la compilation ci dessous
855
-	[$infos, $liste, $invalides] = liste_plugin_valides($plugin, true);
856
-	// trouver l'ordre d'activation
857
-	[$plugin_valides, $ordre, $reste] = plugin_trier($infos, $liste);
858
-	if ($invalides or $reste) {
859
-		plugins_erreurs(array_merge($invalides, $reste), $liste, $infos);
860
-	}
861
-
862
-	// Ignorer les plugins necessitant une lib absente
863
-	// et preparer la meta d'entete Http
864
-	$err = $msg = $header = [];
865
-	foreach ($plugin_valides as $p => $resume) {
866
-		// Les headers ne doivent pas indiquer les versions des extensions PHP, ni la version PHP
867
-		if (!str_starts_with($p, 'PHP:') and $p !== 'PHP') {
868
-			$header[] = $p . ($resume['version'] ? '(' . $resume['version'] . ')' : '');
869
-		}
870
-		if ($resume['dir']) {
871
-			foreach ($infos[$resume['dir_type']][$resume['dir']]['lib'] as $l) {
872
-				if (!find_in_path($l['nom'], 'lib/')) {
873
-					$err[$p] = $resume;
874
-					$msg[$p][] = $l;
875
-					unset($plugin_valides[$p]);
876
-				}
877
-			}
878
-		}
879
-	}
880
-	if ($err) {
881
-		plugins_erreurs($err, '', $infos, $msg);
882
-	}
883
-
884
-	if (isset($GLOBALS['meta']['message_crash_plugins'])) {
885
-		effacer_meta('message_crash_plugins');
886
-	}
887
-	ecrire_meta('plugin', serialize($plugin_valides));
888
-	$liste = array_diff_key($liste, $plugin_valides);
889
-	ecrire_meta('plugin_attente', serialize($liste));
890
-	$header = strtolower(implode(',', $header));
891
-	if (!isset($GLOBALS['spip_header_silencieux']) or !$GLOBALS['spip_header_silencieux']) {
892
-		ecrire_fichier(
893
-			_DIR_VAR . 'config.txt',
894
-			(defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : 'Composed-By: SPIP') . ' ' . $GLOBALS['spip_version_affichee'] . ' @ www.spip.net + ' . $header
895
-		);
896
-	} else {
897
-		@unlink(_DIR_VAR . 'config.txt');
898
-	}
899
-	// generer charger_plugins_chemin.php
900
-	plugins_precompile_chemin($plugin_valides, $ordre);
901
-	// generer les fichiers
902
-	// - charger_plugins_options.php
903
-	// - charger_plugins_fonctions.php
904
-	plugins_precompile_xxxtions($plugin_valides, $ordre);
905
-	// charger les chemins des plugins et les fichiers d'options
906
-	// (qui peuvent déclarer / utiliser des pipelines, ajouter d'autres chemins)
907
-	plugins_amorcer_plugins_actifs();
908
-	// mise a jour de la matrice des pipelines
909
-	$prepend_code = pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche);
910
-	// generer le fichier _CACHE_PIPELINE
911
-	pipeline_precompile($prepend_code);
912
-
913
-	if (spip_connect()) {
914
-		// lancer et initialiser les nouveaux crons !
915
-		include_spip('inc/genie');
916
-		genie_queue_watch_dist();
917
-	}
918
-
919
-	return ($GLOBALS['meta']['plugin'] != $actifs_avant);
810
+    // creer le repertoire cache/ si necessaire ! (installation notamment)
811
+    $cache = sous_repertoire(_DIR_CACHE, '', false, true);
812
+
813
+    // Si on n'a ni cache accessible, ni connexion SQL, on ne peut pas faire grand chose encore.
814
+    if (!$cache and !spip_connect()) {
815
+        return false;
816
+    }
817
+
818
+    if ($operation != 'raz') {
819
+        $plugin_valides = liste_chemin_plugin_actifs();
820
+        $plugin_valides = is_plugin_dir($plugin_valides);
821
+        if (defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
822
+            $plugin_valides_supp = liste_chemin_plugin_actifs(_DIR_PLUGINS_SUPPL);
823
+            $plugin_valides_supp = is_plugin_dir($plugin_valides_supp, _DIR_PLUGINS_SUPPL);
824
+            $plugin_valides = array_merge($plugin_valides, $plugin_valides_supp);
825
+        }
826
+        // si des plugins sont en attentes (coches mais impossible a activer)
827
+        // on les reinjecte ici
828
+        if (
829
+            isset($GLOBALS['meta']['plugin_attente'])
830
+            and $a = unserialize($GLOBALS['meta']['plugin_attente'])
831
+        ) {
832
+            $plugin_valides = $plugin_valides + liste_chemin_plugin($a);
833
+        }
834
+
835
+        if ($operation == 'ajoute') {
836
+            $plugin = array_merge($plugin_valides, $plugin);
837
+        } elseif ($operation == 'enleve') {
838
+            $plugin = array_diff($plugin_valides, $plugin);
839
+        } else {
840
+            $plugin = $plugin_valides;
841
+        }
842
+    }
843
+    $actifs_avant = $GLOBALS['meta']['plugin'] ?? '';
844
+
845
+    // si une fonction de gestion de dependances existe, l'appeler ici
846
+    if ($ajouter_dependances = charger_fonction('ajouter_dependances', 'plugins', true)) {
847
+        $plugin = $ajouter_dependances($plugin);
848
+    }
849
+
850
+    // recharger le xml des plugins a activer
851
+    // on force le reload ici, meme si le fichier xml n'a pas change
852
+    // pour ne pas rater l'ajout ou la suppression d'un fichier fonctions/options/administrations
853
+    // pourra etre evite quand on ne supportera plus les plugin.xml
854
+    // en deplacant la detection de ces fichiers dans la compilation ci dessous
855
+    [$infos, $liste, $invalides] = liste_plugin_valides($plugin, true);
856
+    // trouver l'ordre d'activation
857
+    [$plugin_valides, $ordre, $reste] = plugin_trier($infos, $liste);
858
+    if ($invalides or $reste) {
859
+        plugins_erreurs(array_merge($invalides, $reste), $liste, $infos);
860
+    }
861
+
862
+    // Ignorer les plugins necessitant une lib absente
863
+    // et preparer la meta d'entete Http
864
+    $err = $msg = $header = [];
865
+    foreach ($plugin_valides as $p => $resume) {
866
+        // Les headers ne doivent pas indiquer les versions des extensions PHP, ni la version PHP
867
+        if (!str_starts_with($p, 'PHP:') and $p !== 'PHP') {
868
+            $header[] = $p . ($resume['version'] ? '(' . $resume['version'] . ')' : '');
869
+        }
870
+        if ($resume['dir']) {
871
+            foreach ($infos[$resume['dir_type']][$resume['dir']]['lib'] as $l) {
872
+                if (!find_in_path($l['nom'], 'lib/')) {
873
+                    $err[$p] = $resume;
874
+                    $msg[$p][] = $l;
875
+                    unset($plugin_valides[$p]);
876
+                }
877
+            }
878
+        }
879
+    }
880
+    if ($err) {
881
+        plugins_erreurs($err, '', $infos, $msg);
882
+    }
883
+
884
+    if (isset($GLOBALS['meta']['message_crash_plugins'])) {
885
+        effacer_meta('message_crash_plugins');
886
+    }
887
+    ecrire_meta('plugin', serialize($plugin_valides));
888
+    $liste = array_diff_key($liste, $plugin_valides);
889
+    ecrire_meta('plugin_attente', serialize($liste));
890
+    $header = strtolower(implode(',', $header));
891
+    if (!isset($GLOBALS['spip_header_silencieux']) or !$GLOBALS['spip_header_silencieux']) {
892
+        ecrire_fichier(
893
+            _DIR_VAR . 'config.txt',
894
+            (defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : 'Composed-By: SPIP') . ' ' . $GLOBALS['spip_version_affichee'] . ' @ www.spip.net + ' . $header
895
+        );
896
+    } else {
897
+        @unlink(_DIR_VAR . 'config.txt');
898
+    }
899
+    // generer charger_plugins_chemin.php
900
+    plugins_precompile_chemin($plugin_valides, $ordre);
901
+    // generer les fichiers
902
+    // - charger_plugins_options.php
903
+    // - charger_plugins_fonctions.php
904
+    plugins_precompile_xxxtions($plugin_valides, $ordre);
905
+    // charger les chemins des plugins et les fichiers d'options
906
+    // (qui peuvent déclarer / utiliser des pipelines, ajouter d'autres chemins)
907
+    plugins_amorcer_plugins_actifs();
908
+    // mise a jour de la matrice des pipelines
909
+    $prepend_code = pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche);
910
+    // generer le fichier _CACHE_PIPELINE
911
+    pipeline_precompile($prepend_code);
912
+
913
+    if (spip_connect()) {
914
+        // lancer et initialiser les nouveaux crons !
915
+        include_spip('inc/genie');
916
+        genie_queue_watch_dist();
917
+    }
918
+
919
+    return ($GLOBALS['meta']['plugin'] != $actifs_avant);
920 920
 }
921 921
 
922 922
 /**
@@ -935,74 +935,74 @@  discard block
 block discarded – undo
935 935
  *     Couples (prefixe => infos complètes) des plugins qui seront actifs, dans l'ordre de leurs dépendances
936 936
 **/
937 937
 function plugins_precompile_chemin($plugin_valides, $ordre) {
938
-	$chemins = [
939
-		'public' => [],
940
-		'prive' => []
941
-	];
942
-	$contenu = '';
943
-	foreach ($ordre as $p => $info) {
944
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
945
-		if (isset($plugin_valides[$p])) {
946
-			$dir_type = $plugin_valides[$p]['dir_type'];
947
-			$plug = $plugin_valides[$p]['dir'];
948
-			// definir le plugin, donc le path avant l'include du fichier options
949
-			// permet de faire des include_spip pour attraper un inc_ du plugin
950
-
951
-			$dir = $dir_type . ".'" . $plug . "/'";
952
-
953
-			$prefix = strtoupper(preg_replace(',\W,', '_', $info['prefix']));
954
-			if (
955
-				$prefix !== 'SPIP'
956
-				and !str_contains($dir, ':') // exclure le cas des procure:
957
-			) {
958
-				$contenu .= "define('_DIR_PLUGIN_$prefix',$dir);\n";
959
-				if (!$info['chemin']) {
960
-					$chemins['public'][] = "_DIR_PLUGIN_$prefix";
961
-					$chemins['prive'][] = "_DIR_PLUGIN_$prefix";
962
-					if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
963
-						$chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
964
-					}
965
-				}
966
-				else {
967
-					foreach ($info['chemin'] as $chemin) {
968
-						if (
969
-							!isset($chemin['version']) or plugin_version_compatible(
970
-								$chemin['version'],
971
-								$GLOBALS['spip_version_branche'],
972
-								'spip'
973
-							)
974
-						) {
975
-							$dir = $chemin['path'];
976
-							if (strlen($dir) and $dir[0] == '/') {
977
-								$dir = substr($dir, 1);
978
-							}
979
-							if (strlen($dir) and $dir == './') {
980
-								$dir = '';
981
-							}
982
-							if (strlen($dir)) {
983
-								$dir = rtrim($dir, '/') . '/';
984
-							}
985
-							if (!isset($chemin['type']) or $chemin['type'] == 'public') {
986
-								$chemins['public'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : '');
987
-							}
988
-							if (!isset($chemin['type']) or $chemin['type'] == 'prive') {
989
-								$chemins['prive'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : '');
990
-							}
991
-						}
992
-					}
993
-				}
994
-			}
995
-		}
996
-	}
997
-	if (count($chemins['public']) or count($chemins['prive'])) {
998
-		$contenu .= 'if (_DIR_RESTREINT) _chemin([' . implode(
999
-			',',
1000
-			array_reverse($chemins['public'])
1001
-		) . "]);\n"
1002
-			. 'else _chemin([' . implode(',', array_reverse($chemins['prive'])) . "]);\n";
1003
-	}
1004
-
1005
-	ecrire_fichier_php(_CACHE_PLUGINS_PATH, $contenu);
938
+    $chemins = [
939
+        'public' => [],
940
+        'prive' => []
941
+    ];
942
+    $contenu = '';
943
+    foreach ($ordre as $p => $info) {
944
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
945
+        if (isset($plugin_valides[$p])) {
946
+            $dir_type = $plugin_valides[$p]['dir_type'];
947
+            $plug = $plugin_valides[$p]['dir'];
948
+            // definir le plugin, donc le path avant l'include du fichier options
949
+            // permet de faire des include_spip pour attraper un inc_ du plugin
950
+
951
+            $dir = $dir_type . ".'" . $plug . "/'";
952
+
953
+            $prefix = strtoupper(preg_replace(',\W,', '_', $info['prefix']));
954
+            if (
955
+                $prefix !== 'SPIP'
956
+                and !str_contains($dir, ':') // exclure le cas des procure:
957
+            ) {
958
+                $contenu .= "define('_DIR_PLUGIN_$prefix',$dir);\n";
959
+                if (!$info['chemin']) {
960
+                    $chemins['public'][] = "_DIR_PLUGIN_$prefix";
961
+                    $chemins['prive'][] = "_DIR_PLUGIN_$prefix";
962
+                    if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
963
+                        $chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
964
+                    }
965
+                }
966
+                else {
967
+                    foreach ($info['chemin'] as $chemin) {
968
+                        if (
969
+                            !isset($chemin['version']) or plugin_version_compatible(
970
+                                $chemin['version'],
971
+                                $GLOBALS['spip_version_branche'],
972
+                                'spip'
973
+                            )
974
+                        ) {
975
+                            $dir = $chemin['path'];
976
+                            if (strlen($dir) and $dir[0] == '/') {
977
+                                $dir = substr($dir, 1);
978
+                            }
979
+                            if (strlen($dir) and $dir == './') {
980
+                                $dir = '';
981
+                            }
982
+                            if (strlen($dir)) {
983
+                                $dir = rtrim($dir, '/') . '/';
984
+                            }
985
+                            if (!isset($chemin['type']) or $chemin['type'] == 'public') {
986
+                                $chemins['public'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : '');
987
+                            }
988
+                            if (!isset($chemin['type']) or $chemin['type'] == 'prive') {
989
+                                $chemins['prive'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : '');
990
+                            }
991
+                        }
992
+                    }
993
+                }
994
+            }
995
+        }
996
+    }
997
+    if (count($chemins['public']) or count($chemins['prive'])) {
998
+        $contenu .= 'if (_DIR_RESTREINT) _chemin([' . implode(
999
+            ',',
1000
+            array_reverse($chemins['public'])
1001
+        ) . "]);\n"
1002
+            . 'else _chemin([' . implode(',', array_reverse($chemins['prive'])) . "]);\n";
1003
+    }
1004
+
1005
+    ecrire_fichier_php(_CACHE_PLUGINS_PATH, $contenu);
1006 1006
 }
1007 1007
 
1008 1008
 /**
@@ -1020,67 +1020,67 @@  discard block
 block discarded – undo
1020 1020
  *     Couples (prefixe => infos complètes) des plugins qui seront actifs, dans l'ordre de leurs dépendances
1021 1021
 **/
1022 1022
 function plugins_precompile_xxxtions($plugin_valides, $ordre) {
1023
-	$contenu = ['options' => '', 'fonctions' => ''];
1024
-	$boutons = [];
1025
-	$onglets = [];
1026
-	$sign = '';
1027
-
1028
-	foreach ($ordre as $p => $info) {
1029
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
1030
-		if (isset($plugin_valides[$p])) {
1031
-			$dir_type = $plugin_valides[$p]['dir_type'];
1032
-			$plug = $plugin_valides[$p]['dir'];
1033
-			$dir = constant($dir_type);
1034
-			$root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1035
-			if ($info['menu']) {
1036
-				$boutons = array_merge($boutons, $info['menu']);
1037
-			}
1038
-			if ($info['onglet']) {
1039
-				$onglets = array_merge($onglets, $info['onglet']);
1040
-			}
1041
-			foreach ($contenu as $charge => $v) {
1042
-				// si pas declare/detecte a la lecture du paquet.xml,
1043
-				// detecer a nouveau ici puisque son ajout ne provoque pas une modif du paquet.xml
1044
-				// donc ni sa relecture, ni sa detection
1045
-				if (
1046
-					!isset($info[$charge])
1047
-					and $dir // exclure le cas du plugin "SPIP"
1048
-					and !str_contains($dir, ':') // exclure le cas des procure:
1049
-					and file_exists("$dir$plug/paquet.xml") // uniquement pour les paquet.xml
1050
-				) {
1051
-					if (is_readable("$dir$plug/" . ($file = $info['prefix'] . '_' . $charge . '.php'))) {
1052
-						$info[$charge] = [$file];
1053
-					}
1054
-				}
1055
-				if (isset($info[$charge])) {
1056
-					$files = $info[$charge];
1057
-					foreach ($files as $k => $file) {
1058
-						// on genere un if file_exists devant chaque include
1059
-						// pour pouvoir garder le meme niveau d'erreur general
1060
-						$file = trim($file);
1061
-						if (
1062
-							!is_readable("$dir$plug/$file")
1063
-							// uniquement pour les paquet.xml
1064
-							and file_exists("$dir$plug/paquet.xml")
1065
-						) {
1066
-							unset($info[$charge][$k]);
1067
-						} else {
1068
-							$_file = $root_dir_type . ".'$plug/$file'";
1069
-							$contenu[$charge] .= "include_once_check($_file);\n";
1070
-						}
1071
-					}
1072
-				}
1073
-			}
1074
-			$sign .= md5(serialize($info));
1075
-		}
1076
-	}
1077
-
1078
-	$contenu['options'] = "define('_PLUGINS_HASH','" . md5($sign) . "');\n" . $contenu['options'];
1079
-	$contenu['fonctions'] .= plugin_ongletbouton('boutons_plugins', $boutons)
1080
-		. plugin_ongletbouton('onglets_plugins', $onglets);
1081
-
1082
-	ecrire_fichier_php(_CACHE_PLUGINS_OPT, $contenu['options']);
1083
-	ecrire_fichier_php(_CACHE_PLUGINS_FCT, $contenu['fonctions']);
1023
+    $contenu = ['options' => '', 'fonctions' => ''];
1024
+    $boutons = [];
1025
+    $onglets = [];
1026
+    $sign = '';
1027
+
1028
+    foreach ($ordre as $p => $info) {
1029
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
1030
+        if (isset($plugin_valides[$p])) {
1031
+            $dir_type = $plugin_valides[$p]['dir_type'];
1032
+            $plug = $plugin_valides[$p]['dir'];
1033
+            $dir = constant($dir_type);
1034
+            $root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1035
+            if ($info['menu']) {
1036
+                $boutons = array_merge($boutons, $info['menu']);
1037
+            }
1038
+            if ($info['onglet']) {
1039
+                $onglets = array_merge($onglets, $info['onglet']);
1040
+            }
1041
+            foreach ($contenu as $charge => $v) {
1042
+                // si pas declare/detecte a la lecture du paquet.xml,
1043
+                // detecer a nouveau ici puisque son ajout ne provoque pas une modif du paquet.xml
1044
+                // donc ni sa relecture, ni sa detection
1045
+                if (
1046
+                    !isset($info[$charge])
1047
+                    and $dir // exclure le cas du plugin "SPIP"
1048
+                    and !str_contains($dir, ':') // exclure le cas des procure:
1049
+                    and file_exists("$dir$plug/paquet.xml") // uniquement pour les paquet.xml
1050
+                ) {
1051
+                    if (is_readable("$dir$plug/" . ($file = $info['prefix'] . '_' . $charge . '.php'))) {
1052
+                        $info[$charge] = [$file];
1053
+                    }
1054
+                }
1055
+                if (isset($info[$charge])) {
1056
+                    $files = $info[$charge];
1057
+                    foreach ($files as $k => $file) {
1058
+                        // on genere un if file_exists devant chaque include
1059
+                        // pour pouvoir garder le meme niveau d'erreur general
1060
+                        $file = trim($file);
1061
+                        if (
1062
+                            !is_readable("$dir$plug/$file")
1063
+                            // uniquement pour les paquet.xml
1064
+                            and file_exists("$dir$plug/paquet.xml")
1065
+                        ) {
1066
+                            unset($info[$charge][$k]);
1067
+                        } else {
1068
+                            $_file = $root_dir_type . ".'$plug/$file'";
1069
+                            $contenu[$charge] .= "include_once_check($_file);\n";
1070
+                        }
1071
+                    }
1072
+                }
1073
+            }
1074
+            $sign .= md5(serialize($info));
1075
+        }
1076
+    }
1077
+
1078
+    $contenu['options'] = "define('_PLUGINS_HASH','" . md5($sign) . "');\n" . $contenu['options'];
1079
+    $contenu['fonctions'] .= plugin_ongletbouton('boutons_plugins', $boutons)
1080
+        . plugin_ongletbouton('onglets_plugins', $onglets);
1081
+
1082
+    ecrire_fichier_php(_CACHE_PLUGINS_OPT, $contenu['options']);
1083
+    ecrire_fichier_php(_CACHE_PLUGINS_FCT, $contenu['fonctions']);
1084 1084
 }
1085 1085
 
1086 1086
 /**
@@ -1099,24 +1099,24 @@  discard block
 block discarded – undo
1099 1099
  * @return string Code php
1100 1100
  */
1101 1101
 function plugin_ongletbouton($nom, $val) {
1102
-	if (!$val) {
1103
-		$val = [];
1104
-	}
1105
-
1106
-	$val = serialize($val);
1107
-	$md5 = md5($val);
1108
-
1109
-	if (!defined("_UPDATED_$nom")) {
1110
-		define("_UPDATED_$nom", $val);
1111
-		define("_UPDATED_md5_$nom", $md5);
1112
-	}
1113
-	$val = "unserialize('" . str_replace("'", "\'", $val) . "')";
1114
-
1115
-	return
1116
-		"if (!function_exists('$nom')) {\n"
1117
-		. "function $nom(){return defined('_UPDATED_$nom')?unserialize(_UPDATED_$nom):$val;}\n"
1118
-		. "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'" . $md5 . "';}\n"
1119
-		. "}\n";
1102
+    if (!$val) {
1103
+        $val = [];
1104
+    }
1105
+
1106
+    $val = serialize($val);
1107
+    $md5 = md5($val);
1108
+
1109
+    if (!defined("_UPDATED_$nom")) {
1110
+        define("_UPDATED_$nom", $val);
1111
+        define("_UPDATED_md5_$nom", $md5);
1112
+    }
1113
+    $val = "unserialize('" . str_replace("'", "\'", $val) . "')";
1114
+
1115
+    return
1116
+        "if (!function_exists('$nom')) {\n"
1117
+        . "function $nom(){return defined('_UPDATED_$nom')?unserialize(_UPDATED_$nom):$val;}\n"
1118
+        . "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'" . $md5 . "';}\n"
1119
+        . "}\n";
1120 1120
 }
1121 1121
 
1122 1122
 /**
@@ -1131,15 +1131,15 @@  discard block
 block discarded – undo
1131 1131
 **/
1132 1132
 function plugins_amorcer_plugins_actifs() {
1133 1133
 
1134
-	if (@is_readable(_CACHE_PLUGINS_PATH)) {
1135
-		include_once(_CACHE_PLUGINS_PATH);
1136
-	}
1134
+    if (@is_readable(_CACHE_PLUGINS_PATH)) {
1135
+        include_once(_CACHE_PLUGINS_PATH);
1136
+    }
1137 1137
 
1138
-	if (@is_readable(_CACHE_PLUGINS_OPT)) {
1139
-		include_once(_CACHE_PLUGINS_OPT);
1140
-	} else {
1141
-		spip_log('pipelines desactives: impossible de produire ' . _CACHE_PLUGINS_OPT);
1142
-	}
1138
+    if (@is_readable(_CACHE_PLUGINS_OPT)) {
1139
+        include_once(_CACHE_PLUGINS_OPT);
1140
+    } else {
1141
+        spip_log('pipelines desactives: impossible de produire ' . _CACHE_PLUGINS_OPT);
1142
+    }
1143 1143
 }
1144 1144
 
1145 1145
 /**
@@ -1162,140 +1162,140 @@  discard block
 block discarded – undo
1162 1162
  *     Couples (nom du pipeline => Code PHP à insérer au début du pipeline)
1163 1163
 **/
1164 1164
 function pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche) {
1165
-	static $liste_pipe_manquants = [];
1166
-	if (($pipe_recherche) && (!in_array($pipe_recherche, $liste_pipe_manquants))) {
1167
-		$liste_pipe_manquants[] = $pipe_recherche;
1168
-	}
1169
-
1170
-	$prepend_code = [];
1171
-
1172
-	foreach ($ordre as $p => $info) {
1173
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
1174
-		if (isset($plugin_valides[$p])) {
1175
-			$dir_type = $plugin_valides[$p]['dir_type'];
1176
-			$root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1177
-			$plug = $plugin_valides[$p]['dir'];
1178
-			$prefix = (($info['prefix'] == 'spip') ? '' : $info['prefix'] . '_');
1179
-			if (isset($info['pipeline']) and is_array($info['pipeline'])) {
1180
-				foreach ($info['pipeline'] as $pipe) {
1181
-					$nom = $pipe['nom'];
1182
-					if (isset($pipe['action'])) {
1183
-						$action = $pipe['action'];
1184
-					} else {
1185
-						$action = $nom;
1186
-					}
1187
-					$nomlower = strtolower($nom);
1188
-					if (
1189
-						$nomlower != $nom
1190
-						and isset($GLOBALS['spip_pipeline'][$nom])
1191
-						and !isset($GLOBALS['spip_pipeline'][$nomlower])
1192
-					) {
1193
-						$GLOBALS['spip_pipeline'][$nomlower] = $GLOBALS['spip_pipeline'][$nom];
1194
-						unset($GLOBALS['spip_pipeline'][$nom]);
1195
-					}
1196
-					$nom = $nomlower;
1197
-					// une action vide est une declaration qui ne doit pas etre compilee !
1198
-					if (!isset($GLOBALS['spip_pipeline'][$nom])) { // creer le pipeline eventuel
1199
-					$GLOBALS['spip_pipeline'][$nom] = '';
1200
-					}
1201
-					if ($action) {
1202
-						if (strpos($GLOBALS['spip_pipeline'][$nom], (string) "|$prefix$action") === false) {
1203
-							$GLOBALS['spip_pipeline'][$nom] = preg_replace(
1204
-								',(\|\||$),',
1205
-								"|$prefix$action\\1",
1206
-								$GLOBALS['spip_pipeline'][$nom],
1207
-								1
1208
-							);
1209
-						}
1210
-						if (isset($pipe['inclure'])) {
1211
-							$GLOBALS['spip_matrice']["$prefix$action"] =
1212
-								"$root_dir_type:$plug/" . $pipe['inclure'];
1213
-						}
1214
-					}
1215
-				}
1216
-			}
1217
-			if (isset($info['genie']) and is_countable($info['genie']) ? count($info['genie']) : 0) {
1218
-				if (!isset($prepend_code['taches_generales_cron'])) {
1219
-					$prepend_code['taches_generales_cron'] = '';
1220
-				}
1221
-				foreach ($info['genie'] as $genie) {
1222
-					$nom = $prefix . $genie['nom'];
1223
-					$periode = max(60, intval($genie['periode']));
1224
-					if (charger_fonction($nom, 'genie', true)) {
1225
-						$prepend_code['taches_generales_cron'] .= "\$val['$nom'] = $periode;\n";
1226
-					} else {
1227
-						spip_log("Fonction genie_$nom introuvable", _LOG_ERREUR);
1228
-					}
1229
-				}
1230
-			}
1231
-			if (isset($info['style']) and is_countable($info['style']) ? count($info['style']) : 0) {
1232
-				if (!isset($prepend_code['insert_head_css'])) {
1233
-					$prepend_code['insert_head_css'] = '';
1234
-				}
1235
-				if (!isset($prepend_code['header_prive_css'])) {
1236
-					$prepend_code['header_prive_css'] = '';
1237
-				}
1238
-				foreach ($info['style'] as $style) {
1239
-					if (isset($style['path']) and $style['path']) {
1240
-						$code = "if (\$f=timestamp(direction_css(find_in_path('" . addslashes($style['path']) . "')))) ";
1241
-					} else {
1242
-						$code = "if (\$f='" . addslashes($style['url']) . "') ";
1243
-					}
1244
-					$code .= "\$val .= '<link rel=\"stylesheet\" href=\"'.\$f.'\" type=\"text/css\"";
1245
-					if (isset($style['media']) and strlen($style['media'])) {
1246
-						$code .= ' media="' . addslashes($style['media']) . '"';
1247
-					}
1248
-					$code .= "/>';\n";
1249
-					if ($style['type'] != 'prive') {
1250
-						$prepend_code['insert_head_css'] .= $code;
1251
-					}
1252
-					if ($style['type'] != 'public') {
1253
-						$prepend_code['header_prive_css'] .= $code;
1254
-					}
1255
-				}
1256
-			}
1257
-			if (!isset($prepend_code['insert_head'])) {
1258
-				$prepend_code['insert_head'] = '';
1259
-			}
1260
-			if (!isset($prepend_code['header_prive'])) {
1261
-				$prepend_code['header_prive'] = '';
1262
-			}
1263
-			if (isset($info['script']) and is_countable($info['script']) ? count($info['script']) : 0) {
1264
-				foreach ($info['script'] as $script) {
1265
-					if (isset($script['path']) and $script['path']) {
1266
-						$code = "if (\$f=timestamp(find_in_path('" . addslashes($script['path']) . "'))) ";
1267
-					} else {
1268
-						$code = "if (\$f='" . addslashes($script['url']) . "') ";
1269
-					}
1270
-					$code .= "\$val .= '<script src=\"'.\$f.'\" type=\"text/javascript\"></script>';\n";
1271
-					if ($script['type'] != 'prive') {
1272
-						$prepend_code['insert_head'] .= $code;
1273
-					}
1274
-					if ($script['type'] != 'public') {
1275
-						$prepend_code['header_prive'] .= $code;
1276
-					}
1277
-				}
1278
-			}
1279
-		}
1280
-	}
1281
-
1282
-	$prepend_code['insert_head'] =
1283
-		"include_once_check(_DIR_RESTREINT . 'inc/pipelines.php');\n"
1284
-		. "\$val = minipipe('f_jQuery', \$val);\n"
1285
-		. $prepend_code['insert_head'];
1286
-	$prepend_code['header_prive'] =
1287
-		"include_once_check(_DIR_RESTREINT . 'inc/pipelines_ecrire.php');\n"
1288
-		. "\$val = minipipe('f_jQuery_prive', \$val);\n"
1289
-		. $prepend_code['header_prive'];
1290
-
1291
-	// on ajoute les pipe qui ont ete recenses manquants
1292
-	foreach ($liste_pipe_manquants as $add_pipe) {
1293
-		if (!isset($GLOBALS['spip_pipeline'][$add_pipe])) {
1294
-			$GLOBALS['spip_pipeline'][$add_pipe] = '';
1295
-		}
1296
-	}
1297
-
1298
-	return $prepend_code;
1165
+    static $liste_pipe_manquants = [];
1166
+    if (($pipe_recherche) && (!in_array($pipe_recherche, $liste_pipe_manquants))) {
1167
+        $liste_pipe_manquants[] = $pipe_recherche;
1168
+    }
1169
+
1170
+    $prepend_code = [];
1171
+
1172
+    foreach ($ordre as $p => $info) {
1173
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
1174
+        if (isset($plugin_valides[$p])) {
1175
+            $dir_type = $plugin_valides[$p]['dir_type'];
1176
+            $root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1177
+            $plug = $plugin_valides[$p]['dir'];
1178
+            $prefix = (($info['prefix'] == 'spip') ? '' : $info['prefix'] . '_');
1179
+            if (isset($info['pipeline']) and is_array($info['pipeline'])) {
1180
+                foreach ($info['pipeline'] as $pipe) {
1181
+                    $nom = $pipe['nom'];
1182
+                    if (isset($pipe['action'])) {
1183
+                        $action = $pipe['action'];
1184
+                    } else {
1185
+                        $action = $nom;
1186
+                    }
1187
+                    $nomlower = strtolower($nom);
1188
+                    if (
1189
+                        $nomlower != $nom
1190
+                        and isset($GLOBALS['spip_pipeline'][$nom])
1191
+                        and !isset($GLOBALS['spip_pipeline'][$nomlower])
1192
+                    ) {
1193
+                        $GLOBALS['spip_pipeline'][$nomlower] = $GLOBALS['spip_pipeline'][$nom];
1194
+                        unset($GLOBALS['spip_pipeline'][$nom]);
1195
+                    }
1196
+                    $nom = $nomlower;
1197
+                    // une action vide est une declaration qui ne doit pas etre compilee !
1198
+                    if (!isset($GLOBALS['spip_pipeline'][$nom])) { // creer le pipeline eventuel
1199
+                    $GLOBALS['spip_pipeline'][$nom] = '';
1200
+                    }
1201
+                    if ($action) {
1202
+                        if (strpos($GLOBALS['spip_pipeline'][$nom], (string) "|$prefix$action") === false) {
1203
+                            $GLOBALS['spip_pipeline'][$nom] = preg_replace(
1204
+                                ',(\|\||$),',
1205
+                                "|$prefix$action\\1",
1206
+                                $GLOBALS['spip_pipeline'][$nom],
1207
+                                1
1208
+                            );
1209
+                        }
1210
+                        if (isset($pipe['inclure'])) {
1211
+                            $GLOBALS['spip_matrice']["$prefix$action"] =
1212
+                                "$root_dir_type:$plug/" . $pipe['inclure'];
1213
+                        }
1214
+                    }
1215
+                }
1216
+            }
1217
+            if (isset($info['genie']) and is_countable($info['genie']) ? count($info['genie']) : 0) {
1218
+                if (!isset($prepend_code['taches_generales_cron'])) {
1219
+                    $prepend_code['taches_generales_cron'] = '';
1220
+                }
1221
+                foreach ($info['genie'] as $genie) {
1222
+                    $nom = $prefix . $genie['nom'];
1223
+                    $periode = max(60, intval($genie['periode']));
1224
+                    if (charger_fonction($nom, 'genie', true)) {
1225
+                        $prepend_code['taches_generales_cron'] .= "\$val['$nom'] = $periode;\n";
1226
+                    } else {
1227
+                        spip_log("Fonction genie_$nom introuvable", _LOG_ERREUR);
1228
+                    }
1229
+                }
1230
+            }
1231
+            if (isset($info['style']) and is_countable($info['style']) ? count($info['style']) : 0) {
1232
+                if (!isset($prepend_code['insert_head_css'])) {
1233
+                    $prepend_code['insert_head_css'] = '';
1234
+                }
1235
+                if (!isset($prepend_code['header_prive_css'])) {
1236
+                    $prepend_code['header_prive_css'] = '';
1237
+                }
1238
+                foreach ($info['style'] as $style) {
1239
+                    if (isset($style['path']) and $style['path']) {
1240
+                        $code = "if (\$f=timestamp(direction_css(find_in_path('" . addslashes($style['path']) . "')))) ";
1241
+                    } else {
1242
+                        $code = "if (\$f='" . addslashes($style['url']) . "') ";
1243
+                    }
1244
+                    $code .= "\$val .= '<link rel=\"stylesheet\" href=\"'.\$f.'\" type=\"text/css\"";
1245
+                    if (isset($style['media']) and strlen($style['media'])) {
1246
+                        $code .= ' media="' . addslashes($style['media']) . '"';
1247
+                    }
1248
+                    $code .= "/>';\n";
1249
+                    if ($style['type'] != 'prive') {
1250
+                        $prepend_code['insert_head_css'] .= $code;
1251
+                    }
1252
+                    if ($style['type'] != 'public') {
1253
+                        $prepend_code['header_prive_css'] .= $code;
1254
+                    }
1255
+                }
1256
+            }
1257
+            if (!isset($prepend_code['insert_head'])) {
1258
+                $prepend_code['insert_head'] = '';
1259
+            }
1260
+            if (!isset($prepend_code['header_prive'])) {
1261
+                $prepend_code['header_prive'] = '';
1262
+            }
1263
+            if (isset($info['script']) and is_countable($info['script']) ? count($info['script']) : 0) {
1264
+                foreach ($info['script'] as $script) {
1265
+                    if (isset($script['path']) and $script['path']) {
1266
+                        $code = "if (\$f=timestamp(find_in_path('" . addslashes($script['path']) . "'))) ";
1267
+                    } else {
1268
+                        $code = "if (\$f='" . addslashes($script['url']) . "') ";
1269
+                    }
1270
+                    $code .= "\$val .= '<script src=\"'.\$f.'\" type=\"text/javascript\"></script>';\n";
1271
+                    if ($script['type'] != 'prive') {
1272
+                        $prepend_code['insert_head'] .= $code;
1273
+                    }
1274
+                    if ($script['type'] != 'public') {
1275
+                        $prepend_code['header_prive'] .= $code;
1276
+                    }
1277
+                }
1278
+            }
1279
+        }
1280
+    }
1281
+
1282
+    $prepend_code['insert_head'] =
1283
+        "include_once_check(_DIR_RESTREINT . 'inc/pipelines.php');\n"
1284
+        . "\$val = minipipe('f_jQuery', \$val);\n"
1285
+        . $prepend_code['insert_head'];
1286
+    $prepend_code['header_prive'] =
1287
+        "include_once_check(_DIR_RESTREINT . 'inc/pipelines_ecrire.php');\n"
1288
+        . "\$val = minipipe('f_jQuery_prive', \$val);\n"
1289
+        . $prepend_code['header_prive'];
1290
+
1291
+    // on ajoute les pipe qui ont ete recenses manquants
1292
+    foreach ($liste_pipe_manquants as $add_pipe) {
1293
+        if (!isset($GLOBALS['spip_pipeline'][$add_pipe])) {
1294
+            $GLOBALS['spip_pipeline'][$add_pipe] = '';
1295
+        }
1296
+    }
1297
+
1298
+    return $prepend_code;
1299 1299
 }
1300 1300
 
1301 1301
 /**
@@ -1322,62 +1322,62 @@  discard block
 block discarded – undo
1322 1322
 **/
1323 1323
 function pipeline_precompile($prepend_code = []) {
1324 1324
 
1325
-	$all_pipes = $all_pipes_end = '';
1326
-	if (!empty($GLOBALS['spip_pipeline']['all'])) {
1327
-		$a = explode('||', $GLOBALS['spip_pipeline']['all'], 2);
1328
-		unset($GLOBALS['spip_pipeline']['all']);
1329
-		$all_pipes = trim(array_shift($a));
1330
-		if ($all_pipes) {
1331
-			$all_pipes = '|' . ltrim($all_pipes, '|');
1332
-		}
1333
-		if (count($a)) {
1334
-			$all_pipes_end = '||' . array_shift($a);
1335
-		}
1336
-	}
1337
-	$content = '';
1338
-	foreach ($GLOBALS['spip_pipeline'] as $action => $pipeline) {
1339
-		$s_inc = '';
1340
-		$s_call = '';
1341
-		if ($all_pipes) {
1342
-			$pipeline = preg_replace(',(\|\||$),', "$all_pipes\\1", $pipeline, 1);
1343
-		}
1344
-		if ($all_pipes_end) {
1345
-			$pipeline .= $all_pipes_end;
1346
-		}
1347
-		$pipe = array_filter(explode('|', $pipeline));
1348
-		// Eclater le pipeline en filtres et appliquer chaque filtre
1349
-		foreach ($pipe as $fonc) {
1350
-			$fonc = trim($fonc);
1351
-			$s_call .= '$val = minipipe(\'' . $fonc . '\', $val);' . "\n";
1352
-			if (isset($GLOBALS['spip_matrice'][$fonc])) {
1353
-				$file = $GLOBALS['spip_matrice'][$fonc];
1354
-				$file = "'$file'";
1355
-				// si un _DIR_XXX: est dans la chaine, on extrait la constante
1356
-				if (preg_match(',(_(DIR|ROOT)_[A-Z_]+):,Ums', $file, $regs)) {
1357
-					$dir = $regs[1];
1358
-					$root_dir = str_replace('_DIR_', '_ROOT_', $dir);
1359
-					if (defined($root_dir)) {
1360
-						$dir = $root_dir;
1361
-					}
1362
-					$file = str_replace($regs[0], "'." . $dir . ".'", $file);
1363
-					$file = str_replace("''.", '', $file);
1364
-					$file = str_replace(constant($dir), '', $file);
1365
-				}
1366
-				$s_inc .= "include_once_check($file);\n";
1367
-			}
1368
-		}
1369
-		if (strlen($s_inc)) {
1370
-			$s_inc = "static \$inc=null;\nif (!\$inc){\n$s_inc\$inc=true;\n}\n";
1371
-		}
1372
-		$content .= "// Pipeline $action \n"
1373
-			. "function execute_pipeline_$action(&\$val){\n"
1374
-			. $s_inc
1375
-			. ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action]) . "\n" : '')
1376
-			. $s_call
1377
-			. "return \$val;\n}\n";
1378
-	}
1379
-	ecrire_fichier_php(_CACHE_PIPELINES, $content);
1380
-	clear_path_cache();
1325
+    $all_pipes = $all_pipes_end = '';
1326
+    if (!empty($GLOBALS['spip_pipeline']['all'])) {
1327
+        $a = explode('||', $GLOBALS['spip_pipeline']['all'], 2);
1328
+        unset($GLOBALS['spip_pipeline']['all']);
1329
+        $all_pipes = trim(array_shift($a));
1330
+        if ($all_pipes) {
1331
+            $all_pipes = '|' . ltrim($all_pipes, '|');
1332
+        }
1333
+        if (count($a)) {
1334
+            $all_pipes_end = '||' . array_shift($a);
1335
+        }
1336
+    }
1337
+    $content = '';
1338
+    foreach ($GLOBALS['spip_pipeline'] as $action => $pipeline) {
1339
+        $s_inc = '';
1340
+        $s_call = '';
1341
+        if ($all_pipes) {
1342
+            $pipeline = preg_replace(',(\|\||$),', "$all_pipes\\1", $pipeline, 1);
1343
+        }
1344
+        if ($all_pipes_end) {
1345
+            $pipeline .= $all_pipes_end;
1346
+        }
1347
+        $pipe = array_filter(explode('|', $pipeline));
1348
+        // Eclater le pipeline en filtres et appliquer chaque filtre
1349
+        foreach ($pipe as $fonc) {
1350
+            $fonc = trim($fonc);
1351
+            $s_call .= '$val = minipipe(\'' . $fonc . '\', $val);' . "\n";
1352
+            if (isset($GLOBALS['spip_matrice'][$fonc])) {
1353
+                $file = $GLOBALS['spip_matrice'][$fonc];
1354
+                $file = "'$file'";
1355
+                // si un _DIR_XXX: est dans la chaine, on extrait la constante
1356
+                if (preg_match(',(_(DIR|ROOT)_[A-Z_]+):,Ums', $file, $regs)) {
1357
+                    $dir = $regs[1];
1358
+                    $root_dir = str_replace('_DIR_', '_ROOT_', $dir);
1359
+                    if (defined($root_dir)) {
1360
+                        $dir = $root_dir;
1361
+                    }
1362
+                    $file = str_replace($regs[0], "'." . $dir . ".'", $file);
1363
+                    $file = str_replace("''.", '', $file);
1364
+                    $file = str_replace(constant($dir), '', $file);
1365
+                }
1366
+                $s_inc .= "include_once_check($file);\n";
1367
+            }
1368
+        }
1369
+        if (strlen($s_inc)) {
1370
+            $s_inc = "static \$inc=null;\nif (!\$inc){\n$s_inc\$inc=true;\n}\n";
1371
+        }
1372
+        $content .= "// Pipeline $action \n"
1373
+            . "function execute_pipeline_$action(&\$val){\n"
1374
+            . $s_inc
1375
+            . ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action]) . "\n" : '')
1376
+            . $s_call
1377
+            . "return \$val;\n}\n";
1378
+    }
1379
+    ecrire_fichier_php(_CACHE_PIPELINES, $content);
1380
+    clear_path_cache();
1381 1381
 }
1382 1382
 
1383 1383
 
@@ -1390,12 +1390,12 @@  discard block
 block discarded – undo
1390 1390
  *     true si le plugin est actif, false sinon
1391 1391
 **/
1392 1392
 function plugin_est_installe($plug_path) {
1393
-	$plugin_installes = isset($GLOBALS['meta']['plugin_installes']) ? unserialize($GLOBALS['meta']['plugin_installes']) : [];
1394
-	if (!$plugin_installes) {
1395
-		return false;
1396
-	}
1393
+    $plugin_installes = isset($GLOBALS['meta']['plugin_installes']) ? unserialize($GLOBALS['meta']['plugin_installes']) : [];
1394
+    if (!$plugin_installes) {
1395
+        return false;
1396
+    }
1397 1397
 
1398
-	return in_array($plug_path, $plugin_installes);
1398
+    return in_array($plug_path, $plugin_installes);
1399 1399
 }
1400 1400
 
1401 1401
 
@@ -1408,46 +1408,46 @@  discard block
 block discarded – undo
1408 1408
  * @uses plugins_installer_dist()
1409 1409
  **/
1410 1410
 function plugin_installes_meta() {
1411
-	if (isset($GLOBALS['fichier_php_compile_recent'])) {
1412
-		// attendre eventuellement l'invalidation du cache opcode
1413
-		spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
1414
-	}
1415
-
1416
-	$installer_plugins = charger_fonction('installer', 'plugins');
1417
-	$meta_plug_installes = [];
1418
-	foreach (unserialize($GLOBALS['meta']['plugin']) as $prefix => $resume) {
1419
-		if ($plug = $resume['dir']) {
1420
-			$infos = $installer_plugins($plug, 'install', $resume['dir_type']);
1421
-			if ($infos) {
1422
-				if (!is_array($infos) or $infos['install_test'][0]) {
1423
-					$meta_plug_installes[] = $plug;
1424
-				}
1425
-				if (is_array($infos)) {
1426
-					[$ok, $trace] = $infos['install_test'];
1427
-					$titre = _T('plugin_titre_installation', ['plugin' => typo($infos['nom'])]);
1428
-					$result = ($ok ? ((isset($infos['upgrade']) && $infos['upgrade']) ? _T('plugin_info_upgrade_ok') : _T('plugin_info_install_ok')) : _T('avis_operation_echec'));
1429
-					if (_IS_CLI) {
1430
-						include_spip('inc/filtres');
1431
-						$trace = ltrim(textebrut($trace) . "\n" . $result);
1432
-						$trace = '    ' . str_replace("\n", "\n    ", $trace);
1433
-						echo "\n" . ($ok ? 'OK  ' : '/!\ ') . textebrut($titre) . "\n",
1434
-						  $trace,
1435
-						  "\n";
1436
-					}
1437
-					else {
1438
-						include_spip('inc/filtres_boites');
1439
-						echo "<div class='install-plugins svp_retour'>"
1440
-							. boite_ouvrir($titre, ($ok ? 'success' : 'error'))
1441
-							. $trace
1442
-							. "<div class='result'>$result</div>"
1443
-							. boite_fermer()
1444
-							. '</div>';
1445
-					}
1446
-				}
1447
-			}
1448
-		}
1449
-	}
1450
-	ecrire_meta('plugin_installes', serialize($meta_plug_installes), 'non');
1411
+    if (isset($GLOBALS['fichier_php_compile_recent'])) {
1412
+        // attendre eventuellement l'invalidation du cache opcode
1413
+        spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
1414
+    }
1415
+
1416
+    $installer_plugins = charger_fonction('installer', 'plugins');
1417
+    $meta_plug_installes = [];
1418
+    foreach (unserialize($GLOBALS['meta']['plugin']) as $prefix => $resume) {
1419
+        if ($plug = $resume['dir']) {
1420
+            $infos = $installer_plugins($plug, 'install', $resume['dir_type']);
1421
+            if ($infos) {
1422
+                if (!is_array($infos) or $infos['install_test'][0]) {
1423
+                    $meta_plug_installes[] = $plug;
1424
+                }
1425
+                if (is_array($infos)) {
1426
+                    [$ok, $trace] = $infos['install_test'];
1427
+                    $titre = _T('plugin_titre_installation', ['plugin' => typo($infos['nom'])]);
1428
+                    $result = ($ok ? ((isset($infos['upgrade']) && $infos['upgrade']) ? _T('plugin_info_upgrade_ok') : _T('plugin_info_install_ok')) : _T('avis_operation_echec'));
1429
+                    if (_IS_CLI) {
1430
+                        include_spip('inc/filtres');
1431
+                        $trace = ltrim(textebrut($trace) . "\n" . $result);
1432
+                        $trace = '    ' . str_replace("\n", "\n    ", $trace);
1433
+                        echo "\n" . ($ok ? 'OK  ' : '/!\ ') . textebrut($titre) . "\n",
1434
+                            $trace,
1435
+                            "\n";
1436
+                    }
1437
+                    else {
1438
+                        include_spip('inc/filtres_boites');
1439
+                        echo "<div class='install-plugins svp_retour'>"
1440
+                            . boite_ouvrir($titre, ($ok ? 'success' : 'error'))
1441
+                            . $trace
1442
+                            . "<div class='result'>$result</div>"
1443
+                            . boite_fermer()
1444
+                            . '</div>';
1445
+                    }
1446
+                }
1447
+            }
1448
+        }
1449
+    }
1450
+    ecrire_meta('plugin_installes', serialize($meta_plug_installes), 'non');
1451 1451
 }
1452 1452
 
1453 1453
 /**
@@ -1461,29 +1461,29 @@  discard block
 block discarded – undo
1461 1461
  *     Commentaire : code écrit en tout début de fichier, après la balise PHP ouvrante
1462 1462
 **/
1463 1463
 function ecrire_fichier_php($nom, $contenu, $comment = '') {
1464
-	if (!isset($GLOBALS['fichier_php_compile_recent'])) {
1465
-		$GLOBALS['fichier_php_compile_recent'] = 0;
1466
-	}
1467
-
1468
-	$contenu = '<' . '?php' . "\n" . $comment . "\nif (defined('_ECRIRE_INC_VERSION')) {\n" . $contenu . "}\n?" . '>';
1469
-	// si un fichier existe deja on verifie que son contenu change avant de l'ecraser
1470
-	// si pas de modif on ne touche pas au fichier initial
1471
-	if (file_exists($nom)) {
1472
-		if (substr($nom, -4) == '.php') {
1473
-			$fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1474
-		}
1475
-		else {
1476
-			$fichier_tmp = $nom . '.tmp';
1477
-		}
1478
-		file_put_contents($fichier_tmp, $contenu);
1479
-		if (md5_file($nom) == md5_file($fichier_tmp)) {
1480
-			$GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1481
-			@unlink($fichier_tmp);
1482
-			return;
1483
-		}
1484
-		@unlink($fichier_tmp);
1485
-	}
1486
-	ecrire_fichier($nom, $contenu);
1487
-	$GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1488
-	spip_clear_opcode_cache(realpath($nom));
1464
+    if (!isset($GLOBALS['fichier_php_compile_recent'])) {
1465
+        $GLOBALS['fichier_php_compile_recent'] = 0;
1466
+    }
1467
+
1468
+    $contenu = '<' . '?php' . "\n" . $comment . "\nif (defined('_ECRIRE_INC_VERSION')) {\n" . $contenu . "}\n?" . '>';
1469
+    // si un fichier existe deja on verifie que son contenu change avant de l'ecraser
1470
+    // si pas de modif on ne touche pas au fichier initial
1471
+    if (file_exists($nom)) {
1472
+        if (substr($nom, -4) == '.php') {
1473
+            $fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1474
+        }
1475
+        else {
1476
+            $fichier_tmp = $nom . '.tmp';
1477
+        }
1478
+        file_put_contents($fichier_tmp, $contenu);
1479
+        if (md5_file($nom) == md5_file($fichier_tmp)) {
1480
+            $GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1481
+            @unlink($fichier_tmp);
1482
+            return;
1483
+        }
1484
+        @unlink($fichier_tmp);
1485
+    }
1486
+    ecrire_fichier($nom, $contenu);
1487
+    $GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1488
+    spip_clear_opcode_cache(realpath($nom));
1489 1489
 }
Please login to merge, or discard this patch.
ecrire/inc/xml.php 1 patch
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -47,24 +47,24 @@  discard block
 block discarded – undo
47 47
  *     - false si l'arbre xml ne peut être créé ou est vide
48 48
  **/
49 49
 function spip_xml_load($fichier, $strict = true, $clean = true, $taille_max = 1_048_576, $datas = '', $profondeur = -1) {
50
-	$contenu = '';
51
-	if (tester_url_absolue($fichier)) {
52
-		include_spip('inc/distant');
53
-		$contenu = recuperer_url($fichier, ['taille_max' => $taille_max, 'datas' => $datas]);
54
-		$contenu = $contenu['page'] ?? '';
55
-	} else {
56
-		lire_fichier($fichier, $contenu);
57
-	}
58
-	$arbre = [];
59
-	if ($contenu) {
60
-		$arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
61
-	}
50
+    $contenu = '';
51
+    if (tester_url_absolue($fichier)) {
52
+        include_spip('inc/distant');
53
+        $contenu = recuperer_url($fichier, ['taille_max' => $taille_max, 'datas' => $datas]);
54
+        $contenu = $contenu['page'] ?? '';
55
+    } else {
56
+        lire_fichier($fichier, $contenu);
57
+    }
58
+    $arbre = [];
59
+    if ($contenu) {
60
+        $arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
61
+    }
62 62
 
63
-	return count($arbre) ? $arbre : false;
63
+    return count($arbre) ? $arbre : false;
64 64
 }
65 65
 
66 66
 if (!defined('_SPIP_XML_TAG_SPLIT')) {
67
-	define('_SPIP_XML_TAG_SPLIT', '{<([^:>][^>]*?)>}sS');
67
+    define('_SPIP_XML_TAG_SPLIT', '{<([^:>][^>]*?)>}sS');
68 68
 }
69 69
 
70 70
 /**
@@ -83,150 +83,150 @@  discard block
 block discarded – undo
83 83
  *     - false si l'arbre xml ne peut être créé ou est vide
84 84
  **/
85 85
 function spip_xml_parse(&$texte, $strict = true, $clean = true, $profondeur = -1) {
86
-	$out = [];
87
-	// enlever les commentaires
88
-	$charset = 'AUTO';
89
-	if ($clean === true) {
90
-		if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
91
-			$charset = $regs[2];
92
-		}
93
-		$texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
94
-		$texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
95
-		include_spip('inc/charsets');
96
-		$clean = $charset;
97
-		//$texte = importer_charset($texte,$charset);
98
-	}
99
-	if (is_string($clean)) {
100
-		$charset = $clean;
101
-	}
102
-	$txt = $texte;
86
+    $out = [];
87
+    // enlever les commentaires
88
+    $charset = 'AUTO';
89
+    if ($clean === true) {
90
+        if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
91
+            $charset = $regs[2];
92
+        }
93
+        $texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
94
+        $texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
95
+        include_spip('inc/charsets');
96
+        $clean = $charset;
97
+        //$texte = importer_charset($texte,$charset);
98
+    }
99
+    if (is_string($clean)) {
100
+        $charset = $clean;
101
+    }
102
+    $txt = $texte;
103 103
 
104
-	// tant qu'il y a des tags
105
-	$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
106
-	while ((is_countable($chars) ? count($chars) : 0) >= 2) {
107
-		// tag ouvrant
108
-		//$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
104
+    // tant qu'il y a des tags
105
+    $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
106
+    while ((is_countable($chars) ? count($chars) : 0) >= 2) {
107
+        // tag ouvrant
108
+        //$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
109 109
 
110
-		// $before doit etre vide ou des espaces uniquements!
111
-		$before = trim($chars[0]);
110
+        // $before doit etre vide ou des espaces uniquements!
111
+        $before = trim($chars[0]);
112 112
 
113
-		if (strlen($before) > 0) {
114
-			return importer_charset($texte, $charset);
115
-		}//$texte; // before non vide, donc on est dans du texte
113
+        if (strlen($before) > 0) {
114
+            return importer_charset($texte, $charset);
115
+        }//$texte; // before non vide, donc on est dans du texte
116 116
 
117
-		$tag = rtrim($chars[1]);
118
-		$txt = $chars[2];
117
+        $tag = rtrim($chars[1]);
118
+        $txt = $chars[2];
119 119
 
120
-		if (strncmp($tag, '![CDATA[', 8) == 0) {
121
-			return importer_charset($texte, $charset);
122
-		}//$texte;
123
-		if (substr($tag, -1) == '/') { // self closing tag
124
-			$tag = rtrim(substr($tag, 0, strlen($tag) - 1));
125
-			$out[$tag][] = '';
126
-		} else {
127
-			$closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
128
-			$closing_tag = reset($closing_tag);
129
-			// tag fermant
130
-			$ncclos = strlen("</$closing_tag>");
131
-			$p = strpos($txt, (string) "</$closing_tag>");
132
-			if ($p !== false and (strpos($txt, '<') < $p)) {
133
-				$nclose = 0;
134
-				$nopen = 0;
135
-				$d = 0;
136
-				while (
137
-					$p !== false
138
-					and ($morceau = substr($txt, $d, $p - $d))
139
-					and (($nopen += preg_match_all(
140
-						'{<' . preg_quote($closing_tag) . '(\s*>|\s[^>]*[^/>]>)}is',
141
-						$morceau,
142
-						$matches,
143
-						PREG_SET_ORDER
144
-					)) > $nclose)
145
-				) {
146
-					$nclose++;
147
-					$d = $p + $ncclos;
148
-					$p = strpos($txt, (string) "</$closing_tag>", $d);
149
-				}
150
-			}
151
-			if ($p === false) {
152
-				if ($strict) {
153
-					$out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
120
+        if (strncmp($tag, '![CDATA[', 8) == 0) {
121
+            return importer_charset($texte, $charset);
122
+        }//$texte;
123
+        if (substr($tag, -1) == '/') { // self closing tag
124
+            $tag = rtrim(substr($tag, 0, strlen($tag) - 1));
125
+            $out[$tag][] = '';
126
+        } else {
127
+            $closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
128
+            $closing_tag = reset($closing_tag);
129
+            // tag fermant
130
+            $ncclos = strlen("</$closing_tag>");
131
+            $p = strpos($txt, (string) "</$closing_tag>");
132
+            if ($p !== false and (strpos($txt, '<') < $p)) {
133
+                $nclose = 0;
134
+                $nopen = 0;
135
+                $d = 0;
136
+                while (
137
+                    $p !== false
138
+                    and ($morceau = substr($txt, $d, $p - $d))
139
+                    and (($nopen += preg_match_all(
140
+                        '{<' . preg_quote($closing_tag) . '(\s*>|\s[^>]*[^/>]>)}is',
141
+                        $morceau,
142
+                        $matches,
143
+                        PREG_SET_ORDER
144
+                    )) > $nclose)
145
+                ) {
146
+                    $nclose++;
147
+                    $d = $p + $ncclos;
148
+                    $p = strpos($txt, (string) "</$closing_tag>", $d);
149
+                }
150
+            }
151
+            if ($p === false) {
152
+                if ($strict) {
153
+                    $out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
154 154
 
155
-					return $out;
156
-				} else {
157
-					return importer_charset($texte, $charset);
158
-				}//$texte // un tag qui constitue du texte a reporter dans $before
159
-			}
160
-			$content = substr($txt, 0, $p);
161
-			$txt = substr($txt, $p + $ncclos);
162
-			if ($profondeur == 0 or !str_contains($content, '<')) { // eviter une recursion si pas utile
163
-			$out[$tag][] = importer_charset($content, $charset);
164
-			}//$content;
165
-			else {
166
-				$out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
167
-			}
168
-		}
169
-		$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
170
-	}
171
-	if (count($out) && (strlen(trim($txt)) == 0)) {
172
-		return $out;
173
-	} else {
174
-		return importer_charset($texte, $charset);
175
-	}//$texte;
155
+                    return $out;
156
+                } else {
157
+                    return importer_charset($texte, $charset);
158
+                }//$texte // un tag qui constitue du texte a reporter dans $before
159
+            }
160
+            $content = substr($txt, 0, $p);
161
+            $txt = substr($txt, $p + $ncclos);
162
+            if ($profondeur == 0 or !str_contains($content, '<')) { // eviter une recursion si pas utile
163
+            $out[$tag][] = importer_charset($content, $charset);
164
+            }//$content;
165
+            else {
166
+                $out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
167
+            }
168
+        }
169
+        $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
170
+    }
171
+    if (count($out) && (strlen(trim($txt)) == 0)) {
172
+        return $out;
173
+    } else {
174
+        return importer_charset($texte, $charset);
175
+    }//$texte;
176 176
 }
177 177
 
178 178
 function spip_xml_aplatit($arbre, $separateur = ' ') {
179
-	$s = '';
180
-	if (is_array($arbre)) {
181
-		foreach ($arbre as $tag => $feuille) {
182
-			if (is_array($feuille)) {
183
-				if ($tag !== intval($tag)) {
184
-					$f = spip_xml_aplatit($feuille, $separateur);
185
-					if (strlen($f)) {
186
-						$tagf = explode(' ', $tag);
187
-						$tagf = $tagf[0];
188
-						$s .= "<$tag>$f</$tagf>";
189
-					} else {
190
-						$s .= "<$tag />";
191
-					}
192
-				} else {
193
-					$s .= spip_xml_aplatit($feuille);
194
-				}
195
-				$s .= $separateur;
196
-			} else {
197
-				$s .= "$feuille$separateur";
198
-			}
199
-		}
200
-	}
179
+    $s = '';
180
+    if (is_array($arbre)) {
181
+        foreach ($arbre as $tag => $feuille) {
182
+            if (is_array($feuille)) {
183
+                if ($tag !== intval($tag)) {
184
+                    $f = spip_xml_aplatit($feuille, $separateur);
185
+                    if (strlen($f)) {
186
+                        $tagf = explode(' ', $tag);
187
+                        $tagf = $tagf[0];
188
+                        $s .= "<$tag>$f</$tagf>";
189
+                    } else {
190
+                        $s .= "<$tag />";
191
+                    }
192
+                } else {
193
+                    $s .= spip_xml_aplatit($feuille);
194
+                }
195
+                $s .= $separateur;
196
+            } else {
197
+                $s .= "$feuille$separateur";
198
+            }
199
+        }
200
+    }
201 201
 
202
-	return strlen($separateur) ? substr($s, 0, -strlen($separateur)) : $s;
202
+    return strlen($separateur) ? substr($s, 0, -strlen($separateur)) : $s;
203 203
 }
204 204
 
205 205
 function spip_xml_tagname($tag) {
206
-	if (preg_match(',^([a-z][\w:]*),i', $tag, $reg)) {
207
-		return $reg[1];
208
-	}
206
+    if (preg_match(',^([a-z][\w:]*),i', $tag, $reg)) {
207
+        return $reg[1];
208
+    }
209 209
 
210
-	return '';
210
+    return '';
211 211
 }
212 212
 
213 213
 function spip_xml_decompose_tag($tag) {
214
-	$tagname = spip_xml_tagname($tag);
215
-	$liste = [];
216
-	$tag = ltrim(strpbrk($tag, " \n\t"));
217
-	$p = strpos($tag, '=');
218
-	while ($p !== false) {
219
-		$attr = trim(substr($tag, 0, $p));
220
-		$tag = ltrim(substr($tag, $p + 1));
221
-		$quote = $tag[0];
222
-		$p = strpos($tag, $quote, 1);
223
-		$cont = substr($tag, 1, $p - 1);
224
-		$liste[$attr] = $cont;
225
-		$tag = substr($tag, $p + 1);
226
-		$p = strpos($tag, '=');
227
-	}
214
+    $tagname = spip_xml_tagname($tag);
215
+    $liste = [];
216
+    $tag = ltrim(strpbrk($tag, " \n\t"));
217
+    $p = strpos($tag, '=');
218
+    while ($p !== false) {
219
+        $attr = trim(substr($tag, 0, $p));
220
+        $tag = ltrim(substr($tag, $p + 1));
221
+        $quote = $tag[0];
222
+        $p = strpos($tag, $quote, 1);
223
+        $cont = substr($tag, 1, $p - 1);
224
+        $liste[$attr] = $cont;
225
+        $tag = substr($tag, $p + 1);
226
+        $p = strpos($tag, '=');
227
+    }
228 228
 
229
-	return [$tagname, $liste];
229
+    return [$tagname, $liste];
230 230
 }
231 231
 
232 232
 /**
@@ -249,21 +249,21 @@  discard block
 block discarded – undo
249 249
  *     false si aucun élément ne valide l'expression régulière, true sinon.
250 250
  **/
251 251
 function spip_xml_match_nodes($regexp, &$arbre, &$matches, $init = true) {
252
-	if ($init) {
253
-		$matches = [];
254
-	}
255
-	if (is_array($arbre) && count($arbre)) {
256
-		foreach (array_keys($arbre) as $tag) {
257
-			if (preg_match($regexp, $tag)) {
258
-				$matches[$tag] = &$arbre[$tag];
259
-			}
260
-			if (is_array($arbre[$tag])) {
261
-				foreach (array_keys($arbre[$tag]) as $occurences) {
262
-					spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
263
-				}
264
-			}
265
-		}
266
-	}
252
+    if ($init) {
253
+        $matches = [];
254
+    }
255
+    if (is_array($arbre) && count($arbre)) {
256
+        foreach (array_keys($arbre) as $tag) {
257
+            if (preg_match($regexp, $tag)) {
258
+                $matches[$tag] = &$arbre[$tag];
259
+            }
260
+            if (is_array($arbre[$tag])) {
261
+                foreach (array_keys($arbre[$tag]) as $occurences) {
262
+                    spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
263
+                }
264
+            }
265
+        }
266
+    }
267 267
 
268
-	return (is_countable($matches) ? count($matches) : 0);
268
+    return (is_countable($matches) ? count($matches) : 0);
269 269
 }
Please login to merge, or discard this patch.
ecrire/inc/distant.php 1 patch
Indentation   +1084 added lines, -1084 removed lines patch added patch discarded remove patch
@@ -18,32 +18,32 @@  discard block
 block discarded – undo
18 18
  * @package SPIP\Core\Distant
19 19
  **/
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
25
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
25
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
26 26
 }
27 27
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
28
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
29 29
 }
30 30
 if (!defined('_INC_DISTANT_USER_AGENT')) {
31
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
32 32
 }
33 33
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
34
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
34
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
35 35
 }
36 36
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
37
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
38 38
 }
39 39
 
40 40
 define('_REGEXP_COPIE_LOCALE', ',' 	.
41
-	preg_replace(
42
-		'@^https?:@',
43
-		'https?:',
44
-		($GLOBALS['meta']['adresse_site'] ?? '')
45
-	)
46
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
41
+    preg_replace(
42
+        '@^https?:@',
43
+        'https?:',
44
+        ($GLOBALS['meta']['adresse_site'] ?? '')
45
+    )
46
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
47 47
 
48 48
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
49 49
 
@@ -72,107 +72,107 @@  discard block
 block discarded – undo
72 72
  */
73 73
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
74 74
 
75
-	// si c'est la protection de soi-meme, retourner le path
76
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
77
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
78
-
79
-		return @file_exists($source) ? $source : false;
80
-	}
81
-
82
-	if (is_null($local)) {
83
-		$local = fichier_copie_locale($source);
84
-	} else {
85
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
86
-			$local = substr($local, strlen(_DIR_RACINE));
87
-		}
88
-	}
89
-
90
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
91
-	// par exemple un fichier qui ne figure pas dans nos documents ;
92
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
93
-	if (!$local) {
94
-		return false;
95
-	}
96
-
97
-	$localrac = _DIR_RACINE . $local;
98
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
99
-
100
-	// test d'existence du fichier
101
-	if ($mode === 'test') {
102
-		return $t ? $local : '';
103
-	}
104
-
105
-	// sinon voir si on doit/peut le telecharger
106
-	if ($local === $source or !tester_url_absolue($source)) {
107
-		return $t ? $local : '';
108
-	}
109
-
110
-	if ($mode === 'modif' or !$t) {
111
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
112
-		// et des eventuelles recuperations concurantes
113
-		include_spip('inc/acces');
114
-		if (!$taille_max) {
115
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
116
-		}
117
-		$localrac_tmp = $localrac . '.tmp';
118
-		$res = recuperer_url(
119
-			$source,
120
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
121
-		);
122
-
123
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
124
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
125
-			@unlink($localrac_tmp);
126
-		}
127
-		else {
128
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
129
-		}
130
-		if (!$res or !$res['length']) {
131
-			// si $t c'est sans doute juste un not-modified-since
132
-			return $t ? $local : false;
133
-		}
134
-
135
-		// si option valider url, verifions que l'URL finale est acceptable
136
-		if (
137
-			$callback_valider_url
138
-			and is_callable($callback_valider_url)
139
-			and !$callback_valider_url($res['url'])
140
-		) {
141
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
142
-			@unlink($localrac_tmp);
143
-			return $t ? $local : false;
144
-		}
145
-
146
-		// on peut renommer le fichier tmp
147
-		@rename($localrac_tmp, $localrac);
148
-
149
-		// si on retrouve l'extension
150
-		if (
151
-			!empty($res['headers'])
152
-			and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
153
-		) {
154
-			if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
155
-				$sanitizer($localrac);
156
-			}
157
-		}
158
-
159
-		// pour une eventuelle indexation
160
-		pipeline(
161
-			'post_edition',
162
-			[
163
-				'args' => [
164
-					'operation' => 'copie_locale',
165
-					'source' => $source,
166
-					'fichier' => $local,
167
-					'http_res' => $res['length'],
168
-					'url' => $res['url'],
169
-				],
170
-				'data' => null
171
-			]
172
-		);
173
-	}
174
-
175
-	return $local;
75
+    // si c'est la protection de soi-meme, retourner le path
76
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
77
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
78
+
79
+        return @file_exists($source) ? $source : false;
80
+    }
81
+
82
+    if (is_null($local)) {
83
+        $local = fichier_copie_locale($source);
84
+    } else {
85
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
86
+            $local = substr($local, strlen(_DIR_RACINE));
87
+        }
88
+    }
89
+
90
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
91
+    // par exemple un fichier qui ne figure pas dans nos documents ;
92
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
93
+    if (!$local) {
94
+        return false;
95
+    }
96
+
97
+    $localrac = _DIR_RACINE . $local;
98
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
99
+
100
+    // test d'existence du fichier
101
+    if ($mode === 'test') {
102
+        return $t ? $local : '';
103
+    }
104
+
105
+    // sinon voir si on doit/peut le telecharger
106
+    if ($local === $source or !tester_url_absolue($source)) {
107
+        return $t ? $local : '';
108
+    }
109
+
110
+    if ($mode === 'modif' or !$t) {
111
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
112
+        // et des eventuelles recuperations concurantes
113
+        include_spip('inc/acces');
114
+        if (!$taille_max) {
115
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
116
+        }
117
+        $localrac_tmp = $localrac . '.tmp';
118
+        $res = recuperer_url(
119
+            $source,
120
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
121
+        );
122
+
123
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
124
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
125
+            @unlink($localrac_tmp);
126
+        }
127
+        else {
128
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
129
+        }
130
+        if (!$res or !$res['length']) {
131
+            // si $t c'est sans doute juste un not-modified-since
132
+            return $t ? $local : false;
133
+        }
134
+
135
+        // si option valider url, verifions que l'URL finale est acceptable
136
+        if (
137
+            $callback_valider_url
138
+            and is_callable($callback_valider_url)
139
+            and !$callback_valider_url($res['url'])
140
+        ) {
141
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
142
+            @unlink($localrac_tmp);
143
+            return $t ? $local : false;
144
+        }
145
+
146
+        // on peut renommer le fichier tmp
147
+        @rename($localrac_tmp, $localrac);
148
+
149
+        // si on retrouve l'extension
150
+        if (
151
+            !empty($res['headers'])
152
+            and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
153
+        ) {
154
+            if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
155
+                $sanitizer($localrac);
156
+            }
157
+        }
158
+
159
+        // pour une eventuelle indexation
160
+        pipeline(
161
+            'post_edition',
162
+            [
163
+                'args' => [
164
+                    'operation' => 'copie_locale',
165
+                    'source' => $source,
166
+                    'fichier' => $local,
167
+                    'http_res' => $res['length'],
168
+                    'url' => $res['url'],
169
+                ],
170
+                'data' => null
171
+            ]
172
+        );
173
+    }
174
+
175
+    return $local;
176 176
 }
177 177
 
178 178
 /**
@@ -187,99 +187,99 @@  discard block
 block discarded – undo
187 187
  *   url ou false en cas d'echec
188 188
  */
189 189
 function valider_url_distante($url, $known_hosts = []) {
190
-	if (!function_exists('protocole_verifier')) {
191
-		include_spip('inc/filtres_mini');
192
-	}
193
-
194
-	if (!protocole_verifier($url, ['http', 'https'])) {
195
-		return false;
196
-	}
197
-
198
-	$parsed_url = parse_url($url);
199
-	if (!$parsed_url or empty($parsed_url['host'])) {
200
-		return false;
201
-	}
202
-
203
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
204
-		return false;
205
-	}
206
-
207
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
208
-		return false;
209
-	}
210
-
211
-	if (!is_array($known_hosts)) {
212
-		$known_hosts = [$known_hosts];
213
-	}
214
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
215
-	$known_hosts[] = url_de_base();
216
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
217
-
218
-	$is_known_host = false;
219
-	foreach ($known_hosts as $known_host) {
220
-		$parse_known = parse_url($known_host);
221
-		if (
222
-			$parse_known
223
-			and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
224
-		) {
225
-			$is_known_host = true;
226
-			break;
227
-		}
228
-	}
229
-
230
-	if (!$is_known_host) {
231
-		$host = trim($parsed_url['host'], '.');
232
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
233
-			$ip = gethostbyname($host);
234
-			if ($ip === $host) {
235
-				// Error condition for gethostbyname()
236
-				$ip = false;
237
-			}
238
-			if ($records = dns_get_record($host)) {
239
-				foreach ($records as $record) {
240
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
241
-					// se fasse sur la meme IP
242
-					if ($record['ttl'] < 10) {
243
-						$ip = false;
244
-						break;
245
-					}
246
-				}
247
-			}
248
-			else {
249
-				$ip = false;
250
-			}
251
-		}
252
-		if ($ip) {
253
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
254
-				return false;
255
-			}
256
-		}
257
-	}
258
-
259
-	if (empty($parsed_url['port'])) {
260
-		return $url;
261
-	}
262
-
263
-	$port = $parsed_url['port'];
264
-	if ($port === 80  or $port === 443  or $port === 8080) {
265
-		return $url;
266
-	}
267
-
268
-	if ($is_known_host) {
269
-		foreach ($known_hosts as $known_host) {
270
-			$parse_known = parse_url($known_host);
271
-			if (
272
-				$parse_known
273
-				and !empty($parse_known['port'])
274
-				and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
275
-				and $parse_known['port'] == $port
276
-			) {
277
-				return $url;
278
-			}
279
-		}
280
-	}
281
-
282
-	return false;
190
+    if (!function_exists('protocole_verifier')) {
191
+        include_spip('inc/filtres_mini');
192
+    }
193
+
194
+    if (!protocole_verifier($url, ['http', 'https'])) {
195
+        return false;
196
+    }
197
+
198
+    $parsed_url = parse_url($url);
199
+    if (!$parsed_url or empty($parsed_url['host'])) {
200
+        return false;
201
+    }
202
+
203
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
204
+        return false;
205
+    }
206
+
207
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
208
+        return false;
209
+    }
210
+
211
+    if (!is_array($known_hosts)) {
212
+        $known_hosts = [$known_hosts];
213
+    }
214
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
215
+    $known_hosts[] = url_de_base();
216
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
217
+
218
+    $is_known_host = false;
219
+    foreach ($known_hosts as $known_host) {
220
+        $parse_known = parse_url($known_host);
221
+        if (
222
+            $parse_known
223
+            and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
224
+        ) {
225
+            $is_known_host = true;
226
+            break;
227
+        }
228
+    }
229
+
230
+    if (!$is_known_host) {
231
+        $host = trim($parsed_url['host'], '.');
232
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
233
+            $ip = gethostbyname($host);
234
+            if ($ip === $host) {
235
+                // Error condition for gethostbyname()
236
+                $ip = false;
237
+            }
238
+            if ($records = dns_get_record($host)) {
239
+                foreach ($records as $record) {
240
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
241
+                    // se fasse sur la meme IP
242
+                    if ($record['ttl'] < 10) {
243
+                        $ip = false;
244
+                        break;
245
+                    }
246
+                }
247
+            }
248
+            else {
249
+                $ip = false;
250
+            }
251
+        }
252
+        if ($ip) {
253
+            if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
254
+                return false;
255
+            }
256
+        }
257
+    }
258
+
259
+    if (empty($parsed_url['port'])) {
260
+        return $url;
261
+    }
262
+
263
+    $port = $parsed_url['port'];
264
+    if ($port === 80  or $port === 443  or $port === 8080) {
265
+        return $url;
266
+    }
267
+
268
+    if ($is_known_host) {
269
+        foreach ($known_hosts as $known_host) {
270
+            $parse_known = parse_url($known_host);
271
+            if (
272
+                $parse_known
273
+                and !empty($parse_known['port'])
274
+                and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
275
+                and $parse_known['port'] == $port
276
+            ) {
277
+                return $url;
278
+            }
279
+        }
280
+    }
281
+
282
+    return false;
283 283
 }
284 284
 
285 285
 /**
@@ -299,86 +299,86 @@  discard block
 block discarded – undo
299 299
  */
300 300
 function prepare_donnees_post($donnees, $boundary = '') {
301 301
 
302
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
303
-	// pour un appel soap par exemple
304
-	// l'entete est separe des donnees par un double retour a la ligne
305
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
306
-	if (is_string($donnees) && strlen($donnees)) {
307
-		$entete = '';
308
-		// on repasse tous les \r\n et \r en simples \n
309
-		$donnees = str_replace("\r\n", "\n", $donnees);
310
-		$donnees = str_replace("\r", "\n", $donnees);
311
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
312
-		$p = strpos($donnees, "\n\n");
313
-		if ($p !== false) {
314
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
315
-			$donnees = substr($donnees, $p + 2);
316
-		}
317
-		$chaine = str_replace("\n", "\r\n", $donnees);
318
-	} else {
319
-		/* boundary automatique */
320
-		// Si on a plus de 500 octects de donnees, on "boundarise"
321
-		if ($boundary === '') {
322
-			$taille = 0;
323
-			foreach ($donnees as $cle => $valeur) {
324
-				if (is_array($valeur)) {
325
-					foreach ($valeur as $val2) {
326
-						$taille += strlen($val2);
327
-					}
328
-				} else {
329
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
330
-					$taille += strlen($valeur);
331
-				}
332
-			}
333
-			if ($taille > 500) {
334
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
335
-			}
336
-		}
337
-
338
-		if (is_string($boundary) and strlen($boundary)) {
339
-			// fabrique une chaine HTTP pour un POST avec boundary
340
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
341
-			$chaine = '';
342
-			if (is_array($donnees)) {
343
-				foreach ($donnees as $cle => $valeur) {
344
-					if (is_array($valeur)) {
345
-						foreach ($valeur as $val2) {
346
-							$chaine .= "\r\n--$boundary\r\n";
347
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
348
-							$chaine .= "\r\n";
349
-							$chaine .= $val2;
350
-						}
351
-					} else {
352
-						$chaine .= "\r\n--$boundary\r\n";
353
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
354
-						$chaine .= "\r\n";
355
-						$chaine .= $valeur;
356
-					}
357
-				}
358
-				$chaine .= "\r\n--$boundary\r\n";
359
-			}
360
-		} else {
361
-			// fabrique une chaine HTTP simple pour un POST
362
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
363
-			$chaine = [];
364
-			if (is_array($donnees)) {
365
-				foreach ($donnees as $cle => $valeur) {
366
-					if (is_array($valeur)) {
367
-						foreach ($valeur as $val2) {
368
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
369
-						}
370
-					} else {
371
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
372
-					}
373
-				}
374
-				$chaine = implode('&', $chaine);
375
-			} else {
376
-				$chaine = $donnees;
377
-			}
378
-		}
379
-	}
380
-
381
-	return [$entete, $chaine];
302
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
303
+    // pour un appel soap par exemple
304
+    // l'entete est separe des donnees par un double retour a la ligne
305
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
306
+    if (is_string($donnees) && strlen($donnees)) {
307
+        $entete = '';
308
+        // on repasse tous les \r\n et \r en simples \n
309
+        $donnees = str_replace("\r\n", "\n", $donnees);
310
+        $donnees = str_replace("\r", "\n", $donnees);
311
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
312
+        $p = strpos($donnees, "\n\n");
313
+        if ($p !== false) {
314
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
315
+            $donnees = substr($donnees, $p + 2);
316
+        }
317
+        $chaine = str_replace("\n", "\r\n", $donnees);
318
+    } else {
319
+        /* boundary automatique */
320
+        // Si on a plus de 500 octects de donnees, on "boundarise"
321
+        if ($boundary === '') {
322
+            $taille = 0;
323
+            foreach ($donnees as $cle => $valeur) {
324
+                if (is_array($valeur)) {
325
+                    foreach ($valeur as $val2) {
326
+                        $taille += strlen($val2);
327
+                    }
328
+                } else {
329
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
330
+                    $taille += strlen($valeur);
331
+                }
332
+            }
333
+            if ($taille > 500) {
334
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
335
+            }
336
+        }
337
+
338
+        if (is_string($boundary) and strlen($boundary)) {
339
+            // fabrique une chaine HTTP pour un POST avec boundary
340
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
341
+            $chaine = '';
342
+            if (is_array($donnees)) {
343
+                foreach ($donnees as $cle => $valeur) {
344
+                    if (is_array($valeur)) {
345
+                        foreach ($valeur as $val2) {
346
+                            $chaine .= "\r\n--$boundary\r\n";
347
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
348
+                            $chaine .= "\r\n";
349
+                            $chaine .= $val2;
350
+                        }
351
+                    } else {
352
+                        $chaine .= "\r\n--$boundary\r\n";
353
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
354
+                        $chaine .= "\r\n";
355
+                        $chaine .= $valeur;
356
+                    }
357
+                }
358
+                $chaine .= "\r\n--$boundary\r\n";
359
+            }
360
+        } else {
361
+            // fabrique une chaine HTTP simple pour un POST
362
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
363
+            $chaine = [];
364
+            if (is_array($donnees)) {
365
+                foreach ($donnees as $cle => $valeur) {
366
+                    if (is_array($valeur)) {
367
+                        foreach ($valeur as $val2) {
368
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
369
+                        }
370
+                    } else {
371
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
372
+                    }
373
+                }
374
+                $chaine = implode('&', $chaine);
375
+            } else {
376
+                $chaine = $donnees;
377
+            }
378
+        }
379
+    }
380
+
381
+    return [$entete, $chaine];
382 382
 }
383 383
 
384 384
 /**
@@ -389,19 +389,19 @@  discard block
 block discarded – undo
389 389
  */
390 390
 function url_to_ascii($url_idn) {
391 391
 
392
-	if ($parts = parse_url($url_idn)) {
393
-		$host = $parts['host'];
394
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
395
-			$converter = new ToIdn();
396
-			$host_ascii = $converter->convert($host);
397
-			$url_idn = explode($host, $url_idn, 2);
398
-			$url_idn = implode($host_ascii, $url_idn);
399
-		}
400
-		// et on urlencode les char utf si besoin dans le path
401
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
402
-	}
403
-
404
-	return $url_idn;
392
+    if ($parts = parse_url($url_idn)) {
393
+        $host = $parts['host'];
394
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
395
+            $converter = new ToIdn();
396
+            $host_ascii = $converter->convert($host);
397
+            $url_idn = explode($host, $url_idn, 2);
398
+            $url_idn = implode($host_ascii, $url_idn);
399
+        }
400
+        // et on urlencode les char utf si besoin dans le path
401
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
402
+    }
403
+
404
+    return $url_idn;
405 405
 }
406 406
 
407 407
 /**
@@ -442,209 +442,209 @@  discard block
 block discarded – undo
442 442
  *     string file : nom du fichier si enregistre dans un fichier
443 443
  */
444 444
 function recuperer_url($url, $options = []) {
445
-	// Conserve la mémoire de la méthode fournit éventuellement
446
-	$methode_demandee = $options['methode'] ?? '';
447
-	$default = [
448
-		'transcoder' => false,
449
-		'methode' => 'GET',
450
-		'taille_max' => null,
451
-		'headers' => [],
452
-		'datas' => '',
453
-		'boundary' => '',
454
-		'refuser_gz' => false,
455
-		'if_modified_since' => '',
456
-		'uri_referer' => '',
457
-		'file' => '',
458
-		'follow_location' => 10,
459
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
460
-	];
461
-	$options = array_merge($default, $options);
462
-	// copier directement dans un fichier ?
463
-	$copy = $options['file'];
464
-
465
-	if ($options['methode'] == 'HEAD') {
466
-		$options['taille_max'] = 0;
467
-	}
468
-	if (is_null($options['taille_max'])) {
469
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
470
-	}
471
-
472
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
473
-
474
-	// Ajout des en-têtes spécifiques si besoin
475
-	$formatted_data = '';
476
-	if (!empty($options['headers'])) {
477
-		foreach ($options['headers'] as $champ => $valeur) {
478
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
479
-		}
480
-	}
481
-
482
-	if (!empty($options['datas'])) {
483
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
484
-		$head .= $formatted_data;
485
-		if (stripos($head, 'Content-Length:') === false) {
486
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
487
-		}
488
-		$formatted_data = $head . "\r\n" . $postdata;
489
-		if (
490
-			strlen($postdata)
491
-			and !$methode_demandee
492
-		) {
493
-			$options['methode'] = 'POST';
494
-		}
495
-	} elseif ($formatted_data) {
496
-		$formatted_data .= "\r\n";
497
-	}
498
-
499
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
500
-	$url = preg_replace(',^feed://,i', 'http://', $url);
501
-	if (!tester_url_absolue($url)) {
502
-		$url = 'http://' . $url;
503
-	} elseif (strncmp($url, '//', 2) == 0) {
504
-		$url = 'http:' . $url;
505
-	}
506
-
507
-	$url = url_to_ascii($url);
508
-
509
-	$result = [
510
-		'status' => 0,
511
-		'headers' => '',
512
-		'page' => '',
513
-		'length' => 0,
514
-		'last_modified' => '',
515
-		'location' => '',
516
-		'url' => $url
517
-	];
518
-
519
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
520
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
521
-
522
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
523
-	[$handle, $fopen] = init_http(
524
-		$options['methode'],
525
-		$url,
526
-		$refuser_gz,
527
-		$options['uri_referer'],
528
-		$formatted_data,
529
-		$options['version_http'],
530
-		$options['if_modified_since']
531
-	);
532
-	if (!$handle) {
533
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
534
-
535
-		return false;
536
-	}
537
-
538
-	// Sauf en fopen, envoyer le flux d'entree
539
-	// et recuperer les en-tetes de reponses
540
-	if (!$fopen) {
541
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
542
-		if (!$res) {
543
-			fclose($handle);
544
-			$t = @parse_url($url);
545
-			$host = $t['host'];
546
-			// Chinoisierie inexplicable pour contrer
547
-			// les actions liberticides de l'empire du milieu
548
-			if (
549
-				!need_proxy($host)
550
-				and $res = @file_get_contents($url)
551
-			) {
552
-				$result['length'] = strlen($res);
553
-				if ($copy) {
554
-					ecrire_fichier($copy, $res);
555
-					$result['file'] = $copy;
556
-				} else {
557
-					$result['page'] = $res;
558
-				}
559
-				$res = [
560
-					'status' => 200,
561
-				];
562
-			} else {
563
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
564
-				return false;
565
-			}
566
-		} elseif ($res['location'] and $options['follow_location']) {
567
-			$options['follow_location']--;
568
-			fclose($handle);
569
-			include_spip('inc/filtres');
570
-			$url = suivre_lien($url, $res['location']);
571
-
572
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
573
-			if ($options['methode'] !== 'GET') {
574
-				if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
575
-					$options['methode'] = 'GET';
576
-					$options['datas'] = '';
577
-				}
578
-			}
579
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
580
-
581
-			return recuperer_url($url, $options);
582
-		} elseif ($res['status'] !== 200) {
583
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
584
-		}
585
-		$result['status'] = $res['status'];
586
-		if (isset($res['headers'])) {
587
-			$result['headers'] = $res['headers'];
588
-		}
589
-		if (isset($res['last_modified'])) {
590
-			$result['last_modified'] = $res['last_modified'];
591
-		}
592
-		if (isset($res['location'])) {
593
-			$result['location'] = $res['location'];
594
-		}
595
-	}
596
-
597
-	// on ne veut que les entetes
598
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
600
-		return $result;
601
-	}
602
-
603
-
604
-	// s'il faut deballer, le faire via un fichier temporaire
605
-	// sinon la memoire explose pour les gros flux
606
-
607
-	$gz = false;
608
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
609
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
-	}
611
-
612
-	// si on a pas deja recuperer le contenu par une methode detournee
613
-	if (!$result['length']) {
614
-		$res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
615
-		fclose($handle);
616
-		if ($copy) {
617
-			$result['length'] = $res;
618
-			$result['file'] = $copy;
619
-		} elseif ($res) {
620
-			$result['page'] = &$res;
621
-			$result['length'] = strlen($result['page']);
622
-		}
623
-		if (!$result['status']) {
624
-			$result['status'] = 200; // on a reussi, donc !
625
-		}
626
-	}
627
-	if (!$result['page']) {
628
-		return $result;
629
-	}
630
-
631
-	// Decompresser au besoin
632
-	if ($gz) {
633
-		$result['page'] = implode('', gzfile($gz));
634
-		supprimer_fichier($gz);
635
-	}
636
-
637
-	// Faut-il l'importer dans notre charset local ?
638
-	if ($options['transcoder']) {
639
-		include_spip('inc/charsets');
640
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
641
-	}
642
-
643
-	$trace = json_decode(json_encode($result), true);
644
-	$trace['page'] = '...';
645
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
646
-
647
-	return $result;
445
+    // Conserve la mémoire de la méthode fournit éventuellement
446
+    $methode_demandee = $options['methode'] ?? '';
447
+    $default = [
448
+        'transcoder' => false,
449
+        'methode' => 'GET',
450
+        'taille_max' => null,
451
+        'headers' => [],
452
+        'datas' => '',
453
+        'boundary' => '',
454
+        'refuser_gz' => false,
455
+        'if_modified_since' => '',
456
+        'uri_referer' => '',
457
+        'file' => '',
458
+        'follow_location' => 10,
459
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
460
+    ];
461
+    $options = array_merge($default, $options);
462
+    // copier directement dans un fichier ?
463
+    $copy = $options['file'];
464
+
465
+    if ($options['methode'] == 'HEAD') {
466
+        $options['taille_max'] = 0;
467
+    }
468
+    if (is_null($options['taille_max'])) {
469
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
470
+    }
471
+
472
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
473
+
474
+    // Ajout des en-têtes spécifiques si besoin
475
+    $formatted_data = '';
476
+    if (!empty($options['headers'])) {
477
+        foreach ($options['headers'] as $champ => $valeur) {
478
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
479
+        }
480
+    }
481
+
482
+    if (!empty($options['datas'])) {
483
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
484
+        $head .= $formatted_data;
485
+        if (stripos($head, 'Content-Length:') === false) {
486
+            $head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
487
+        }
488
+        $formatted_data = $head . "\r\n" . $postdata;
489
+        if (
490
+            strlen($postdata)
491
+            and !$methode_demandee
492
+        ) {
493
+            $options['methode'] = 'POST';
494
+        }
495
+    } elseif ($formatted_data) {
496
+        $formatted_data .= "\r\n";
497
+    }
498
+
499
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
500
+    $url = preg_replace(',^feed://,i', 'http://', $url);
501
+    if (!tester_url_absolue($url)) {
502
+        $url = 'http://' . $url;
503
+    } elseif (strncmp($url, '//', 2) == 0) {
504
+        $url = 'http:' . $url;
505
+    }
506
+
507
+    $url = url_to_ascii($url);
508
+
509
+    $result = [
510
+        'status' => 0,
511
+        'headers' => '',
512
+        'page' => '',
513
+        'length' => 0,
514
+        'last_modified' => '',
515
+        'location' => '',
516
+        'url' => $url
517
+    ];
518
+
519
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
520
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
521
+
522
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
523
+    [$handle, $fopen] = init_http(
524
+        $options['methode'],
525
+        $url,
526
+        $refuser_gz,
527
+        $options['uri_referer'],
528
+        $formatted_data,
529
+        $options['version_http'],
530
+        $options['if_modified_since']
531
+    );
532
+    if (!$handle) {
533
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
534
+
535
+        return false;
536
+    }
537
+
538
+    // Sauf en fopen, envoyer le flux d'entree
539
+    // et recuperer les en-tetes de reponses
540
+    if (!$fopen) {
541
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
542
+        if (!$res) {
543
+            fclose($handle);
544
+            $t = @parse_url($url);
545
+            $host = $t['host'];
546
+            // Chinoisierie inexplicable pour contrer
547
+            // les actions liberticides de l'empire du milieu
548
+            if (
549
+                !need_proxy($host)
550
+                and $res = @file_get_contents($url)
551
+            ) {
552
+                $result['length'] = strlen($res);
553
+                if ($copy) {
554
+                    ecrire_fichier($copy, $res);
555
+                    $result['file'] = $copy;
556
+                } else {
557
+                    $result['page'] = $res;
558
+                }
559
+                $res = [
560
+                    'status' => 200,
561
+                ];
562
+            } else {
563
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
564
+                return false;
565
+            }
566
+        } elseif ($res['location'] and $options['follow_location']) {
567
+            $options['follow_location']--;
568
+            fclose($handle);
569
+            include_spip('inc/filtres');
570
+            $url = suivre_lien($url, $res['location']);
571
+
572
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
573
+            if ($options['methode'] !== 'GET') {
574
+                if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
575
+                    $options['methode'] = 'GET';
576
+                    $options['datas'] = '';
577
+                }
578
+            }
579
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
580
+
581
+            return recuperer_url($url, $options);
582
+        } elseif ($res['status'] !== 200) {
583
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
584
+        }
585
+        $result['status'] = $res['status'];
586
+        if (isset($res['headers'])) {
587
+            $result['headers'] = $res['headers'];
588
+        }
589
+        if (isset($res['last_modified'])) {
590
+            $result['last_modified'] = $res['last_modified'];
591
+        }
592
+        if (isset($res['location'])) {
593
+            $result['location'] = $res['location'];
594
+        }
595
+    }
596
+
597
+    // on ne veut que les entetes
598
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
599
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
600
+        return $result;
601
+    }
602
+
603
+
604
+    // s'il faut deballer, le faire via un fichier temporaire
605
+    // sinon la memoire explose pour les gros flux
606
+
607
+    $gz = false;
608
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
609
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
+    }
611
+
612
+    // si on a pas deja recuperer le contenu par une methode detournee
613
+    if (!$result['length']) {
614
+        $res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
615
+        fclose($handle);
616
+        if ($copy) {
617
+            $result['length'] = $res;
618
+            $result['file'] = $copy;
619
+        } elseif ($res) {
620
+            $result['page'] = &$res;
621
+            $result['length'] = strlen($result['page']);
622
+        }
623
+        if (!$result['status']) {
624
+            $result['status'] = 200; // on a reussi, donc !
625
+        }
626
+    }
627
+    if (!$result['page']) {
628
+        return $result;
629
+    }
630
+
631
+    // Decompresser au besoin
632
+    if ($gz) {
633
+        $result['page'] = implode('', gzfile($gz));
634
+        supprimer_fichier($gz);
635
+    }
636
+
637
+    // Faut-il l'importer dans notre charset local ?
638
+    if ($options['transcoder']) {
639
+        include_spip('inc/charsets');
640
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
641
+    }
642
+
643
+    $trace = json_decode(json_encode($result), true);
644
+    $trace['page'] = '...';
645
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
646
+
647
+    return $result;
648 648
 }
649 649
 
650 650
 /**
@@ -660,73 +660,73 @@  discard block
 block discarded – undo
660 660
  * @return array|bool|mixed
661 661
  */
662 662
 function recuperer_url_cache($url, $options = []) {
663
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
664
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
665
-	}
666
-	$default = [
667
-		'transcoder' => false,
668
-		'methode' => 'GET',
669
-		'taille_max' => null,
670
-		'datas' => '',
671
-		'boundary' => '',
672
-		'refuser_gz' => false,
673
-		'if_modified_since' => '',
674
-		'uri_referer' => '',
675
-		'file' => '',
676
-		'follow_location' => 10,
677
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
678
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
679
-	];
680
-	$options = array_merge($default, $options);
681
-
682
-	// cas ou il n'est pas possible de cacher
683
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
684
-		return recuperer_url($url, $options);
685
-	}
686
-
687
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
688
-	static $errors = [];
689
-	if (isset($errors[$url])) {
690
-		return $errors[$url];
691
-	}
692
-
693
-	$sig = $options;
694
-	unset($sig['if_modified_since']);
695
-	unset($sig['delai_cache']);
696
-	$sig['url'] = $url;
697
-
698
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
699
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
700
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
701
-	$cache = "$sub$cache";
702
-
703
-	$res = false;
704
-	$is_cached = file_exists($cache);
705
-	if (
706
-		$is_cached
707
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
708
-	) {
709
-		lire_fichier($cache, $res);
710
-		if ($res = unserialize($res)) {
711
-			// mettre le last_modified et le status=304 ?
712
-		}
713
-	}
714
-	if (!$res) {
715
-		$res = recuperer_url($url, $options);
716
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
717
-		if (!$res) {
718
-			if ($is_cached) {
719
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
720
-				lire_fichier($cache, $res);
721
-				$res = unserialize($res);
722
-			}
723
-
724
-			return $errors[$url] = $res;
725
-		}
726
-		ecrire_fichier($cache, serialize($res));
727
-	}
728
-
729
-	return $res;
663
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
664
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
665
+    }
666
+    $default = [
667
+        'transcoder' => false,
668
+        'methode' => 'GET',
669
+        'taille_max' => null,
670
+        'datas' => '',
671
+        'boundary' => '',
672
+        'refuser_gz' => false,
673
+        'if_modified_since' => '',
674
+        'uri_referer' => '',
675
+        'file' => '',
676
+        'follow_location' => 10,
677
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
678
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
679
+    ];
680
+    $options = array_merge($default, $options);
681
+
682
+    // cas ou il n'est pas possible de cacher
683
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
684
+        return recuperer_url($url, $options);
685
+    }
686
+
687
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
688
+    static $errors = [];
689
+    if (isset($errors[$url])) {
690
+        return $errors[$url];
691
+    }
692
+
693
+    $sig = $options;
694
+    unset($sig['if_modified_since']);
695
+    unset($sig['delai_cache']);
696
+    $sig['url'] = $url;
697
+
698
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
699
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
700
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
701
+    $cache = "$sub$cache";
702
+
703
+    $res = false;
704
+    $is_cached = file_exists($cache);
705
+    if (
706
+        $is_cached
707
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
708
+    ) {
709
+        lire_fichier($cache, $res);
710
+        if ($res = unserialize($res)) {
711
+            // mettre le last_modified et le status=304 ?
712
+        }
713
+    }
714
+    if (!$res) {
715
+        $res = recuperer_url($url, $options);
716
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
717
+        if (!$res) {
718
+            if ($is_cached) {
719
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
720
+                lire_fichier($cache, $res);
721
+                $res = unserialize($res);
722
+            }
723
+
724
+            return $errors[$url] = $res;
725
+        }
726
+        ecrire_fichier($cache, serialize($res));
727
+    }
728
+
729
+    return $res;
730 730
 }
731 731
 
732 732
 /**
@@ -744,42 +744,42 @@  discard block
 block discarded – undo
744 744
  *   string contenu de la resource
745 745
  */
746 746
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
747
-	$tmpfile = null;
748
-	$taille = 0;
749
-	$result = '';
750
-	$fp = false;
751
-	if ($fichier) {
752
-		include_spip('inc/acces');
753
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
754
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
755
-		if (!$fp and file_exists($fichier)) {
756
-			return filesize($fichier);
757
-		}
758
-		if (!$fp) {
759
-			return false;
760
-		}
761
-		$result = 0; // on renvoie la taille du fichier
762
-	}
763
-	while (!feof($handle) and $taille < $taille_max) {
764
-		$res = fread($handle, 16384);
765
-		$taille += strlen($res);
766
-		if ($fp) {
767
-			fwrite($fp, $res);
768
-			$result = $taille;
769
-		} else {
770
-			$result .= $res;
771
-		}
772
-	}
773
-	if ($fp) {
774
-		spip_fclose_unlock($fp);
775
-		spip_unlink($fichier);
776
-		@rename($tmpfile, $fichier);
777
-		if (!file_exists($fichier)) {
778
-			return false;
779
-		}
780
-	}
781
-
782
-	return $result;
747
+    $tmpfile = null;
748
+    $taille = 0;
749
+    $result = '';
750
+    $fp = false;
751
+    if ($fichier) {
752
+        include_spip('inc/acces');
753
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
754
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
755
+        if (!$fp and file_exists($fichier)) {
756
+            return filesize($fichier);
757
+        }
758
+        if (!$fp) {
759
+            return false;
760
+        }
761
+        $result = 0; // on renvoie la taille du fichier
762
+    }
763
+    while (!feof($handle) and $taille < $taille_max) {
764
+        $res = fread($handle, 16384);
765
+        $taille += strlen($res);
766
+        if ($fp) {
767
+            fwrite($fp, $res);
768
+            $result = $taille;
769
+        } else {
770
+            $result .= $res;
771
+        }
772
+    }
773
+    if ($fp) {
774
+        spip_fclose_unlock($fp);
775
+        spip_unlink($fichier);
776
+        @rename($tmpfile, $fichier);
777
+        if (!file_exists($fichier)) {
778
+            return false;
779
+        }
780
+    }
781
+
782
+    return $result;
783 783
 }
784 784
 
785 785
 /**
@@ -801,35 +801,35 @@  discard block
 block discarded – undo
801 801
  *   string location
802 802
  */
803 803
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
804
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
805
-
806
-	$s = @trim(fgets($handle, 16384));
807
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
808
-		return false;
809
-	}
810
-	$result['status'] = intval($r[1]);
811
-	while ($s = trim(fgets($handle, 16384))) {
812
-		$result['headers'][] = $s . "\n";
813
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
814
-		[, $d, $v] = $r;
815
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
816
-			$result['location'] = $v;
817
-		} elseif ($d == 'Last-Modified') {
818
-			$result['last_modified'] = strtotime($v);
819
-		}
820
-	}
821
-	if (
822
-		$if_modified_since
823
-		and $result['last_modified']
824
-		and $if_modified_since > $result['last_modified']
825
-		and $result['status'] == 200
826
-	) {
827
-		$result['status'] = 304;
828
-	}
829
-
830
-	$result['headers'] = implode('', $result['headers']);
831
-
832
-	return $result;
804
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
805
+
806
+    $s = @trim(fgets($handle, 16384));
807
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
808
+        return false;
809
+    }
810
+    $result['status'] = intval($r[1]);
811
+    while ($s = trim(fgets($handle, 16384))) {
812
+        $result['headers'][] = $s . "\n";
813
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
814
+        [, $d, $v] = $r;
815
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
816
+            $result['location'] = $v;
817
+        } elseif ($d == 'Last-Modified') {
818
+            $result['last_modified'] = strtotime($v);
819
+        }
820
+    }
821
+    if (
822
+        $if_modified_since
823
+        and $result['last_modified']
824
+        and $if_modified_since > $result['last_modified']
825
+        and $result['status'] == 200
826
+    ) {
827
+        $result['status'] = 304;
828
+    }
829
+
830
+    $result['headers'] = implode('', $result['headers']);
831
+
832
+    return $result;
833 833
 }
834 834
 
835 835
 /**
@@ -851,22 +851,22 @@  discard block
 block discarded – undo
851 851
  *     Nom du fichier pour copie locale
852 852
  **/
853 853
 function nom_fichier_copie_locale($source, $extension) {
854
-	include_spip('inc/documents');
854
+    include_spip('inc/documents');
855 855
 
856
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
857
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
856
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
857
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
858 858
 
859
-	// on se place tout le temps comme si on etait a la racine
860
-	if (_DIR_RACINE) {
861
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
862
-	}
859
+    // on se place tout le temps comme si on etait a la racine
860
+    if (_DIR_RACINE) {
861
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
862
+    }
863 863
 
864
-	$m = md5($source);
864
+    $m = md5($source);
865 865
 
866
-	return $d
867
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
868
-	. substr($m, 0, 4)
869
-	. ".$extension";
866
+    return $d
867
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
868
+    . substr($m, 0, 4)
869
+    . ".$extension";
870 870
 }
871 871
 
872 872
 /**
@@ -884,70 +884,70 @@  discard block
 block discarded – undo
884 884
  *      Nom du fichier calculé
885 885
  **/
886 886
 function fichier_copie_locale($source) {
887
-	// Si c'est deja local pas de souci
888
-	if (!tester_url_absolue($source)) {
889
-		if (_DIR_RACINE) {
890
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
891
-		}
892
-
893
-		return $source;
894
-	}
895
-
896
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
897
-	// a deja ete copie en local avec cette extension
898
-	// dans ce cas elle est fiable, pas la peine de requeter en base
899
-	$path_parts = pathinfo($source);
900
-	if (!isset($path_parts['extension'])) {
901
-		$path_parts['extension'] = '';
902
-	}
903
-	$ext = $path_parts ? $path_parts['extension'] : '';
904
-	if (
905
-		$ext
906
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
907
-		and $f = nom_fichier_copie_locale($source, $ext)
908
-		and file_exists(_DIR_RACINE . $f)
909
-	) {
910
-		return $f;
911
-	}
912
-
913
-
914
-	// Si c'est deja dans la table des documents,
915
-	// ramener le nom de sa copie potentielle
916
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
917
-
918
-	if ($ext) {
919
-		return nom_fichier_copie_locale($source, $ext);
920
-	}
921
-
922
-	// voir si l'extension indiquee dans le nom du fichier est ok
923
-	// et si il n'aurait pas deja ete rapatrie
924
-
925
-	$ext = $path_parts ? $path_parts['extension'] : '';
926
-
927
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
928
-		$f = nom_fichier_copie_locale($source, $ext);
929
-		if (file_exists(_DIR_RACINE . $f)) {
930
-			return $f;
931
-		}
932
-	}
933
-
934
-	// Ping  pour voir si son extension est connue et autorisee
935
-	// avec mise en cache du resultat du ping
936
-
937
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
938
-	if (
939
-		!@file_exists($cache)
940
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
941
-		or _request('var_mode') === 'recalcul'
942
-	) {
943
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
944
-		ecrire_fichier($cache, serialize($path_parts));
945
-	}
946
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
947
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
948
-		return nom_fichier_copie_locale($source, $ext);
949
-	}
950
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
887
+    // Si c'est deja local pas de souci
888
+    if (!tester_url_absolue($source)) {
889
+        if (_DIR_RACINE) {
890
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
891
+        }
892
+
893
+        return $source;
894
+    }
895
+
896
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
897
+    // a deja ete copie en local avec cette extension
898
+    // dans ce cas elle est fiable, pas la peine de requeter en base
899
+    $path_parts = pathinfo($source);
900
+    if (!isset($path_parts['extension'])) {
901
+        $path_parts['extension'] = '';
902
+    }
903
+    $ext = $path_parts ? $path_parts['extension'] : '';
904
+    if (
905
+        $ext
906
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
907
+        and $f = nom_fichier_copie_locale($source, $ext)
908
+        and file_exists(_DIR_RACINE . $f)
909
+    ) {
910
+        return $f;
911
+    }
912
+
913
+
914
+    // Si c'est deja dans la table des documents,
915
+    // ramener le nom de sa copie potentielle
916
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
917
+
918
+    if ($ext) {
919
+        return nom_fichier_copie_locale($source, $ext);
920
+    }
921
+
922
+    // voir si l'extension indiquee dans le nom du fichier est ok
923
+    // et si il n'aurait pas deja ete rapatrie
924
+
925
+    $ext = $path_parts ? $path_parts['extension'] : '';
926
+
927
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
928
+        $f = nom_fichier_copie_locale($source, $ext);
929
+        if (file_exists(_DIR_RACINE . $f)) {
930
+            return $f;
931
+        }
932
+    }
933
+
934
+    // Ping  pour voir si son extension est connue et autorisee
935
+    // avec mise en cache du resultat du ping
936
+
937
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
938
+    if (
939
+        !@file_exists($cache)
940
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
941
+        or _request('var_mode') === 'recalcul'
942
+    ) {
943
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
944
+        ecrire_fichier($cache, serialize($path_parts));
945
+    }
946
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
947
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
948
+        return nom_fichier_copie_locale($source, $ext);
949
+    }
950
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
951 951
 }
952 952
 
953 953
 
@@ -976,110 +976,110 @@  discard block
 block discarded – undo
976 976
  **/
977 977
 function recuperer_infos_distantes($source, $options = []) {
978 978
 
979
-	// pas la peine de perdre son temps
980
-	if (!tester_url_absolue($source)) {
981
-		return false;
982
-	}
983
-
984
-	$taille_max = $options['taille_max'] ?? 0;
985
-	$charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
986
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
987
-
988
-	# charger les alias des types mime
989
-	include_spip('base/typedoc');
990
-
991
-	$a = [];
992
-	$mime_type = '';
993
-	// On va directement charger le debut des images et des fichiers html,
994
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
995
-	// ca echoue l'utilisateur devra les entrer...
996
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
997
-	if (
998
-		$callback_valider_url
999
-		and is_callable($callback_valider_url)
1000
-		and !$callback_valider_url($reponse['url'])
1001
-	) {
1002
-		return false;
1003
-	}
1004
-	$headers = $reponse['headers'] ?? '';
1005
-	$a['body'] = $reponse['page'] ?? '';
1006
-	if ($headers) {
1007
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1008
-			return false;
1009
-		}
1010
-
1011
-		$a['extension'] = $extension;
1012
-
1013
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1014
-			$a['taille'] = intval($regs[1]);
1015
-		}
1016
-	}
1017
-
1018
-	// Echec avec HEAD, on tente avec GET
1019
-	if (!$a and !$taille_max) {
1020
-		spip_log("tenter GET $source", 'distant');
1021
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1022
-		$a = recuperer_infos_distantes($source, $options);
1023
-	}
1024
-
1025
-	// si on a rien trouve pas la peine d'insister
1026
-	if (!$a) {
1027
-		return false;
1028
-	}
1029
-
1030
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1031
-	// recharger le document en GET et recuperer des donnees supplementaires...
1032
-	include_spip('inc/filtres_images_lib_mini');
1033
-	if (
1034
-		strpos($mime_type, 'image/') === 0
1035
-		and $extension = _image_trouver_extension_depuis_mime($mime_type)
1036
-	) {
1037
-		if (
1038
-			$taille_max == 0
1039
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1040
-			and in_array($extension, formats_image_acceptables())
1041
-			and $charger_si_petite_image
1042
-		) {
1043
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1044
-			$a = recuperer_infos_distantes($source, $options);
1045
-		} else {
1046
-			if ($a['body']) {
1047
-				$a['extension'] = $extension;
1048
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1049
-				ecrire_fichier($a['fichier'], $a['body']);
1050
-				$size_image = @spip_getimagesize($a['fichier']);
1051
-				$a['largeur'] = intval($size_image[0]);
1052
-				$a['hauteur'] = intval($size_image[1]);
1053
-				$a['type_image'] = true;
1054
-			}
1055
-		}
1056
-	}
1057
-
1058
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1059
-	// ce sera mieux que 0x0
1060
-	// Flash is dead!
1061
-	if (
1062
-		$a and isset($a['extension']) and $a['extension'] == 'swf'
1063
-		and empty($a['largeur'])
1064
-	) {
1065
-		$a['largeur'] = 425;
1066
-		$a['hauteur'] = 350;
1067
-	}
1068
-
1069
-	if ($mime_type == 'text/html') {
1070
-		include_spip('inc/filtres');
1071
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1072
-		$page = $page['page'] ?? '';
1073
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1074
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1075
-		}
1076
-		if (!isset($a['taille']) or !$a['taille']) {
1077
-			$a['taille'] = strlen($page); # a peu pres
1078
-		}
1079
-	}
1080
-	$a['mime_type'] = $mime_type;
1081
-
1082
-	return $a;
979
+    // pas la peine de perdre son temps
980
+    if (!tester_url_absolue($source)) {
981
+        return false;
982
+    }
983
+
984
+    $taille_max = $options['taille_max'] ?? 0;
985
+    $charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
986
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
987
+
988
+    # charger les alias des types mime
989
+    include_spip('base/typedoc');
990
+
991
+    $a = [];
992
+    $mime_type = '';
993
+    // On va directement charger le debut des images et des fichiers html,
994
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
995
+    // ca echoue l'utilisateur devra les entrer...
996
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
997
+    if (
998
+        $callback_valider_url
999
+        and is_callable($callback_valider_url)
1000
+        and !$callback_valider_url($reponse['url'])
1001
+    ) {
1002
+        return false;
1003
+    }
1004
+    $headers = $reponse['headers'] ?? '';
1005
+    $a['body'] = $reponse['page'] ?? '';
1006
+    if ($headers) {
1007
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1008
+            return false;
1009
+        }
1010
+
1011
+        $a['extension'] = $extension;
1012
+
1013
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1014
+            $a['taille'] = intval($regs[1]);
1015
+        }
1016
+    }
1017
+
1018
+    // Echec avec HEAD, on tente avec GET
1019
+    if (!$a and !$taille_max) {
1020
+        spip_log("tenter GET $source", 'distant');
1021
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1022
+        $a = recuperer_infos_distantes($source, $options);
1023
+    }
1024
+
1025
+    // si on a rien trouve pas la peine d'insister
1026
+    if (!$a) {
1027
+        return false;
1028
+    }
1029
+
1030
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1031
+    // recharger le document en GET et recuperer des donnees supplementaires...
1032
+    include_spip('inc/filtres_images_lib_mini');
1033
+    if (
1034
+        strpos($mime_type, 'image/') === 0
1035
+        and $extension = _image_trouver_extension_depuis_mime($mime_type)
1036
+    ) {
1037
+        if (
1038
+            $taille_max == 0
1039
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1040
+            and in_array($extension, formats_image_acceptables())
1041
+            and $charger_si_petite_image
1042
+        ) {
1043
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1044
+            $a = recuperer_infos_distantes($source, $options);
1045
+        } else {
1046
+            if ($a['body']) {
1047
+                $a['extension'] = $extension;
1048
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1049
+                ecrire_fichier($a['fichier'], $a['body']);
1050
+                $size_image = @spip_getimagesize($a['fichier']);
1051
+                $a['largeur'] = intval($size_image[0]);
1052
+                $a['hauteur'] = intval($size_image[1]);
1053
+                $a['type_image'] = true;
1054
+            }
1055
+        }
1056
+    }
1057
+
1058
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1059
+    // ce sera mieux que 0x0
1060
+    // Flash is dead!
1061
+    if (
1062
+        $a and isset($a['extension']) and $a['extension'] == 'swf'
1063
+        and empty($a['largeur'])
1064
+    ) {
1065
+        $a['largeur'] = 425;
1066
+        $a['hauteur'] = 350;
1067
+    }
1068
+
1069
+    if ($mime_type == 'text/html') {
1070
+        include_spip('inc/filtres');
1071
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1072
+        $page = $page['page'] ?? '';
1073
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1074
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1075
+        }
1076
+        if (!isset($a['taille']) or !$a['taille']) {
1077
+            $a['taille'] = strlen($page); # a peu pres
1078
+        }
1079
+    }
1080
+    $a['mime_type'] = $mime_type;
1081
+
1082
+    return $a;
1083 1083
 }
1084 1084
 
1085 1085
 /**
@@ -1088,70 +1088,70 @@  discard block
 block discarded – undo
1088 1088
  * @return false|mixed
1089 1089
  */
1090 1090
 function distant_trouver_extension_selon_headers($source, $headers) {
1091
-	if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1092
-		$mime_type = (trim($regs[1]));
1093
-	} else {
1094
-		$mime_type = '';
1095
-	} // inconnu
1096
-
1097
-	// Appliquer les alias
1098
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1099
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1100
-	}
1101
-
1102
-	// pour corriger_extension()
1103
-	include_spip('inc/documents');
1104
-
1105
-	// Si on a un mime-type insignifiant
1106
-	// text/plain,application/octet-stream ou vide
1107
-	// c'est peut-etre que le serveur ne sait pas
1108
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1109
-	// ou le Content-Disposition: attachment; filename=...
1110
-	$t = null;
1111
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1112
-		if (
1113
-			!$t
1114
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1115
-		) {
1116
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1117
-		}
1118
-		if (
1119
-			!$t
1120
-			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1121
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1122
-		) {
1123
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1124
-		}
1125
-	}
1126
-
1127
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1128
-	if (!$t) {
1129
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1130
-	}
1131
-
1132
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1133
-	// On essaie de nouveau avec l'extension
1134
-	if (
1135
-		!$t
1136
-		and $mime_type != 'text/plain'
1137
-		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1138
-	) {
1139
-		# eviter xxx.3 => 3gp (> SPIP 3)
1140
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1141
-	}
1142
-
1143
-	if ($t) {
1144
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1145
-		return $t['extension'];
1146
-	} else {
1147
-		# par defaut on retombe sur '.bin' si c'est autorise
1148
-		spip_log("mime-type $mime_type inconnu", 'distant');
1149
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1150
-		if (!$t) {
1151
-			return false;
1152
-		}
1153
-		return $t['extension'];
1154
-	}
1091
+    if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1092
+        $mime_type = (trim($regs[1]));
1093
+    } else {
1094
+        $mime_type = '';
1095
+    } // inconnu
1096
+
1097
+    // Appliquer les alias
1098
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1099
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1100
+    }
1101
+
1102
+    // pour corriger_extension()
1103
+    include_spip('inc/documents');
1104
+
1105
+    // Si on a un mime-type insignifiant
1106
+    // text/plain,application/octet-stream ou vide
1107
+    // c'est peut-etre que le serveur ne sait pas
1108
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1109
+    // ou le Content-Disposition: attachment; filename=...
1110
+    $t = null;
1111
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1112
+        if (
1113
+            !$t
1114
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1115
+        ) {
1116
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1117
+        }
1118
+        if (
1119
+            !$t
1120
+            and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1121
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1122
+        ) {
1123
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1124
+        }
1125
+    }
1126
+
1127
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1128
+    if (!$t) {
1129
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1130
+    }
1131
+
1132
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1133
+    // On essaie de nouveau avec l'extension
1134
+    if (
1135
+        !$t
1136
+        and $mime_type != 'text/plain'
1137
+        and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1138
+    ) {
1139
+        # eviter xxx.3 => 3gp (> SPIP 3)
1140
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1141
+    }
1142
+
1143
+    if ($t) {
1144
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1145
+        return $t['extension'];
1146
+    } else {
1147
+        # par defaut on retombe sur '.bin' si c'est autorise
1148
+        spip_log("mime-type $mime_type inconnu", 'distant');
1149
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1150
+        if (!$t) {
1151
+            return false;
1152
+        }
1153
+        return $t['extension'];
1154
+    }
1155 1155
 }
1156 1156
 
1157 1157
 /**
@@ -1167,45 +1167,45 @@  discard block
 block discarded – undo
1167 1167
  */
1168 1168
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1169 1169
 
1170
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1171
-
1172
-	// rien a faire si pas de proxy :)
1173
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1174
-		return '';
1175
-	}
1176
-
1177
-	if (is_null($http_noproxy)) {
1178
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1179
-	}
1180
-	// si pas d'exception, on retourne le proxy
1181
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1182
-		return $http_proxy;
1183
-	}
1184
-
1185
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1186
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1187
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1188
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1189
-	$http_noproxy = " $http_noproxy ";
1190
-	$domain = $host;
1191
-	// si le domaine exact www.example.org est dans les exceptions
1192
-	if (strpos($http_noproxy, (string) " $domain ") !== false) {
1193
-		return '';
1194
-	}
1195
-
1196
-	while (strpos($domain, '.') !== false) {
1197
-		$domain = explode('.', $domain);
1198
-		array_shift($domain);
1199
-		$domain = implode('.', $domain);
1200
-
1201
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1202
-		if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1203
-			return '';
1204
-		}
1205
-	}
1206
-
1207
-	// ok c'est pas une exception
1208
-	return $http_proxy;
1170
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1171
+
1172
+    // rien a faire si pas de proxy :)
1173
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1174
+        return '';
1175
+    }
1176
+
1177
+    if (is_null($http_noproxy)) {
1178
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1179
+    }
1180
+    // si pas d'exception, on retourne le proxy
1181
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1182
+        return $http_proxy;
1183
+    }
1184
+
1185
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1186
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1187
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1188
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1189
+    $http_noproxy = " $http_noproxy ";
1190
+    $domain = $host;
1191
+    // si le domaine exact www.example.org est dans les exceptions
1192
+    if (strpos($http_noproxy, (string) " $domain ") !== false) {
1193
+        return '';
1194
+    }
1195
+
1196
+    while (strpos($domain, '.') !== false) {
1197
+        $domain = explode('.', $domain);
1198
+        array_shift($domain);
1199
+        $domain = implode('.', $domain);
1200
+
1201
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1202
+        if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1203
+            return '';
1204
+        }
1205
+    }
1206
+
1207
+    // ok c'est pas une exception
1208
+    return $http_proxy;
1209 1209
 }
1210 1210
 
1211 1211
 
@@ -1228,59 +1228,59 @@  discard block
 block discarded – undo
1228 1228
  * @return array
1229 1229
  */
1230 1230
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1231
-	$user = $via_proxy = $proxy_user = '';
1232
-	$fopen = false;
1233
-
1234
-	$t = @parse_url($url);
1235
-	$host = $t['host'];
1236
-	if ($t['scheme'] == 'http') {
1237
-		$scheme = 'http';
1238
-		$noproxy = '';
1239
-	} elseif ($t['scheme'] == 'https') {
1240
-		$scheme = 'ssl';
1241
-		$noproxy = 'ssl://';
1242
-		if (!isset($t['port']) || !($port = $t['port'])) {
1243
-			$t['port'] = 443;
1244
-		}
1245
-	} else {
1246
-		$scheme = $t['scheme'];
1247
-		$noproxy = $scheme . '://';
1248
-	}
1249
-	if (isset($t['user'])) {
1250
-		$user = [$t['user'], $t['pass']];
1251
-	}
1252
-
1253
-	if (!isset($t['port']) || !($port = $t['port'])) {
1254
-		$port = 80;
1255
-	}
1256
-	if (!isset($t['path']) || !($path = $t['path'])) {
1257
-		$path = '/';
1258
-	}
1259
-
1260
-	if (!empty($t['query'])) {
1261
-		$path .= '?' . $t['query'];
1262
-	}
1263
-
1264
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1265
-	if (!$f or !is_resource($f)) {
1266
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1267
-		// ce qui correspond a $f===110
1268
-		if (
1269
-			$f !== 110
1270
-			and !need_proxy($host)
1271
-			and !_request('tester_proxy')
1272
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1273
-		) {
1274
-			$f = @fopen($url, 'rb');
1275
-			spip_log("connexion vers $url par simple fopen", 'distant');
1276
-			$fopen = true;
1277
-		} else {
1278
-			// echec total
1279
-			$f = false;
1280
-		}
1281
-	}
1282
-
1283
-	return [$f, $fopen];
1231
+    $user = $via_proxy = $proxy_user = '';
1232
+    $fopen = false;
1233
+
1234
+    $t = @parse_url($url);
1235
+    $host = $t['host'];
1236
+    if ($t['scheme'] == 'http') {
1237
+        $scheme = 'http';
1238
+        $noproxy = '';
1239
+    } elseif ($t['scheme'] == 'https') {
1240
+        $scheme = 'ssl';
1241
+        $noproxy = 'ssl://';
1242
+        if (!isset($t['port']) || !($port = $t['port'])) {
1243
+            $t['port'] = 443;
1244
+        }
1245
+    } else {
1246
+        $scheme = $t['scheme'];
1247
+        $noproxy = $scheme . '://';
1248
+    }
1249
+    if (isset($t['user'])) {
1250
+        $user = [$t['user'], $t['pass']];
1251
+    }
1252
+
1253
+    if (!isset($t['port']) || !($port = $t['port'])) {
1254
+        $port = 80;
1255
+    }
1256
+    if (!isset($t['path']) || !($path = $t['path'])) {
1257
+        $path = '/';
1258
+    }
1259
+
1260
+    if (!empty($t['query'])) {
1261
+        $path .= '?' . $t['query'];
1262
+    }
1263
+
1264
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1265
+    if (!$f or !is_resource($f)) {
1266
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1267
+        // ce qui correspond a $f===110
1268
+        if (
1269
+            $f !== 110
1270
+            and !need_proxy($host)
1271
+            and !_request('tester_proxy')
1272
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1273
+        ) {
1274
+            $f = @fopen($url, 'rb');
1275
+            spip_log("connexion vers $url par simple fopen", 'distant');
1276
+            $fopen = true;
1277
+        } else {
1278
+            // echec total
1279
+            $f = false;
1280
+        }
1281
+    }
1282
+
1283
+    return [$f, $fopen];
1284 1284
 }
1285 1285
 
1286 1286
 /**
@@ -1315,123 +1315,123 @@  discard block
 block discarded – undo
1315 1315
  *   resource socket vers l'url demandee
1316 1316
  */
1317 1317
 function lance_requete(
1318
-	$method,
1319
-	$scheme,
1320
-	$user,
1321
-	$host,
1322
-	$path,
1323
-	$port,
1324
-	$noproxy,
1325
-	$refuse_gz = false,
1326
-	$referer = '',
1327
-	$datas = '',
1328
-	$vers = 'HTTP/1.0',
1329
-	$date = ''
1318
+    $method,
1319
+    $scheme,
1320
+    $user,
1321
+    $host,
1322
+    $path,
1323
+    $port,
1324
+    $noproxy,
1325
+    $refuse_gz = false,
1326
+    $referer = '',
1327
+    $datas = '',
1328
+    $vers = 'HTTP/1.0',
1329
+    $date = ''
1330 1330
 ) {
1331 1331
 
1332
-	$proxy_user = '';
1333
-	$http_proxy = need_proxy($host);
1334
-	if ($user) {
1335
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1336
-	}
1337
-
1338
-	$connect = '';
1339
-	if ($http_proxy) {
1340
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1341
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1342
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1343
-				. "Host: $path_host\r\n"
1344
-				. "Proxy-Connection: Keep-Alive\r\n";
1345
-		} else {
1346
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1347
-				. (!$user ? '' : "$user@")
1348
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1349
-		}
1350
-		$t2 = @parse_url($http_proxy);
1351
-		$first_host = $t2['host'];
1352
-		$port = ($t2['port'] ?? null) ?: 80;
1353
-		if ($t2['user'] ?? null) {
1354
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1355
-		}
1356
-	} else {
1357
-		$first_host = $noproxy . $host;
1358
-	}
1359
-
1360
-	if ($connect) {
1361
-		$streamContext = stream_context_create([
1362
-			'ssl' => [
1363
-				'verify_peer' => false,
1364
-				'allow_self_signed' => true,
1365
-				'SNI_enabled' => true,
1366
-				'peer_name' => $host,
1367
-			]
1368
-		]);
1369
-		$f = @stream_socket_client(
1370
-			"tcp://$first_host:$port",
1371
-			$errno,
1372
-			$errstr,
1373
-			_INC_DISTANT_CONNECT_TIMEOUT,
1374
-			STREAM_CLIENT_CONNECT,
1375
-			$streamContext
1376
-		);
1377
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1378
-		if (!$f) {
1379
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1380
-			return $errno;
1381
-		}
1382
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1383
-
1384
-		fputs($f, $connect);
1385
-		fputs($f, "\r\n");
1386
-		$res = fread($f, 1024);
1387
-		if (
1388
-			!$res
1389
-			or !count($res = explode(' ', $res))
1390
-			or $res[1] !== '200'
1391
-		) {
1392
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1393
-			fclose($f);
1394
-
1395
-			return false;
1396
-		}
1397
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1398
-		stream_set_blocking($f, true);
1399
-		// envoyer le handshake
1400
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1401
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1402
-	} else {
1403
-		$ntry = 3;
1404
-		do {
1405
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1406
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1407
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1408
-		if (!$f) {
1409
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1410
-
1411
-			return $errno;
1412
-		}
1413
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1414
-	}
1415
-
1416
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1417
-
1418
-	$host_port = $host;
1419
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1420
-		$host_port .= ":$port";
1421
-	}
1422
-	$req = "$method $path $vers\r\n"
1423
-		. "Host: $host_port\r\n"
1424
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1425
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1426
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1427
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1428
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1429
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1430
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1332
+    $proxy_user = '';
1333
+    $http_proxy = need_proxy($host);
1334
+    if ($user) {
1335
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1336
+    }
1337
+
1338
+    $connect = '';
1339
+    if ($http_proxy) {
1340
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1341
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1342
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1343
+                . "Host: $path_host\r\n"
1344
+                . "Proxy-Connection: Keep-Alive\r\n";
1345
+        } else {
1346
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1347
+                . (!$user ? '' : "$user@")
1348
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1349
+        }
1350
+        $t2 = @parse_url($http_proxy);
1351
+        $first_host = $t2['host'];
1352
+        $port = ($t2['port'] ?? null) ?: 80;
1353
+        if ($t2['user'] ?? null) {
1354
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1355
+        }
1356
+    } else {
1357
+        $first_host = $noproxy . $host;
1358
+    }
1359
+
1360
+    if ($connect) {
1361
+        $streamContext = stream_context_create([
1362
+            'ssl' => [
1363
+                'verify_peer' => false,
1364
+                'allow_self_signed' => true,
1365
+                'SNI_enabled' => true,
1366
+                'peer_name' => $host,
1367
+            ]
1368
+        ]);
1369
+        $f = @stream_socket_client(
1370
+            "tcp://$first_host:$port",
1371
+            $errno,
1372
+            $errstr,
1373
+            _INC_DISTANT_CONNECT_TIMEOUT,
1374
+            STREAM_CLIENT_CONNECT,
1375
+            $streamContext
1376
+        );
1377
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1378
+        if (!$f) {
1379
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1380
+            return $errno;
1381
+        }
1382
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1383
+
1384
+        fputs($f, $connect);
1385
+        fputs($f, "\r\n");
1386
+        $res = fread($f, 1024);
1387
+        if (
1388
+            !$res
1389
+            or !count($res = explode(' ', $res))
1390
+            or $res[1] !== '200'
1391
+        ) {
1392
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1393
+            fclose($f);
1394
+
1395
+            return false;
1396
+        }
1397
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1398
+        stream_set_blocking($f, true);
1399
+        // envoyer le handshake
1400
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1401
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1402
+    } else {
1403
+        $ntry = 3;
1404
+        do {
1405
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1406
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1407
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1408
+        if (!$f) {
1409
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1410
+
1411
+            return $errno;
1412
+        }
1413
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1414
+    }
1415
+
1416
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1417
+
1418
+    $host_port = $host;
1419
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1420
+        $host_port .= ":$port";
1421
+    }
1422
+    $req = "$method $path $vers\r\n"
1423
+        . "Host: $host_port\r\n"
1424
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1425
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1426
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1427
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1428
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1429
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1430
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1431 1431
 
1432 1432
 #	spip_log("Requete\n$req", 'distant');
1433
-	fputs($f, $req);
1434
-	fputs($f, $datas ?: "\r\n");
1433
+    fputs($f, $req);
1434
+    fputs($f, $datas ?: "\r\n");
1435 1435
 
1436
-	return $f;
1436
+    return $f;
1437 1437
 }
Please login to merge, or discard this patch.
ecrire/inc/config.php 1 patch
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
  * @return void
29 29
  */
30 30
 function inc_config_dist() {
31
-	actualise_metas(liste_metas());
31
+    actualise_metas(liste_metas());
32 32
 }
33 33
 
34 34
 /**
@@ -45,34 +45,34 @@  discard block
 block discarded – undo
45 45
  *     Liste (table, casier, sous_casier)
46 46
  */
47 47
 function expliquer_config($cfg) {
48
-	// par defaut, sur la table des meta
49
-	$table = 'meta';
50
-	$casier = null;
51
-	$sous_casier = [];
52
-	$cfg = explode('/', $cfg);
53
-
54
-	// si le premier argument est vide, c'est une syntaxe /table/ ou un appel vide ''
55
-	if (!reset($cfg) and count($cfg) > 1) {
56
-		array_shift($cfg);
57
-		$table = array_shift($cfg);
58
-		if (!isset($GLOBALS[$table])) {
59
-			lire_metas($table);
60
-		}
61
-	}
62
-
63
-	// si on a demande #CONFIG{/meta,'',0}
64
-	if (count($cfg)) {
65
-		// pas sur un appel vide ''
66
-		if ('' !== ($c = array_shift($cfg))) {
67
-			$casier = $c;
68
-		}
69
-	}
70
-
71
-	if (count($cfg)) {
72
-		$sous_casier = $cfg;
73
-	}
74
-
75
-	return [$table, $casier, $sous_casier];
48
+    // par defaut, sur la table des meta
49
+    $table = 'meta';
50
+    $casier = null;
51
+    $sous_casier = [];
52
+    $cfg = explode('/', $cfg);
53
+
54
+    // si le premier argument est vide, c'est une syntaxe /table/ ou un appel vide ''
55
+    if (!reset($cfg) and count($cfg) > 1) {
56
+        array_shift($cfg);
57
+        $table = array_shift($cfg);
58
+        if (!isset($GLOBALS[$table])) {
59
+            lire_metas($table);
60
+        }
61
+    }
62
+
63
+    // si on a demande #CONFIG{/meta,'',0}
64
+    if (count($cfg)) {
65
+        // pas sur un appel vide ''
66
+        if ('' !== ($c = array_shift($cfg))) {
67
+            $casier = $c;
68
+        }
69
+    }
70
+
71
+    if (count($cfg)) {
72
+        $sous_casier = $cfg;
73
+    }
74
+
75
+    return [$table, $casier, $sous_casier];
76 76
 }
77 77
 
78 78
 /**
@@ -100,65 +100,65 @@  discard block
 block discarded – undo
100 100
  *    Contenu de la configuration obtenue
101 101
  */
102 102
 function lire_config($cfg = '', $def = null, $unserialize = true) {
103
-	// lire le stockage sous la forme /table/valeur
104
-	// ou valeur qui est en fait implicitement /meta/valeur
105
-	// ou casier/valeur qui est en fait implicitement /meta/casier/valeur
106
-
107
-	// traiter en priorite le cas simple et frequent
108
-	// de lecture direct $GLOBALS['meta']['truc'], si $cfg ne contient ni / ni :
109
-	if ($cfg and strpbrk($cfg, '/:') === false) {
110
-		$r = isset($GLOBALS['meta'][$cfg]) ?
111
-			((!$unserialize
112
-				// ne pas essayer de deserialiser autre chose qu'une chaine
113
-				or !is_string($GLOBALS['meta'][$cfg])
114
-				// ne pas essayer de deserialiser si ce n'est visiblement pas une chaine serializee
115
-				or !str_contains($GLOBALS['meta'][$cfg], ':')
116
-				or ($t = @unserialize($GLOBALS['meta'][$cfg])) === false) ? $GLOBALS['meta'][$cfg] : $t)
117
-			: $def;
118
-
119
-		return $r;
120
-	}
121
-
122
-	// Brancher sur methodes externes si besoin
123
-	if ($cfg and $p = strpos($cfg, '::')) {
124
-		$methode = substr($cfg, 0, $p);
125
-		$lire_config = charger_fonction($methode, 'lire_config');
126
-
127
-		return $lire_config(substr($cfg, $p + 2), $def, $unserialize);
128
-	}
129
-
130
-	[$table, $casier, $sous_casier] = expliquer_config($cfg);
131
-
132
-	if (!isset($GLOBALS[$table])) {
133
-		return $def;
134
-	}
135
-
136
-	$r = $GLOBALS[$table];
137
-
138
-	// si on a demande #CONFIG{/meta,'',0}
139
-	if (!$casier) {
140
-		return $unserialize ? $r : serialize($r);
141
-	}
142
-
143
-	// casier principal :
144
-	// le deserializer si demande
145
-	// ou si on a besoin
146
-	// d'un sous casier
147
-	$r = $r[$casier] ?? null;
148
-	if (($unserialize or is_countable($sous_casier) ? count($sous_casier) : 0) and $r and is_string($r)) {
149
-		$r = (($t = @unserialize($r)) === false ? $r : $t);
150
-	}
151
-
152
-	// aller chercher le sous_casier
153
-	while (!is_null($r) and $casier = array_shift($sous_casier)) {
154
-		$r = $r[$casier] ?? null;
155
-	}
156
-
157
-	if (is_null($r)) {
158
-		return $def;
159
-	}
160
-
161
-	return $r;
103
+    // lire le stockage sous la forme /table/valeur
104
+    // ou valeur qui est en fait implicitement /meta/valeur
105
+    // ou casier/valeur qui est en fait implicitement /meta/casier/valeur
106
+
107
+    // traiter en priorite le cas simple et frequent
108
+    // de lecture direct $GLOBALS['meta']['truc'], si $cfg ne contient ni / ni :
109
+    if ($cfg and strpbrk($cfg, '/:') === false) {
110
+        $r = isset($GLOBALS['meta'][$cfg]) ?
111
+            ((!$unserialize
112
+                // ne pas essayer de deserialiser autre chose qu'une chaine
113
+                or !is_string($GLOBALS['meta'][$cfg])
114
+                // ne pas essayer de deserialiser si ce n'est visiblement pas une chaine serializee
115
+                or !str_contains($GLOBALS['meta'][$cfg], ':')
116
+                or ($t = @unserialize($GLOBALS['meta'][$cfg])) === false) ? $GLOBALS['meta'][$cfg] : $t)
117
+            : $def;
118
+
119
+        return $r;
120
+    }
121
+
122
+    // Brancher sur methodes externes si besoin
123
+    if ($cfg and $p = strpos($cfg, '::')) {
124
+        $methode = substr($cfg, 0, $p);
125
+        $lire_config = charger_fonction($methode, 'lire_config');
126
+
127
+        return $lire_config(substr($cfg, $p + 2), $def, $unserialize);
128
+    }
129
+
130
+    [$table, $casier, $sous_casier] = expliquer_config($cfg);
131
+
132
+    if (!isset($GLOBALS[$table])) {
133
+        return $def;
134
+    }
135
+
136
+    $r = $GLOBALS[$table];
137
+
138
+    // si on a demande #CONFIG{/meta,'',0}
139
+    if (!$casier) {
140
+        return $unserialize ? $r : serialize($r);
141
+    }
142
+
143
+    // casier principal :
144
+    // le deserializer si demande
145
+    // ou si on a besoin
146
+    // d'un sous casier
147
+    $r = $r[$casier] ?? null;
148
+    if (($unserialize or is_countable($sous_casier) ? count($sous_casier) : 0) and $r and is_string($r)) {
149
+        $r = (($t = @unserialize($r)) === false ? $r : $t);
150
+    }
151
+
152
+    // aller chercher le sous_casier
153
+    while (!is_null($r) and $casier = array_shift($sous_casier)) {
154
+        $r = $r[$casier] ?? null;
155
+    }
156
+
157
+    if (is_null($r)) {
158
+        return $def;
159
+    }
160
+
161
+    return $r;
162 162
 }
163 163
 
164 164
 /**
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
  * @return mixed
173 173
  */
174 174
 function lire_config_metapack_dist($cfg = '', $def = null, $unserialize = true) {
175
-	return lire_config($cfg, $def, $unserialize);
175
+    return lire_config($cfg, $def, $unserialize);
176 176
 }
177 177
 
178 178
 
@@ -184,144 +184,144 @@  discard block
 block discarded – undo
184 184
  * @return bool
185 185
  */
186 186
 function ecrire_config($cfg, $store) {
187
-	// Brancher sur methodes externes si besoin
188
-	if ($cfg and $p = strpos($cfg, '::')) {
189
-		$methode = substr($cfg, 0, $p);
190
-		$ecrire_config = charger_fonction($methode, 'ecrire_config');
191
-
192
-		return $ecrire_config(substr($cfg, $p + 2), $store);
193
-	}
194
-
195
-	[$table, $casier, $sous_casier] = expliquer_config($cfg);
196
-	// il faut au moins un casier pour ecrire
197
-	if (!$casier) {
198
-		return false;
199
-	}
200
-
201
-	// trouvons ou creons le pointeur sur le casier
202
-	$st = $GLOBALS[$table][$casier] ?? null;
203
-	if (!is_array($st) and ($sous_casier or is_array($store))) {
204
-		if ($st === null) {
205
-			// ne rien creer si c'est une demande d'effacement
206
-			if ($store === null) {
207
-				return false;
208
-			}
209
-			$st = [];
210
-		} else {
211
-			$st = unserialize($st);
212
-			if ($st === false) {
213
-				// ne rien creer si c'est une demande d'effacement
214
-				if ($store === null) {
215
-					return false;
216
-				}
217
-				$st = [];
218
-			}
219
-		}
220
-	}
221
-
222
-	$has_planes = false;
223
-	// si on a affaire a un sous caiser
224
-	// il faut ecrire au bon endroit sans perdre les autres sous casier freres
225
-	if ($c = $sous_casier) {
226
-		$sc = &$st;
227
-		$pointeurs = [];
228
-		while (is_countable($c) ? count($c) : 0 and $cc = array_shift($c)) {
229
-			// creer l'entree si elle n'existe pas
230
-			if (!isset($sc[$cc])) {
231
-				// si on essaye d'effacer une config qui n'existe pas
232
-				// ne rien creer mais sortir
233
-				if (is_null($store)) {
234
-					return false;
235
-				}
236
-				$sc[$cc] = [];
237
-			}
238
-			$pointeurs[$cc] = &$sc;
239
-			$sc = &$sc[$cc];
240
-		}
241
-
242
-		// si c'est une demande d'effacement
243
-		if (is_null($store)) {
244
-			$c = $sous_casier;
245
-			$sous = array_pop($c);
246
-			// effacer, et remonter pour effacer les parents vides
247
-			do {
248
-				unset($pointeurs[$sous][$sous]);
249
-			} while ($sous = array_pop($c) and !(is_countable($pointeurs[$sous][$sous]) ? count($pointeurs[$sous][$sous]) : 0));
250
-
251
-			// si on a vide tous les sous casiers,
252
-			// et que le casier est vide
253
-			// vider aussi la meta
254
-			if (!$sous and !(is_countable($st) ? count($st) : 0)) {
255
-				$st = null;
256
-			}
257
-		} // dans tous les autres cas, on ecrase
258
-		else {
259
-			if (
260
-					defined('_MYSQL_NOPLANES')
261
-				and _MYSQL_NOPLANES
262
-				and !empty($GLOBALS['meta']['charset_sql_connexion'])
263
-				and $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
264
-			) {
265
-				// detecter si la valeur qu'on veut ecrire a des planes
266
-				// @see utf8_noplanes
267
-				$serialized_store = (is_string($store) ? $store : serialize($store));
268
-				// un preg_match rapide pour voir si ca vaut le coup de lancer utf8_noplanes
269
-				if (preg_match(',[\xF0-\xF4],ms', $serialized_store)) {
270
-					if (!function_exists('utf8_noplanes')) {
271
-						include_spip('inc/charsets');
272
-					}
273
-					if ($serialized_store !== utf8_noplanes($serialized_store)) {
274
-						$has_planes = true;
275
-					}
276
-				}
277
-			}
278
-
279
-			$sc = $store;
280
-		}
281
-
282
-		// Maintenant que $st est modifiee
283
-		// reprenons la comme valeur a stocker dans le casier principal
284
-		$store = $st;
285
-	}
286
-
287
-	if (is_null($store)) {
288
-		if (is_null($st) and !$sous_casier) {
289
-			return false;
290
-		} // la config n'existait deja pas !
291
-		effacer_meta($casier, $table);
292
-		supprimer_table_meta($table); // supprimons la table (si elle est bien vide)
293
-	} // les meta ne peuvent etre que des chaines : il faut serializer le reste
294
-	else {
295
-		if (!isset($GLOBALS[$table])) {
296
-			installer_table_meta($table);
297
-		}
298
-		// si ce n'est pas une chaine
299
-		// il faut serializer
300
-		if (!is_string($store)) {
301
-			$serialized_store = serialize($store);
302
-			ecrire_meta($casier, $serialized_store, null, $table);
303
-			// et dans ce cas il faut verifier que l'ecriture en base a bien eu lieu a l'identique si il y a des planes dans la chaine
304
-			// car sinon ca casse le serialize PHP - par exemple si on est en mysql utf8 (non mb4)
305
-			if ($has_planes) {
306
-				$check_store = sql_getfetsel('valeur', 'spip_' . $table, 'nom=' . sql_quote($casier));
307
-				if ($check_store !== $serialized_store) {
308
-					array_walk_recursive($store, function (&$value, $key) {
309
-						if (is_string($value)) {
310
-							$value = utf8_noplanes($value);
311
-						}
312
-					});
313
-					$serialized_store = serialize($store);
314
-					ecrire_meta($casier, $serialized_store, null, $table);
315
-				}
316
-			}
317
-		}
318
-		else {
319
-			ecrire_meta($casier, $store, null, $table);
320
-		}
321
-	}
322
-
323
-	// verifier que lire_config($cfg)==$store ?
324
-	return true;
187
+    // Brancher sur methodes externes si besoin
188
+    if ($cfg and $p = strpos($cfg, '::')) {
189
+        $methode = substr($cfg, 0, $p);
190
+        $ecrire_config = charger_fonction($methode, 'ecrire_config');
191
+
192
+        return $ecrire_config(substr($cfg, $p + 2), $store);
193
+    }
194
+
195
+    [$table, $casier, $sous_casier] = expliquer_config($cfg);
196
+    // il faut au moins un casier pour ecrire
197
+    if (!$casier) {
198
+        return false;
199
+    }
200
+
201
+    // trouvons ou creons le pointeur sur le casier
202
+    $st = $GLOBALS[$table][$casier] ?? null;
203
+    if (!is_array($st) and ($sous_casier or is_array($store))) {
204
+        if ($st === null) {
205
+            // ne rien creer si c'est une demande d'effacement
206
+            if ($store === null) {
207
+                return false;
208
+            }
209
+            $st = [];
210
+        } else {
211
+            $st = unserialize($st);
212
+            if ($st === false) {
213
+                // ne rien creer si c'est une demande d'effacement
214
+                if ($store === null) {
215
+                    return false;
216
+                }
217
+                $st = [];
218
+            }
219
+        }
220
+    }
221
+
222
+    $has_planes = false;
223
+    // si on a affaire a un sous caiser
224
+    // il faut ecrire au bon endroit sans perdre les autres sous casier freres
225
+    if ($c = $sous_casier) {
226
+        $sc = &$st;
227
+        $pointeurs = [];
228
+        while (is_countable($c) ? count($c) : 0 and $cc = array_shift($c)) {
229
+            // creer l'entree si elle n'existe pas
230
+            if (!isset($sc[$cc])) {
231
+                // si on essaye d'effacer une config qui n'existe pas
232
+                // ne rien creer mais sortir
233
+                if (is_null($store)) {
234
+                    return false;
235
+                }
236
+                $sc[$cc] = [];
237
+            }
238
+            $pointeurs[$cc] = &$sc;
239
+            $sc = &$sc[$cc];
240
+        }
241
+
242
+        // si c'est une demande d'effacement
243
+        if (is_null($store)) {
244
+            $c = $sous_casier;
245
+            $sous = array_pop($c);
246
+            // effacer, et remonter pour effacer les parents vides
247
+            do {
248
+                unset($pointeurs[$sous][$sous]);
249
+            } while ($sous = array_pop($c) and !(is_countable($pointeurs[$sous][$sous]) ? count($pointeurs[$sous][$sous]) : 0));
250
+
251
+            // si on a vide tous les sous casiers,
252
+            // et que le casier est vide
253
+            // vider aussi la meta
254
+            if (!$sous and !(is_countable($st) ? count($st) : 0)) {
255
+                $st = null;
256
+            }
257
+        } // dans tous les autres cas, on ecrase
258
+        else {
259
+            if (
260
+                    defined('_MYSQL_NOPLANES')
261
+                and _MYSQL_NOPLANES
262
+                and !empty($GLOBALS['meta']['charset_sql_connexion'])
263
+                and $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
264
+            ) {
265
+                // detecter si la valeur qu'on veut ecrire a des planes
266
+                // @see utf8_noplanes
267
+                $serialized_store = (is_string($store) ? $store : serialize($store));
268
+                // un preg_match rapide pour voir si ca vaut le coup de lancer utf8_noplanes
269
+                if (preg_match(',[\xF0-\xF4],ms', $serialized_store)) {
270
+                    if (!function_exists('utf8_noplanes')) {
271
+                        include_spip('inc/charsets');
272
+                    }
273
+                    if ($serialized_store !== utf8_noplanes($serialized_store)) {
274
+                        $has_planes = true;
275
+                    }
276
+                }
277
+            }
278
+
279
+            $sc = $store;
280
+        }
281
+
282
+        // Maintenant que $st est modifiee
283
+        // reprenons la comme valeur a stocker dans le casier principal
284
+        $store = $st;
285
+    }
286
+
287
+    if (is_null($store)) {
288
+        if (is_null($st) and !$sous_casier) {
289
+            return false;
290
+        } // la config n'existait deja pas !
291
+        effacer_meta($casier, $table);
292
+        supprimer_table_meta($table); // supprimons la table (si elle est bien vide)
293
+    } // les meta ne peuvent etre que des chaines : il faut serializer le reste
294
+    else {
295
+        if (!isset($GLOBALS[$table])) {
296
+            installer_table_meta($table);
297
+        }
298
+        // si ce n'est pas une chaine
299
+        // il faut serializer
300
+        if (!is_string($store)) {
301
+            $serialized_store = serialize($store);
302
+            ecrire_meta($casier, $serialized_store, null, $table);
303
+            // et dans ce cas il faut verifier que l'ecriture en base a bien eu lieu a l'identique si il y a des planes dans la chaine
304
+            // car sinon ca casse le serialize PHP - par exemple si on est en mysql utf8 (non mb4)
305
+            if ($has_planes) {
306
+                $check_store = sql_getfetsel('valeur', 'spip_' . $table, 'nom=' . sql_quote($casier));
307
+                if ($check_store !== $serialized_store) {
308
+                    array_walk_recursive($store, function (&$value, $key) {
309
+                        if (is_string($value)) {
310
+                            $value = utf8_noplanes($value);
311
+                        }
312
+                    });
313
+                    $serialized_store = serialize($store);
314
+                    ecrire_meta($casier, $serialized_store, null, $table);
315
+                }
316
+            }
317
+        }
318
+        else {
319
+            ecrire_meta($casier, $store, null, $table);
320
+        }
321
+    }
322
+
323
+    // verifier que lire_config($cfg)==$store ?
324
+    return true;
325 325
 }
326 326
 
327 327
 
@@ -335,14 +335,14 @@  discard block
 block discarded – undo
335 335
  * @return bool
336 336
  */
337 337
 function ecrire_config_metapack_dist($cfg, $store) {
338
-	// cas particulier en metapack::
339
-	// si on ecrit une chaine deja serializee, il faut la reserializer pour la rendre
340
-	// intacte en sortie ...
341
-	if (is_string($store) and strpos($store, ':') and unserialize($store)) {
342
-		$store = serialize($store);
343
-	}
344
-
345
-	return ecrire_config($cfg, $store);
338
+    // cas particulier en metapack::
339
+    // si on ecrit une chaine deja serializee, il faut la reserializer pour la rendre
340
+    // intacte en sortie ...
341
+    if (is_string($store) and strpos($store, ':') and unserialize($store)) {
342
+        $store = serialize($store);
343
+    }
344
+
345
+    return ecrire_config($cfg, $store);
346 346
 }
347 347
 
348 348
 /**
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
  * @return bool
353 353
  */
354 354
 function effacer_config($cfg) {
355
-	ecrire_config($cfg, null);
355
+    ecrire_config($cfg, null);
356 356
 
357
-	return true;
357
+    return true;
358 358
 }
359 359
 
360 360
 /**
@@ -371,58 +371,58 @@  discard block
 block discarded – undo
371 371
  *    Couples nom de la `meta` => valeur par défaut
372 372
  */
373 373
 function liste_metas() {
374
-	return pipeline('configurer_liste_metas', [
375
-		'nom_site' => _T('info_mon_site_spip'),
376
-		'slogan_site' => '',
377
-		'adresse_site' => preg_replace(',/$,', '', url_de_base()),
378
-		'descriptif_site' => '',
379
-		'activer_logos' => 'oui',
380
-		'activer_logos_survol' => 'non',
381
-		'articles_surtitre' => 'non',
382
-		'articles_soustitre' => 'non',
383
-		'articles_descriptif' => 'non',
384
-		'articles_chapeau' => 'non',
385
-		'articles_texte' => 'oui',
386
-		'articles_ps' => 'non',
387
-		'articles_redac' => 'non',
388
-		'post_dates' => 'non',
389
-		'articles_urlref' => 'non',
390
-		'articles_redirection' => 'non',
391
-		'creer_preview' => 'non',
392
-		'taille_preview' => 150,
393
-		'articles_modif' => 'non',
394
-
395
-		'rubriques_descriptif' => 'non',
396
-		'rubriques_texte' => 'oui',
397
-
398
-		'accepter_inscriptions' => 'non',
399
-		'accepter_visiteurs' => 'non',
400
-		'prevenir_auteurs' => 'non',
401
-		'suivi_edito' => 'non',
402
-		'adresse_suivi' => '',
403
-		'adresse_suivi_inscription' => '',
404
-		'adresse_neuf' => '',
405
-		'jours_neuf' => '',
406
-		'quoi_de_neuf' => 'non',
407
-		'preview' => ',0minirezo,1comite,',
408
-
409
-		'syndication_integrale' => 'oui',
410
-		'charset' => _DEFAULT_CHARSET,
411
-		'dir_img' => substr(_DIR_IMG, strlen(_DIR_RACINE)),
412
-
413
-		'multi_rubriques' => 'non',
414
-		'multi_secteurs' => 'non',
415
-		'gerer_trad' => 'non',
416
-		'langues_multilingue' => '',
417
-
418
-		'version_html_max' => 'html4',
419
-
420
-		'type_urls' => 'page',
421
-
422
-		'email_envoi' => '',
423
-		'email_webmaster' => '',
424
-		'auto_compress_http' => 'non',
425
-	]);
374
+    return pipeline('configurer_liste_metas', [
375
+        'nom_site' => _T('info_mon_site_spip'),
376
+        'slogan_site' => '',
377
+        'adresse_site' => preg_replace(',/$,', '', url_de_base()),
378
+        'descriptif_site' => '',
379
+        'activer_logos' => 'oui',
380
+        'activer_logos_survol' => 'non',
381
+        'articles_surtitre' => 'non',
382
+        'articles_soustitre' => 'non',
383
+        'articles_descriptif' => 'non',
384
+        'articles_chapeau' => 'non',
385
+        'articles_texte' => 'oui',
386
+        'articles_ps' => 'non',
387
+        'articles_redac' => 'non',
388
+        'post_dates' => 'non',
389
+        'articles_urlref' => 'non',
390
+        'articles_redirection' => 'non',
391
+        'creer_preview' => 'non',
392
+        'taille_preview' => 150,
393
+        'articles_modif' => 'non',
394
+
395
+        'rubriques_descriptif' => 'non',
396
+        'rubriques_texte' => 'oui',
397
+
398
+        'accepter_inscriptions' => 'non',
399
+        'accepter_visiteurs' => 'non',
400
+        'prevenir_auteurs' => 'non',
401
+        'suivi_edito' => 'non',
402
+        'adresse_suivi' => '',
403
+        'adresse_suivi_inscription' => '',
404
+        'adresse_neuf' => '',
405
+        'jours_neuf' => '',
406
+        'quoi_de_neuf' => 'non',
407
+        'preview' => ',0minirezo,1comite,',
408
+
409
+        'syndication_integrale' => 'oui',
410
+        'charset' => _DEFAULT_CHARSET,
411
+        'dir_img' => substr(_DIR_IMG, strlen(_DIR_RACINE)),
412
+
413
+        'multi_rubriques' => 'non',
414
+        'multi_secteurs' => 'non',
415
+        'gerer_trad' => 'non',
416
+        'langues_multilingue' => '',
417
+
418
+        'version_html_max' => 'html4',
419
+
420
+        'type_urls' => 'page',
421
+
422
+        'email_envoi' => '',
423
+        'email_webmaster' => '',
424
+        'auto_compress_http' => 'non',
425
+    ]);
426 426
 }
427 427
 
428 428
 /**
@@ -433,43 +433,43 @@  discard block
 block discarded – undo
433 433
  * @return void
434 434
  */
435 435
 function actualise_metas($liste_meta) {
436
-	$meta_serveur =
437
-		[
438
-			'version_installee',
439
-			'adresse_site',
440
-			'alea_ephemere_ancien',
441
-			'alea_ephemere',
442
-			'alea_ephemere_date',
443
-			'langue_site',
444
-			'langues_proposees',
445
-			'date_calcul_rubriques',
446
-			'derniere_modif',
447
-			'optimiser_table',
448
-			'drapeau_edition',
449
-			'creer_preview',
450
-			'taille_preview',
451
-			'creer_htpasswd',
452
-			'creer_htaccess',
453
-			'gd_formats_read',
454
-			'gd_formats',
455
-			'netpbm_formats',
456
-			'formats_graphiques',
457
-			'image_process',
458
-			'plugin_header',
459
-			'plugin'
460
-		];
461
-	// verifier le impt=non
462
-	sql_updateq('spip_meta', ['impt' => 'non'], sql_in('nom', $meta_serveur));
463
-
464
-	foreach ($liste_meta as $nom => $valeur) {
465
-		if (empty($GLOBALS['meta'][$nom])) {
466
-			ecrire_meta($nom, $valeur);
467
-		}
468
-	}
469
-
470
-	include_spip('inc/rubriques');
471
-	$langues = calculer_langues_utilisees();
472
-	ecrire_meta('langues_utilisees', $langues);
436
+    $meta_serveur =
437
+        [
438
+            'version_installee',
439
+            'adresse_site',
440
+            'alea_ephemere_ancien',
441
+            'alea_ephemere',
442
+            'alea_ephemere_date',
443
+            'langue_site',
444
+            'langues_proposees',
445
+            'date_calcul_rubriques',
446
+            'derniere_modif',
447
+            'optimiser_table',
448
+            'drapeau_edition',
449
+            'creer_preview',
450
+            'taille_preview',
451
+            'creer_htpasswd',
452
+            'creer_htaccess',
453
+            'gd_formats_read',
454
+            'gd_formats',
455
+            'netpbm_formats',
456
+            'formats_graphiques',
457
+            'image_process',
458
+            'plugin_header',
459
+            'plugin'
460
+        ];
461
+    // verifier le impt=non
462
+    sql_updateq('spip_meta', ['impt' => 'non'], sql_in('nom', $meta_serveur));
463
+
464
+    foreach ($liste_meta as $nom => $valeur) {
465
+        if (empty($GLOBALS['meta'][$nom])) {
466
+            ecrire_meta($nom, $valeur);
467
+        }
468
+    }
469
+
470
+    include_spip('inc/rubriques');
471
+    $langues = calculer_langues_utilisees();
472
+    ecrire_meta('langues_utilisees', $langues);
473 473
 }
474 474
 
475 475
 
@@ -491,18 +491,18 @@  discard block
 block discarded – undo
491 491
  */
492 492
 function appliquer_modifs_config($purger_skel = false) {
493 493
 
494
-	foreach (liste_metas() as $i => $v) {
495
-		if (($x = _request($i)) !== null) {
496
-			ecrire_meta($i, $x);
497
-		} elseif (!isset($GLOBALS['meta'][$i])) {
498
-			ecrire_meta($i, $v);
499
-		}
500
-	}
501
-
502
-	if ($purger_skel) {
503
-		include_spip('inc/invalideur');
504
-		purger_repertoire(_DIR_SKELS);
505
-	}
494
+    foreach (liste_metas() as $i => $v) {
495
+        if (($x = _request($i)) !== null) {
496
+            ecrire_meta($i, $x);
497
+        } elseif (!isset($GLOBALS['meta'][$i])) {
498
+            ecrire_meta($i, $v);
499
+        }
500
+    }
501
+
502
+    if ($purger_skel) {
503
+        include_spip('inc/invalideur');
504
+        purger_repertoire(_DIR_SKELS);
505
+    }
506 506
 }
507 507
 
508 508
 /**
@@ -513,21 +513,21 @@  discard block
 block discarded – undo
513 513
  * @return string
514 514
  */
515 515
 function appliquer_adresse_site($adresse_site) {
516
-	if ($adresse_site !== null) {
517
-		if (!strlen($adresse_site)) {
518
-			$GLOBALS['profondeur_url'] = _DIR_RESTREINT ? 0 : 1;
519
-			$adresse_site = url_de_base();
520
-		}
521
-		$adresse_site = preg_replace(',/?\s*$,', '', $adresse_site);
516
+    if ($adresse_site !== null) {
517
+        if (!strlen($adresse_site)) {
518
+            $GLOBALS['profondeur_url'] = _DIR_RESTREINT ? 0 : 1;
519
+            $adresse_site = url_de_base();
520
+        }
521
+        $adresse_site = preg_replace(',/?\s*$,', '', $adresse_site);
522 522
 
523
-		if (!tester_url_absolue($adresse_site)) {
524
-			$adresse_site = "http://$adresse_site";
525
-		}
523
+        if (!tester_url_absolue($adresse_site)) {
524
+            $adresse_site = "http://$adresse_site";
525
+        }
526 526
 
527
-		$adresse_site = entites_html($adresse_site);
527
+        $adresse_site = entites_html($adresse_site);
528 528
 
529
-		ecrire_meta('adresse_site', $adresse_site);
530
-	}
529
+        ecrire_meta('adresse_site', $adresse_site);
530
+    }
531 531
 
532
-	return $adresse_site;
532
+    return $adresse_site;
533 533
 }
Please login to merge, or discard this patch.
ecrire/inc/actions.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -43,9 +43,9 @@  discard block
 block discarded – undo
43 43
  *     URL, code HTML du formulaire ou tableau (action, arg, hash)
44 44
  */
45 45
 function generer_action_auteur($action, $arg = '', $redirect = '', $mode = false, $att = '', $public = false) {
46
-	$securiser_action = charger_fonction('securiser_action', 'inc');
46
+    $securiser_action = charger_fonction('securiser_action', 'inc');
47 47
 
48
-	return $securiser_action($action, $arg, $redirect, $mode, $att, $public);
48
+    return $securiser_action($action, $arg, $redirect, $mode, $att, $public);
49 49
 }
50 50
 
51 51
 /**
@@ -78,9 +78,9 @@  discard block
 block discarded – undo
78 78
  *     Code HTML du formulaire
79 79
  */
80 80
 function redirige_action_auteur($action, $arg, $ret, $gra = '', $mode = false, $atts = '', $public = false) {
81
-	$r = ($public ? _DIR_RESTREINT_ABS : _DIR_RESTREINT) . generer_url_ecrire($ret, $gra, true, true);
81
+    $r = ($public ? _DIR_RESTREINT_ABS : _DIR_RESTREINT) . generer_url_ecrire($ret, $gra, true, true);
82 82
 
83
-	return generer_action_auteur($action, $arg, $r, $mode, $atts, $public);
83
+    return generer_action_auteur($action, $arg, $r, $mode, $atts, $public);
84 84
 }
85 85
 
86 86
 /**
@@ -105,9 +105,9 @@  discard block
 block discarded – undo
105 105
  *     URL, code HTML du formulaire ou tableau (action, arg, hash)
106 106
  */
107 107
 function redirige_action_post($action, $arg, $ret, $gra, $corps, $att = '') {
108
-	$r = _DIR_RESTREINT . generer_url_ecrire($ret, $gra, false, true);
108
+    $r = _DIR_RESTREINT . generer_url_ecrire($ret, $gra, false, true);
109 109
 
110
-	return generer_action_auteur($action, $arg, $r, $corps, $att . " method='post'");
110
+    return generer_action_auteur($action, $arg, $r, $corps, $att . " method='post'");
111 111
 }
112 112
 
113 113
 
@@ -124,26 +124,26 @@  discard block
 block discarded – undo
124 124
  *   passer "text/html" comme $content_type
125 125
  */
126 126
 function ajax_retour($corps, $content_type = null): void {
127
-	$xml = false;
128
-	if (is_null($content_type) or $content_type === true) {
129
-		$xml = true;
130
-		$content_type = 'text/html';
131
-	} elseif (!$content_type or !is_string($content_type) or !str_contains($content_type, '/')) {
132
-		$content_type = 'text/html';
133
-	}
127
+    $xml = false;
128
+    if (is_null($content_type) or $content_type === true) {
129
+        $xml = true;
130
+        $content_type = 'text/html';
131
+    } elseif (!$content_type or !is_string($content_type) or !str_contains($content_type, '/')) {
132
+        $content_type = 'text/html';
133
+    }
134 134
 
135
-	$e = '';
136
-	if (
137
-		isset($_COOKIE['spip_admin'])
138
-		and ((_request('var_mode') == 'debug') or !empty($GLOBALS['tableau_des_temps']))
139
-	) {
140
-		$e = erreur_squelette();
141
-	}
135
+    $e = '';
136
+    if (
137
+        isset($_COOKIE['spip_admin'])
138
+        and ((_request('var_mode') == 'debug') or !empty($GLOBALS['tableau_des_temps']))
139
+    ) {
140
+        $e = erreur_squelette();
141
+    }
142 142
 
143
-	$c = $GLOBALS['meta']['charset'];
144
-	header('Content-Type: ' . $content_type . '; charset=' . $c);
145
-	$debut = (($xml and strlen(trim($corps))) ? '<' . "?xml version='1.0' encoding='" . $c . "'?" . ">\n" : '');
146
-	$fin = '';
143
+    $c = $GLOBALS['meta']['charset'];
144
+    header('Content-Type: ' . $content_type . '; charset=' . $c);
145
+    $debut = (($xml and strlen(trim($corps))) ? '<' . "?xml version='1.0' encoding='" . $c . "'?" . ">\n" : '');
146
+    $fin = '';
147 147
 
148
-	echo $debut, $corps, $fin, $e;
148
+    echo $debut, $corps, $fin, $e;
149 149
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_dates.php 1 patch
Indentation   +580 added lines, -580 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Filtres
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 
@@ -37,11 +37,11 @@  discard block
 block discarded – undo
37 37
  *    Date au format SQL tel que `2008-04-01` sinon ''
38 38
  **/
39 39
 function extraire_date($texte): string {
40
-	// format = 2001-08
41
-	if (preg_match(',([1-2][0-9]{3})[^0-9]*(1[0-2]|0?[1-9]),', $texte, $regs)) {
42
-		return $regs[1] . '-' . sprintf('%02d', $regs[2]) . '-01';
43
-	}
44
-	return '';
40
+    // format = 2001-08
41
+    if (preg_match(',([1-2][0-9]{3})[^0-9]*(1[0-2]|0?[1-9]),', $texte, $regs)) {
42
+        return $regs[1] . '-' . sprintf('%02d', $regs[2]) . '-01';
43
+    }
44
+    return '';
45 45
 }
46 46
 
47 47
 
@@ -63,29 +63,29 @@  discard block
 block discarded – undo
63 63
  *     - une chaîne vide si la date est considérée nulle
64 64
  **/
65 65
 function normaliser_date($date, $forcer_jour = false): string {
66
-	$date = vider_date($date);
67
-	if ($date) {
68
-		if (preg_match('/^[0-9]{8,10}$/', $date)) {
69
-			$date = date('Y-m-d H:i:s', $date);
70
-		}
71
-		if (preg_match('#^([12][0-9]{3})([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
72
-			$regs = array_pad($regs, 4, null); // eviter notice php
73
-			$date = $regs[1] . '-00-00' . $regs[3];
74
-		} else {
75
-			if (preg_match('#^([12][0-9]{3}[-/][01]?[0-9])([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
76
-				$regs = array_pad($regs, 4, null); // eviter notice php
77
-				$date = preg_replace('@/@', '-', $regs[1]) . '-00' . $regs[3];
78
-			} else {
79
-				$date = date('Y-m-d H:i:s', strtotime($date));
80
-			}
81
-		}
82
-
83
-		if ($forcer_jour) {
84
-			$date = str_replace('-00', '-01', $date);
85
-		}
86
-	}
87
-
88
-	return $date;
66
+    $date = vider_date($date);
67
+    if ($date) {
68
+        if (preg_match('/^[0-9]{8,10}$/', $date)) {
69
+            $date = date('Y-m-d H:i:s', $date);
70
+        }
71
+        if (preg_match('#^([12][0-9]{3})([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
72
+            $regs = array_pad($regs, 4, null); // eviter notice php
73
+            $date = $regs[1] . '-00-00' . $regs[3];
74
+        } else {
75
+            if (preg_match('#^([12][0-9]{3}[-/][01]?[0-9])([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
76
+                $regs = array_pad($regs, 4, null); // eviter notice php
77
+                $date = preg_replace('@/@', '-', $regs[1]) . '-00' . $regs[3];
78
+            } else {
79
+                $date = date('Y-m-d H:i:s', strtotime($date));
80
+            }
81
+        }
82
+
83
+        if ($forcer_jour) {
84
+            $date = str_replace('-00', '-01', $date);
85
+        }
86
+    }
87
+
88
+    return $date;
89 89
 }
90 90
 
91 91
 /**
@@ -98,23 +98,23 @@  discard block
 block discarded – undo
98 98
  *     - Une chaine vide
99 99
  **/
100 100
 function vider_date($letexte, $verif_format_date = false): string {
101
-	$letexte ??= '';
102
-	if (
103
-		!$verif_format_date
104
-		or (in_array(strlen($letexte), [10,19]) and
105
-			  preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $letexte))
106
-	) {
107
-		if (strncmp('0000-00-00', $letexte, 10) == 0) {
108
-			return '';
109
-		}
110
-		if (strncmp('0001-01-01', $letexte, 10) == 0) {
111
-			return '';
112
-		}
113
-		if (strncmp('1970-01-01', $letexte, 10) == 0) {
114
-			return '';
115
-		}  // eviter le bug GMT-1
116
-	}
117
-	return $letexte;
101
+    $letexte ??= '';
102
+    if (
103
+        !$verif_format_date
104
+        or (in_array(strlen($letexte), [10,19]) and
105
+              preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $letexte))
106
+    ) {
107
+        if (strncmp('0000-00-00', $letexte, 10) == 0) {
108
+            return '';
109
+        }
110
+        if (strncmp('0001-01-01', $letexte, 10) == 0) {
111
+            return '';
112
+        }
113
+        if (strncmp('1970-01-01', $letexte, 10) == 0) {
114
+            return '';
115
+        }  // eviter le bug GMT-1
116
+    }
117
+    return $letexte;
118 118
 }
119 119
 
120 120
 /**
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
  **/
131 131
 function recup_heure($date): array {
132 132
 
133
-	static $d = [0, 0, 0];
134
-	if (!preg_match('#([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $date, $r)) {
135
-		return $d;
136
-	}
133
+    static $d = [0, 0, 0];
134
+    if (!preg_match('#([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $date, $r)) {
135
+        return $d;
136
+    }
137 137
 
138
-	array_shift($r);
138
+    array_shift($r);
139 139
 
140
-	return $r;
140
+    return $r;
141 141
 }
142 142
 
143 143
 /**
@@ -151,13 +151,13 @@  discard block
 block discarded – undo
151 151
  * @return string heures, sinon 0
152 152
  **/
153 153
 function heures($numdate): string {
154
-	$heures = null;
155
-	$date_array = recup_heure($numdate);
156
-	if ($date_array) {
157
-		[$heures, $minutes, $secondes] = $date_array;
158
-	}
154
+    $heures = null;
155
+    $date_array = recup_heure($numdate);
156
+    if ($date_array) {
157
+        [$heures, $minutes, $secondes] = $date_array;
158
+    }
159 159
 
160
-	return $heures;
160
+    return $heures;
161 161
 }
162 162
 
163 163
 /**
@@ -171,13 +171,13 @@  discard block
 block discarded – undo
171 171
  * @return string minutes, sinon 0
172 172
  **/
173 173
 function minutes($numdate): string {
174
-	$minutes = null;
175
-	$date_array = recup_heure($numdate);
176
-	if ($date_array) {
177
-		[$heures, $minutes, $secondes] = $date_array;
178
-	}
174
+    $minutes = null;
175
+    $date_array = recup_heure($numdate);
176
+    if ($date_array) {
177
+        [$heures, $minutes, $secondes] = $date_array;
178
+    }
179 179
 
180
-	return $minutes;
180
+    return $minutes;
181 181
 }
182 182
 
183 183
 /**
@@ -191,13 +191,13 @@  discard block
 block discarded – undo
191 191
  * @return string secondes, sinon 0
192 192
  **/
193 193
 function secondes($numdate): string {
194
-	$secondes = null;
195
-	$date_array = recup_heure($numdate);
196
-	if ($date_array) {
197
-		[$heures, $minutes, $secondes] = $date_array;
198
-	}
194
+    $secondes = null;
195
+    $date_array = recup_heure($numdate);
196
+    if ($date_array) {
197
+        [$heures, $minutes, $secondes] = $date_array;
198
+    }
199 199
 
200
-	return $secondes;
200
+    return $secondes;
201 201
 }
202 202
 
203 203
 /**
@@ -216,11 +216,11 @@  discard block
 block discarded – undo
216 216
  * @return string L'heure formatée dans la langue en cours.
217 217
  **/
218 218
 function heures_minutes($numdate, $forme = ''): string {
219
-	if ($forme !== 'abbr') {
220
-		return _T('date_fmt_heures_minutes', ['h' => heures($numdate), 'm' => minutes($numdate)]);
221
-	} else {
222
-		return _T('date_fmt_heures_minutes_court', ['h' => heures($numdate), 'm' => minutes($numdate)]);
223
-	}
219
+    if ($forme !== 'abbr') {
220
+        return _T('date_fmt_heures_minutes', ['h' => heures($numdate), 'm' => minutes($numdate)]);
221
+    } else {
222
+        return _T('date_fmt_heures_minutes_court', ['h' => heures($numdate), 'm' => minutes($numdate)]);
223
+    }
224 224
 }
225 225
 
226 226
 /**
@@ -245,57 +245,57 @@  discard block
 block discarded – undo
245 245
  * @return array [année, mois, jour, heures, minutes, secondes] ou []
246 246
  **/
247 247
 function recup_date($numdate, $forcer_jour = true): array {
248
-	if (!$numdate) {
249
-		return [];
250
-	}
251
-	$heures = $minutes = $secondes = 0;
252
-	if (preg_match('#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}|[0-9]{1,2})#', $numdate, $regs)) {
253
-		$jour = $regs[1];
254
-		$mois = $regs[2];
255
-		$annee = $regs[3];
256
-		if ($annee < 90) {
257
-			$annee = 2000 + $annee;
258
-		} elseif ($annee < 100) {
259
-			$annee = 1900 + $annee;
260
-		}
261
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
262
-	} elseif (preg_match('#([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})#', $numdate, $regs)) {
263
-		$annee = $regs[1];
264
-		$mois = $regs[2];
265
-		$jour = $regs[3];
266
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
267
-	} elseif (preg_match('#([0-9]{4})-([0-9]{2})#', $numdate, $regs)) {
268
-		$annee = $regs[1];
269
-		$mois = $regs[2];
270
-		$jour = '';
271
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
272
-	} elseif (preg_match('#^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$#', $numdate, $regs)) {
273
-		$annee = $regs[1];
274
-		$mois = $regs[2];
275
-		$jour = $regs[3];
276
-		$heures = $regs[4];
277
-		$minutes = $regs[5];
278
-		$secondes = $regs[6];
279
-	} else {
280
-		$annee = $mois = $jour = '';
281
-	}
282
-	if ($annee > 4000) {
283
-		$annee -= 9000;
284
-	}
285
-	if (strlen($jour) and substr($jour, 0, 1) == '0') {
286
-		$jour = substr($jour, 1);
287
-	}
288
-
289
-	if ($forcer_jour and $jour == '0') {
290
-		$jour = '1';
291
-	}
292
-	if ($forcer_jour and $mois == '0') {
293
-		$mois = '1';
294
-	}
295
-	if ($annee or $mois or $jour or $heures or $minutes or $secondes) {
296
-		return [$annee, $mois, $jour, $heures, $minutes, $secondes];
297
-	}
298
-	return [];
248
+    if (!$numdate) {
249
+        return [];
250
+    }
251
+    $heures = $minutes = $secondes = 0;
252
+    if (preg_match('#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}|[0-9]{1,2})#', $numdate, $regs)) {
253
+        $jour = $regs[1];
254
+        $mois = $regs[2];
255
+        $annee = $regs[3];
256
+        if ($annee < 90) {
257
+            $annee = 2000 + $annee;
258
+        } elseif ($annee < 100) {
259
+            $annee = 1900 + $annee;
260
+        }
261
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
262
+    } elseif (preg_match('#([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})#', $numdate, $regs)) {
263
+        $annee = $regs[1];
264
+        $mois = $regs[2];
265
+        $jour = $regs[3];
266
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
267
+    } elseif (preg_match('#([0-9]{4})-([0-9]{2})#', $numdate, $regs)) {
268
+        $annee = $regs[1];
269
+        $mois = $regs[2];
270
+        $jour = '';
271
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
272
+    } elseif (preg_match('#^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$#', $numdate, $regs)) {
273
+        $annee = $regs[1];
274
+        $mois = $regs[2];
275
+        $jour = $regs[3];
276
+        $heures = $regs[4];
277
+        $minutes = $regs[5];
278
+        $secondes = $regs[6];
279
+    } else {
280
+        $annee = $mois = $jour = '';
281
+    }
282
+    if ($annee > 4000) {
283
+        $annee -= 9000;
284
+    }
285
+    if (strlen($jour) and substr($jour, 0, 1) == '0') {
286
+        $jour = substr($jour, 1);
287
+    }
288
+
289
+    if ($forcer_jour and $jour == '0') {
290
+        $jour = '1';
291
+    }
292
+    if ($forcer_jour and $mois == '0') {
293
+        $mois = '1';
294
+    }
295
+    if ($annee or $mois or $jour or $heures or $minutes or $secondes) {
296
+        return [$annee, $mois, $jour, $heures, $minutes, $secondes];
297
+    }
298
+    return [];
299 299
 }
300 300
 
301 301
 /**
@@ -322,10 +322,10 @@  discard block
 block discarded – undo
322 322
  *     La date relative ou complète
323 323
  **/
324 324
 function date_interface($date, $decalage_maxi = 43200 /* 12*3600 */): string {
325
-	return sinon(
326
-		date_relative($date, $decalage_maxi),
327
-		affdate_heure($date)
328
-	);
325
+    return sinon(
326
+        date_relative($date, $decalage_maxi),
327
+        affdate_heure($date)
328
+    );
329 329
 }
330 330
 
331 331
 /**
@@ -358,86 +358,86 @@  discard block
 block discarded – undo
358 358
  **/
359 359
 function date_relative($date, $decalage_maxi = 0, $ref_date = null): string {
360 360
 
361
-	if (!$date) {
362
-		return '';
363
-	}
364
-
365
-	if (is_null($ref_date)) {
366
-		$ref_time = time();
367
-	} else {
368
-		$ref_time = strtotime($ref_date);
369
-	}
370
-
371
-	$decal = date('U', $ref_time) - date('U', strtotime($date));
372
-
373
-	if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
374
-		return '';
375
-	}
376
-
377
-	if ($decal < 0) {
378
-		$il_y_a = 'date_dans';
379
-		$decal = -1 * $decal;
380
-	} else {
381
-		$il_y_a = 'date_il_y_a';
382
-	}
383
-
384
-	if ($decal > 3600 * 24 * 30 * 6) {
385
-		return affdate_court($date);
386
-	}
387
-
388
-	if ($decal > 3600 * 24 * 30) {
389
-		$mois = floor($decal / (3600 * 24 * 30));
390
-		if ($mois < 2) {
391
-			$delai = "$mois " . _T('date_un_mois');
392
-		} else {
393
-			$delai = "$mois " . _T('date_mois');
394
-		}
395
-	} else {
396
-		if ($decal > 3600 * 24 * 7) {
397
-			$semaines = floor($decal / (3600 * 24 * 7));
398
-			if ($semaines < 2) {
399
-				$delai = "$semaines " . _T('date_une_semaine');
400
-			} else {
401
-				$delai = "$semaines " . _T('date_semaines');
402
-			}
403
-		} else {
404
-			if ($decal > 3600 * 24) {
405
-				$jours = floor($decal / (3600 * 24));
406
-				if ($jours < 2) {
407
-					return $il_y_a == 'date_dans' ? _T('date_demain') : _T('date_hier');
408
-				} else {
409
-					$delai = "$jours " . _T('date_jours');
410
-				}
411
-			} else {
412
-				if ($decal >= 3600) {
413
-					$heures = floor($decal / 3600);
414
-					if ($heures < 2) {
415
-						$delai = "$heures " . _T('date_une_heure');
416
-					} else {
417
-						$delai = "$heures " . _T('date_heures');
418
-					}
419
-				} else {
420
-					if ($decal >= 60) {
421
-						$minutes = floor($decal / 60);
422
-						if ($minutes < 2) {
423
-							$delai = "$minutes " . _T('date_une_minute');
424
-						} else {
425
-							$delai = "$minutes " . _T('date_minutes');
426
-						}
427
-					} else {
428
-						$secondes = ceil($decal);
429
-						if ($secondes < 2) {
430
-							$delai = "$secondes " . _T('date_une_seconde');
431
-						} else {
432
-							$delai = "$secondes " . _T('date_secondes');
433
-						}
434
-					}
435
-				}
436
-			}
437
-		}
438
-	}
439
-
440
-	return _T($il_y_a, ['delai' => $delai]);
361
+    if (!$date) {
362
+        return '';
363
+    }
364
+
365
+    if (is_null($ref_date)) {
366
+        $ref_time = time();
367
+    } else {
368
+        $ref_time = strtotime($ref_date);
369
+    }
370
+
371
+    $decal = date('U', $ref_time) - date('U', strtotime($date));
372
+
373
+    if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
374
+        return '';
375
+    }
376
+
377
+    if ($decal < 0) {
378
+        $il_y_a = 'date_dans';
379
+        $decal = -1 * $decal;
380
+    } else {
381
+        $il_y_a = 'date_il_y_a';
382
+    }
383
+
384
+    if ($decal > 3600 * 24 * 30 * 6) {
385
+        return affdate_court($date);
386
+    }
387
+
388
+    if ($decal > 3600 * 24 * 30) {
389
+        $mois = floor($decal / (3600 * 24 * 30));
390
+        if ($mois < 2) {
391
+            $delai = "$mois " . _T('date_un_mois');
392
+        } else {
393
+            $delai = "$mois " . _T('date_mois');
394
+        }
395
+    } else {
396
+        if ($decal > 3600 * 24 * 7) {
397
+            $semaines = floor($decal / (3600 * 24 * 7));
398
+            if ($semaines < 2) {
399
+                $delai = "$semaines " . _T('date_une_semaine');
400
+            } else {
401
+                $delai = "$semaines " . _T('date_semaines');
402
+            }
403
+        } else {
404
+            if ($decal > 3600 * 24) {
405
+                $jours = floor($decal / (3600 * 24));
406
+                if ($jours < 2) {
407
+                    return $il_y_a == 'date_dans' ? _T('date_demain') : _T('date_hier');
408
+                } else {
409
+                    $delai = "$jours " . _T('date_jours');
410
+                }
411
+            } else {
412
+                if ($decal >= 3600) {
413
+                    $heures = floor($decal / 3600);
414
+                    if ($heures < 2) {
415
+                        $delai = "$heures " . _T('date_une_heure');
416
+                    } else {
417
+                        $delai = "$heures " . _T('date_heures');
418
+                    }
419
+                } else {
420
+                    if ($decal >= 60) {
421
+                        $minutes = floor($decal / 60);
422
+                        if ($minutes < 2) {
423
+                            $delai = "$minutes " . _T('date_une_minute');
424
+                        } else {
425
+                            $delai = "$minutes " . _T('date_minutes');
426
+                        }
427
+                    } else {
428
+                        $secondes = ceil($decal);
429
+                        if ($secondes < 2) {
430
+                            $delai = "$secondes " . _T('date_une_seconde');
431
+                        } else {
432
+                            $delai = "$secondes " . _T('date_secondes');
433
+                        }
434
+                    }
435
+                }
436
+            }
437
+        }
438
+    }
439
+
440
+    return _T($il_y_a, ['delai' => $delai]);
441 441
 }
442 442
 
443 443
 
@@ -463,32 +463,32 @@  discard block
 block discarded – undo
463 463
  **/
464 464
 function date_relativecourt($date, $decalage_maxi = 0): string {
465 465
 
466
-	if (!$date) {
467
-		return '';
468
-	}
469
-	$decal = date('U', strtotime(date('Y-m-d')) - strtotime(date('Y-m-d', strtotime($date))));
470
-
471
-	if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
472
-		return '';
473
-	}
474
-
475
-	if ($decal < -24 * 3600) {
476
-		$retour = date_relative($date, $decalage_maxi);
477
-	} elseif ($decal < 0) {
478
-		$retour = _T('date_demain');
479
-	} else {
480
-		if ($decal < (3600 * 24)) {
481
-			$retour = _T('date_aujourdhui');
482
-		} else {
483
-			if ($decal < (3600 * 24 * 2)) {
484
-				$retour = _T('date_hier');
485
-			} else {
486
-				$retour = date_relative($date, $decalage_maxi);
487
-			}
488
-		}
489
-	}
490
-
491
-	return $retour;
466
+    if (!$date) {
467
+        return '';
468
+    }
469
+    $decal = date('U', strtotime(date('Y-m-d')) - strtotime(date('Y-m-d', strtotime($date))));
470
+
471
+    if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
472
+        return '';
473
+    }
474
+
475
+    if ($decal < -24 * 3600) {
476
+        $retour = date_relative($date, $decalage_maxi);
477
+    } elseif ($decal < 0) {
478
+        $retour = _T('date_demain');
479
+    } else {
480
+        if ($decal < (3600 * 24)) {
481
+            $retour = _T('date_aujourdhui');
482
+        } else {
483
+            if ($decal < (3600 * 24 * 2)) {
484
+                $retour = _T('date_hier');
485
+            } else {
486
+                $retour = date_relative($date, $decalage_maxi);
487
+            }
488
+        }
489
+    }
490
+
491
+    return $retour;
492 492
 }
493 493
 
494 494
 /**
@@ -505,174 +505,174 @@  discard block
 block discarded – undo
505 505
  * @return string
506 506
  */
507 507
 function affdate_base($numdate, $vue, $options = []): string {
508
-	if (is_string($options)) {
509
-		$options = ['param' => $options];
510
-	}
511
-	$date_array = recup_date($numdate, false);
512
-	if (!$date_array) {
513
-		return '';
514
-	}
515
-	[$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
516
-
517
-	// 1er, 21st, etc.
518
-	$journum = $jour;
519
-
520
-	if ($jour == 0) {
521
-		$jour = '';
522
-		$njour = 0;
523
-	} else {
524
-		$njour = intval($jour);
525
-		if ($jourth = _T('date_jnum' . $jour)) {
526
-			$jour = $jourth;
527
-		}
528
-	}
529
-
530
-	$mois = intval($mois);
531
-	if ($mois > 0 and $mois < 13) {
532
-		/* Traiter le cas "abbr" pour les noms de mois */
533
-		$param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_' . $options['param'] : '');
534
-		$nommois = _T('date_mois_' . $mois . $param);
535
-		if ($jour) {
536
-			$jourmois = _T('date_de_mois_' . $mois, ['j' => $jour, 'nommois' => $nommois]);
537
-		} else {
538
-			$jourmois = $nommois;
539
-		}
540
-	} else {
541
-		$nommois = '';
542
-		$jourmois = '';
543
-	}
544
-
545
-	if ($annee < 0) {
546
-		$annee = -$annee . ' ' . _T('date_avant_jc');
547
-		$avjc = true;
548
-	} else {
549
-		$avjc = false;
550
-	}
551
-
552
-	switch ($vue) {
553
-		case 'saison':
554
-		case 'saison_annee':
555
-			$saison = '';
556
-			if ($mois > 0) {
557
-				$saison = ($options['param'] == 'sud') ? 3 : 1;
558
-				if (($mois == 3 and $jour >= 21) or $mois > 3) {
559
-					$saison = ($options['param'] == 'sud') ? 4 : 2;
560
-				}
561
-				if (($mois == 6 and $jour >= 21) or $mois > 6) {
562
-					$saison = ($options['param'] == 'sud') ? 1 : 3;
563
-				}
564
-				if (($mois == 9 and $jour >= 21) or $mois > 9) {
565
-					$saison = ($options['param'] == 'sud') ? 2 : 4;
566
-				}
567
-				if (($mois == 12 and $jour >= 21) or $mois > 12) {
568
-					$saison = ($options['param'] == 'sud') ? 3 : 1;
569
-				}
570
-			}
571
-			if ($vue == 'saison') {
572
-				return $saison ? _T('date_saison_' . $saison) : '';
573
-			} else {
574
-				return $saison ? trim(_T(
575
-					'date_fmt_saison_annee',
576
-					['saison' => _T('date_saison_' . $saison), 'annee' => $annee]
577
-				)) : '';
578
-			}
579
-
580
-		case 'court':
581
-			if ($avjc) {
582
-				return $annee;
583
-			}
584
-			$a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
585
-			if ($annee < ($a - 100) or $annee > ($a + 100)) {
586
-				return $annee;
587
-			}
588
-			if ($annee != $a) {
589
-				return _T(
590
-					'date_fmt_mois_annee',
591
-					['mois' => $mois, 'nommois' => spip_ucfirst($nommois), 'annee' => $annee]
592
-				);
593
-			}
594
-
595
-			return _T(
596
-				'date_fmt_jour_mois',
597
-				['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
598
-			);
599
-
600
-		case 'jourcourt':
601
-			if ($avjc) {
602
-				return $annee;
603
-			}
604
-			$a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
605
-			if ($annee < ($a - 100) or $annee > ($a + 100)) {
606
-				return $annee;
607
-			}
608
-			if ($annee != $a) {
609
-				return _T(
610
-					'date_fmt_jour_mois_annee',
611
-					['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
612
-				);
613
-			}
614
-
615
-			return _T(
616
-				'date_fmt_jour_mois',
617
-				['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
618
-			);
619
-
620
-		case 'entier':
621
-			if ($avjc) {
622
-				return $annee;
623
-			}
624
-			if ($jour) {
625
-				return _T(
626
-					'date_fmt_jour_mois_annee',
627
-					['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
628
-				);
629
-			} elseif ($mois) {
630
-				return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
631
-			} else {
632
-				return $annee;
633
-			}
634
-
635
-		case 'nom_mois':
636
-			return $nommois;
637
-
638
-		case 'mois':
639
-			return sprintf('%02s', $mois);
640
-
641
-		case 'jour':
642
-			return $jour;
643
-
644
-		case 'journum':
645
-			return $journum;
646
-
647
-		case 'nom_jour':
648
-			if (!$mois or !$njour) {
649
-				return '';
650
-			}
651
-			$nom = mktime(1, 1, 1, $mois, $njour, $annee);
652
-			$nom = 1 + (int) date('w', $nom);
653
-			$param = ((isset($options['param']) and $options['param']) ? '_' . $options['param'] : '');
654
-
655
-			return _T('date_jour_' . $nom . $param);
656
-
657
-		case 'mois_annee':
658
-			if ($avjc) {
659
-				return $annee;
660
-			}
661
-
662
-			return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
663
-
664
-		case 'annee':
665
-			return $annee;
666
-
667
-		// Cas d'une vue non definie : retomber sur le format
668
-		// de date propose par http://www.php.net/date
669
-		default:
670
-			[$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
671
-			if (!$time = mktime($heures, $minutes, $secondes, $mois, (int) $jour, $annee)) {
672
-				$time = strtotime($numdate);
673
-			}
674
-			return date($vue, $time);
675
-	}
508
+    if (is_string($options)) {
509
+        $options = ['param' => $options];
510
+    }
511
+    $date_array = recup_date($numdate, false);
512
+    if (!$date_array) {
513
+        return '';
514
+    }
515
+    [$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
516
+
517
+    // 1er, 21st, etc.
518
+    $journum = $jour;
519
+
520
+    if ($jour == 0) {
521
+        $jour = '';
522
+        $njour = 0;
523
+    } else {
524
+        $njour = intval($jour);
525
+        if ($jourth = _T('date_jnum' . $jour)) {
526
+            $jour = $jourth;
527
+        }
528
+    }
529
+
530
+    $mois = intval($mois);
531
+    if ($mois > 0 and $mois < 13) {
532
+        /* Traiter le cas "abbr" pour les noms de mois */
533
+        $param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_' . $options['param'] : '');
534
+        $nommois = _T('date_mois_' . $mois . $param);
535
+        if ($jour) {
536
+            $jourmois = _T('date_de_mois_' . $mois, ['j' => $jour, 'nommois' => $nommois]);
537
+        } else {
538
+            $jourmois = $nommois;
539
+        }
540
+    } else {
541
+        $nommois = '';
542
+        $jourmois = '';
543
+    }
544
+
545
+    if ($annee < 0) {
546
+        $annee = -$annee . ' ' . _T('date_avant_jc');
547
+        $avjc = true;
548
+    } else {
549
+        $avjc = false;
550
+    }
551
+
552
+    switch ($vue) {
553
+        case 'saison':
554
+        case 'saison_annee':
555
+            $saison = '';
556
+            if ($mois > 0) {
557
+                $saison = ($options['param'] == 'sud') ? 3 : 1;
558
+                if (($mois == 3 and $jour >= 21) or $mois > 3) {
559
+                    $saison = ($options['param'] == 'sud') ? 4 : 2;
560
+                }
561
+                if (($mois == 6 and $jour >= 21) or $mois > 6) {
562
+                    $saison = ($options['param'] == 'sud') ? 1 : 3;
563
+                }
564
+                if (($mois == 9 and $jour >= 21) or $mois > 9) {
565
+                    $saison = ($options['param'] == 'sud') ? 2 : 4;
566
+                }
567
+                if (($mois == 12 and $jour >= 21) or $mois > 12) {
568
+                    $saison = ($options['param'] == 'sud') ? 3 : 1;
569
+                }
570
+            }
571
+            if ($vue == 'saison') {
572
+                return $saison ? _T('date_saison_' . $saison) : '';
573
+            } else {
574
+                return $saison ? trim(_T(
575
+                    'date_fmt_saison_annee',
576
+                    ['saison' => _T('date_saison_' . $saison), 'annee' => $annee]
577
+                )) : '';
578
+            }
579
+
580
+        case 'court':
581
+            if ($avjc) {
582
+                return $annee;
583
+            }
584
+            $a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
585
+            if ($annee < ($a - 100) or $annee > ($a + 100)) {
586
+                return $annee;
587
+            }
588
+            if ($annee != $a) {
589
+                return _T(
590
+                    'date_fmt_mois_annee',
591
+                    ['mois' => $mois, 'nommois' => spip_ucfirst($nommois), 'annee' => $annee]
592
+                );
593
+            }
594
+
595
+            return _T(
596
+                'date_fmt_jour_mois',
597
+                ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
598
+            );
599
+
600
+        case 'jourcourt':
601
+            if ($avjc) {
602
+                return $annee;
603
+            }
604
+            $a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
605
+            if ($annee < ($a - 100) or $annee > ($a + 100)) {
606
+                return $annee;
607
+            }
608
+            if ($annee != $a) {
609
+                return _T(
610
+                    'date_fmt_jour_mois_annee',
611
+                    ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
612
+                );
613
+            }
614
+
615
+            return _T(
616
+                'date_fmt_jour_mois',
617
+                ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
618
+            );
619
+
620
+        case 'entier':
621
+            if ($avjc) {
622
+                return $annee;
623
+            }
624
+            if ($jour) {
625
+                return _T(
626
+                    'date_fmt_jour_mois_annee',
627
+                    ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
628
+                );
629
+            } elseif ($mois) {
630
+                return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
631
+            } else {
632
+                return $annee;
633
+            }
634
+
635
+        case 'nom_mois':
636
+            return $nommois;
637
+
638
+        case 'mois':
639
+            return sprintf('%02s', $mois);
640
+
641
+        case 'jour':
642
+            return $jour;
643
+
644
+        case 'journum':
645
+            return $journum;
646
+
647
+        case 'nom_jour':
648
+            if (!$mois or !$njour) {
649
+                return '';
650
+            }
651
+            $nom = mktime(1, 1, 1, $mois, $njour, $annee);
652
+            $nom = 1 + (int) date('w', $nom);
653
+            $param = ((isset($options['param']) and $options['param']) ? '_' . $options['param'] : '');
654
+
655
+            return _T('date_jour_' . $nom . $param);
656
+
657
+        case 'mois_annee':
658
+            if ($avjc) {
659
+                return $annee;
660
+            }
661
+
662
+            return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
663
+
664
+        case 'annee':
665
+            return $annee;
666
+
667
+        // Cas d'une vue non definie : retomber sur le format
668
+        // de date propose par http://www.php.net/date
669
+        default:
670
+            [$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
671
+            if (!$time = mktime($heures, $minutes, $secondes, $mois, (int) $jour, $annee)) {
672
+                $time = strtotime($numdate);
673
+            }
674
+            return date($vue, $time);
675
+    }
676 676
 }
677 677
 
678 678
 
@@ -699,11 +699,11 @@  discard block
 block discarded – undo
699 699
  *     Nom du jour
700 700
  **/
701 701
 function nom_jour($numdate, $forme = ''): string {
702
-	if (!($forme === 'abbr' or $forme === 'initiale')) {
703
-		$forme = '';
704
-	}
702
+    if (!($forme === 'abbr' or $forme === 'initiale')) {
703
+        $forme = '';
704
+    }
705 705
 
706
-	return affdate_base($numdate, 'nom_jour', ['param' => $forme]);
706
+    return affdate_base($numdate, 'nom_jour', ['param' => $forme]);
707 707
 }
708 708
 
709 709
 /**
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
  *     Numéro du jour
726 726
  **/
727 727
 function jour($numdate): string {
728
-	return affdate_base($numdate, 'jour');
728
+    return affdate_base($numdate, 'jour');
729 729
 }
730 730
 
731 731
 /**
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
  *     Numéro du jour
744 744
  **/
745 745
 function journum($numdate): string {
746
-	return affdate_base($numdate, 'journum');
746
+    return affdate_base($numdate, 'journum');
747 747
 }
748 748
 
749 749
 /**
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
  *     Numéro du mois (sur 2 chiffres)
762 762
  **/
763 763
 function mois($numdate): string {
764
-	return  affdate_base($numdate, 'mois');
764
+    return  affdate_base($numdate, 'mois');
765 765
 }
766 766
 
767 767
 /**
@@ -785,11 +785,11 @@  discard block
 block discarded – undo
785 785
  *     Nom du mois
786 786
  **/
787 787
 function nom_mois($numdate, $forme = ''): string {
788
-	if (!($forme === 'abbr')) {
789
-		$forme = '';
790
-	}
788
+    if (!($forme === 'abbr')) {
789
+        $forme = '';
790
+    }
791 791
 
792
-	return affdate_base($numdate, 'nom_mois', ['param' => $forme]);
792
+    return affdate_base($numdate, 'nom_mois', ['param' => $forme]);
793 793
 }
794 794
 
795 795
 /**
@@ -807,7 +807,7 @@  discard block
 block discarded – undo
807 807
  *     Année (sur 4 chiffres)
808 808
  **/
809 809
 function annee($numdate): string {
810
-	return affdate_base($numdate, 'annee');
810
+    return affdate_base($numdate, 'annee');
811 811
 }
812 812
 
813 813
 
@@ -837,11 +837,11 @@  discard block
 block discarded – undo
837 837
  *     La date formatée
838 838
  **/
839 839
 function saison($numdate, $hemisphere = 'nord'): string {
840
-	if ($hemisphere !== 'sud') {
841
-		$hemisphere = 'nord';
842
-	}
840
+    if ($hemisphere !== 'sud') {
841
+        $hemisphere = 'nord';
842
+    }
843 843
 
844
-	return affdate_base($numdate, 'saison', ['param' => $hemisphere]);
844
+    return affdate_base($numdate, 'saison', ['param' => $hemisphere]);
845 845
 }
846 846
 
847 847
 
@@ -870,11 +870,11 @@  discard block
 block discarded – undo
870 870
  *     La date formatée
871 871
  **/
872 872
 function saison_annee($numdate, $hemisphere = 'nord'): string {
873
-	if ($hemisphere !== 'sud') {
874
-		$hemisphere = 'nord';
875
-	}
873
+    if ($hemisphere !== 'sud') {
874
+        $hemisphere = 'nord';
875
+    }
876 876
 
877
-	return affdate_base($numdate, 'saison_annee', ['param' => $hemisphere]);
877
+    return affdate_base($numdate, 'saison_annee', ['param' => $hemisphere]);
878 878
 }
879 879
 
880 880
 /**
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
  *     La date formatée
903 903
  **/
904 904
 function affdate($numdate, $format = 'entier'): string {
905
-	return affdate_base($numdate, $format);
905
+    return affdate_base($numdate, $format);
906 906
 }
907 907
 
908 908
 
@@ -929,7 +929,7 @@  discard block
 block discarded – undo
929 929
  *     La date formatée
930 930
  **/
931 931
 function affdate_court($numdate, $annee_courante = null): string {
932
-	return affdate_base($numdate, 'court', ['annee_courante' => $annee_courante]);
932
+    return affdate_base($numdate, 'court', ['annee_courante' => $annee_courante]);
933 933
 }
934 934
 
935 935
 
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
  *     La date formatée
957 957
  **/
958 958
 function affdate_jourcourt($numdate, $annee_courante = null): string {
959
-	return affdate_base($numdate, 'jourcourt', ['annee_courante' => $annee_courante]);
959
+    return affdate_base($numdate, 'jourcourt', ['annee_courante' => $annee_courante]);
960 960
 }
961 961
 
962 962
 /**
@@ -974,7 +974,7 @@  discard block
 block discarded – undo
974 974
  *     La date formatée
975 975
  **/
976 976
 function affdate_mois_annee($numdate): string {
977
-	return affdate_base($numdate, 'mois_annee');
977
+    return affdate_base($numdate, 'mois_annee');
978 978
 }
979 979
 
980 980
 /**
@@ -992,16 +992,16 @@  discard block
 block discarded – undo
992 992
  *     La date formatée, sinon ''
993 993
  **/
994 994
 function affdate_heure($numdate): string {
995
-	$date_array = recup_date($numdate);
996
-	if (!$date_array) {
997
-		return '';
998
-	}
999
-	[$annee, $mois, $jour, $heures, $minutes, $sec] = $date_array;
1000
-
1001
-	return _T('date_fmt_jour_heure', [
1002
-		'jour' => affdate($numdate),
1003
-		'heure' => _T('date_fmt_heures_minutes', ['h' => $heures, 'm' => $minutes])
1004
-	]);
995
+    $date_array = recup_date($numdate);
996
+    if (!$date_array) {
997
+        return '';
998
+    }
999
+    [$annee, $mois, $jour, $heures, $minutes, $sec] = $date_array;
1000
+
1001
+    return _T('date_fmt_jour_heure', [
1002
+        'jour' => affdate($numdate),
1003
+        'heure' => _T('date_fmt_heures_minutes', ['h' => $heures, 'm' => $minutes])
1004
+    ]);
1005 1005
 }
1006 1006
 
1007 1007
 /**
@@ -1033,117 +1033,117 @@  discard block
 block discarded – undo
1033 1033
  *     texte de la date
1034 1034
  */
1035 1035
 function affdate_debut_fin($date_debut, $date_fin, $horaire = 'oui', $forme = ''): string {
1036
-	$abbr = $jour = '';
1037
-	$affdate = 'affdate_jourcourt';
1038
-	if (strpos($forme, 'abbr') !== false) {
1039
-		$abbr = 'abbr';
1040
-	}
1041
-	if (strpos($forme, 'annee') !== false) {
1042
-		$affdate = 'affdate';
1043
-	}
1044
-	if (strpos($forme, 'jour') !== false) {
1045
-		$jour = 'jour';
1046
-	}
1047
-
1048
-	$dtstart = $dtend = $dtabbr = '';
1049
-	if (strpos($forme, 'hcal') !== false) {
1050
-		$dtstart = "<abbr class='dtstart' title='" . date_iso($date_debut) . "'>";
1051
-		$dtend = "<abbr class='dtend' title='" . date_iso($date_fin) . "'>";
1052
-		$dtabbr = '</abbr>';
1053
-	}
1054
-
1055
-	$date_debut = strtotime($date_debut);
1056
-	$date_fin = strtotime($date_fin);
1057
-	$d = date('Y-m-d', $date_debut);
1058
-	$f = date('Y-m-d', $date_fin);
1059
-	$h = ($horaire === 'oui' or $horaire === true);
1060
-	$hd = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_debut), 'm' => date('i', $date_debut)]);
1061
-	$hf = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_fin), 'm' => date('i', $date_fin)]);
1062
-
1063
-	if ($d == $f) { // meme jour
1064
-		$nomjour = nom_jour($d, $abbr);
1065
-		$s = $affdate($d);
1066
-		$s = _T('date_fmt_jour', ['nomjour' => $nomjour, 'jour' => $s]);
1067
-		if ($h) {
1068
-			if ($hd == $hf) {
1069
-				// Lundi 20 fevrier a 18h25
1070
-				$s = spip_ucfirst(_T('date_fmt_jour_heure', ['jour' => $s, 'heure' => $hd]));
1071
-				$s = "$dtstart$s$dtabbr";
1072
-			} else {
1073
-				// Le <abbr...>lundi 20 fevrier de 18h00</abbr> a <abbr...>20h00</abbr>
1074
-				if ($dtabbr && $dtstart && $dtend) {
1075
-					$s = _T(
1076
-						'date_fmt_jour_heure_debut_fin_abbr',
1077
-						[
1078
-						'jour' => spip_ucfirst($s),
1079
-						'heure_debut' => $hd,
1080
-						'heure_fin' => $hf,
1081
-						'dtstart' => $dtstart,
1082
-						'dtend' => $dtend,
1083
-						'dtabbr' => $dtabbr
1084
-						],
1085
-						[
1086
-							'sanitize' => false
1087
-						]
1088
-					);
1089
-				} // Le lundi 20 fevrier de 18h00 a 20h00
1090
-				else {
1091
-					$s = spip_ucfirst(_T(
1092
-						'date_fmt_jour_heure_debut_fin',
1093
-						['jour' => $s, 'heure_debut' => $hd, 'heure_fin' => $hf]
1094
-					));
1095
-				}
1096
-			}
1097
-		} else {
1098
-			if ($dtabbr && $dtstart) {
1099
-				$s = $dtstart . spip_ucfirst($s) . $dtabbr;
1100
-			} else {
1101
-				$s = spip_ucfirst($s);
1102
-			}
1103
-		}
1104
-	} else {
1105
-		if ((date('Y-m', $date_debut)) == date('Y-m', $date_fin)) { // meme annee et mois, jours differents
1106
-			if (!$h) {
1107
-				$date_debut = jour($d);
1108
-			} else {
1109
-				$date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1110
-			}
1111
-			$date_fin = $affdate($f);
1112
-			if ($jour) {
1113
-				$nomjour_debut = nom_jour($d, $abbr);
1114
-				$date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1115
-				$nomjour_fin = nom_jour($f, $abbr);
1116
-				$date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1117
-			}
1118
-			if ($h) {
1119
-				$date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1120
-				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1121
-			}
1122
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1123
-			$date_fin = $dtend . $date_fin . $dtabbr;
1124
-
1125
-			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1126
-		} else {
1127
-			$date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1128
-			$date_fin = $affdate($f);
1129
-			if ($jour) {
1130
-				$nomjour_debut = nom_jour($d, $abbr);
1131
-				$date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1132
-				$nomjour_fin = nom_jour($f, $abbr);
1133
-				$date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1134
-			}
1135
-			if ($h) {
1136
-				$date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1137
-				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1138
-			}
1139
-
1140
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1141
-			$date_fin = $dtend . $date_fin . $dtabbr;
1142
-			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1143
-		}
1144
-	}
1145
-
1146
-	return $s;
1036
+    $abbr = $jour = '';
1037
+    $affdate = 'affdate_jourcourt';
1038
+    if (strpos($forme, 'abbr') !== false) {
1039
+        $abbr = 'abbr';
1040
+    }
1041
+    if (strpos($forme, 'annee') !== false) {
1042
+        $affdate = 'affdate';
1043
+    }
1044
+    if (strpos($forme, 'jour') !== false) {
1045
+        $jour = 'jour';
1046
+    }
1047
+
1048
+    $dtstart = $dtend = $dtabbr = '';
1049
+    if (strpos($forme, 'hcal') !== false) {
1050
+        $dtstart = "<abbr class='dtstart' title='" . date_iso($date_debut) . "'>";
1051
+        $dtend = "<abbr class='dtend' title='" . date_iso($date_fin) . "'>";
1052
+        $dtabbr = '</abbr>';
1053
+    }
1054
+
1055
+    $date_debut = strtotime($date_debut);
1056
+    $date_fin = strtotime($date_fin);
1057
+    $d = date('Y-m-d', $date_debut);
1058
+    $f = date('Y-m-d', $date_fin);
1059
+    $h = ($horaire === 'oui' or $horaire === true);
1060
+    $hd = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_debut), 'm' => date('i', $date_debut)]);
1061
+    $hf = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_fin), 'm' => date('i', $date_fin)]);
1062
+
1063
+    if ($d == $f) { // meme jour
1064
+        $nomjour = nom_jour($d, $abbr);
1065
+        $s = $affdate($d);
1066
+        $s = _T('date_fmt_jour', ['nomjour' => $nomjour, 'jour' => $s]);
1067
+        if ($h) {
1068
+            if ($hd == $hf) {
1069
+                // Lundi 20 fevrier a 18h25
1070
+                $s = spip_ucfirst(_T('date_fmt_jour_heure', ['jour' => $s, 'heure' => $hd]));
1071
+                $s = "$dtstart$s$dtabbr";
1072
+            } else {
1073
+                // Le <abbr...>lundi 20 fevrier de 18h00</abbr> a <abbr...>20h00</abbr>
1074
+                if ($dtabbr && $dtstart && $dtend) {
1075
+                    $s = _T(
1076
+                        'date_fmt_jour_heure_debut_fin_abbr',
1077
+                        [
1078
+                        'jour' => spip_ucfirst($s),
1079
+                        'heure_debut' => $hd,
1080
+                        'heure_fin' => $hf,
1081
+                        'dtstart' => $dtstart,
1082
+                        'dtend' => $dtend,
1083
+                        'dtabbr' => $dtabbr
1084
+                        ],
1085
+                        [
1086
+                            'sanitize' => false
1087
+                        ]
1088
+                    );
1089
+                } // Le lundi 20 fevrier de 18h00 a 20h00
1090
+                else {
1091
+                    $s = spip_ucfirst(_T(
1092
+                        'date_fmt_jour_heure_debut_fin',
1093
+                        ['jour' => $s, 'heure_debut' => $hd, 'heure_fin' => $hf]
1094
+                    ));
1095
+                }
1096
+            }
1097
+        } else {
1098
+            if ($dtabbr && $dtstart) {
1099
+                $s = $dtstart . spip_ucfirst($s) . $dtabbr;
1100
+            } else {
1101
+                $s = spip_ucfirst($s);
1102
+            }
1103
+        }
1104
+    } else {
1105
+        if ((date('Y-m', $date_debut)) == date('Y-m', $date_fin)) { // meme annee et mois, jours differents
1106
+            if (!$h) {
1107
+                $date_debut = jour($d);
1108
+            } else {
1109
+                $date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1110
+            }
1111
+            $date_fin = $affdate($f);
1112
+            if ($jour) {
1113
+                $nomjour_debut = nom_jour($d, $abbr);
1114
+                $date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1115
+                $nomjour_fin = nom_jour($f, $abbr);
1116
+                $date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1117
+            }
1118
+            if ($h) {
1119
+                $date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1120
+                $date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1121
+            }
1122
+            $date_debut = $dtstart . $date_debut . $dtabbr;
1123
+            $date_fin = $dtend . $date_fin . $dtabbr;
1124
+
1125
+            $s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1126
+        } else {
1127
+            $date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1128
+            $date_fin = $affdate($f);
1129
+            if ($jour) {
1130
+                $nomjour_debut = nom_jour($d, $abbr);
1131
+                $date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1132
+                $nomjour_fin = nom_jour($f, $abbr);
1133
+                $date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1134
+            }
1135
+            if ($h) {
1136
+                $date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1137
+                $date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1138
+            }
1139
+
1140
+            $date_debut = $dtstart . $date_debut . $dtabbr;
1141
+            $date_fin = $dtend . $date_fin . $dtabbr;
1142
+            $s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1143
+        }
1144
+    }
1145
+
1146
+    return $s;
1147 1147
 }
1148 1148
 
1149 1149
 /**
@@ -1164,10 +1164,10 @@  discard block
 block discarded – undo
1164 1164
  *     Date au format ical
1165 1165
  **/
1166 1166
 function date_ical($date, $addminutes = 0): string {
1167
-	[$heures, $minutes, $secondes] = recup_heure($date);
1168
-	[$annee, $mois, $jour] = recup_date($date);
1167
+    [$heures, $minutes, $secondes] = recup_heure($date);
1168
+    [$annee, $mois, $jour] = recup_date($date);
1169 1169
 
1170
-	return gmdate('Ymd\THis\Z', mktime($heures, $minutes + $addminutes, $secondes, $mois, $jour, $annee));
1170
+    return gmdate('Ymd\THis\Z', mktime($heures, $minutes + $addminutes, $secondes, $mois, $jour, $annee));
1171 1171
 }
1172 1172
 
1173 1173
 
@@ -1191,11 +1191,11 @@  discard block
 block discarded – undo
1191 1191
  *     La date formatée
1192 1192
  **/
1193 1193
 function date_iso($date_heure): string {
1194
-	[$annee, $mois, $jour] = recup_date($date_heure);
1195
-	[$heures, $minutes, $secondes] = recup_heure($date_heure);
1196
-	$time = @mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1194
+    [$annee, $mois, $jour] = recup_date($date_heure);
1195
+    [$heures, $minutes, $secondes] = recup_heure($date_heure);
1196
+    $time = @mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1197 1197
 
1198
-	return gmdate('Y-m-d\TH:i:s\Z', $time);
1198
+    return gmdate('Y-m-d\TH:i:s\Z', $time);
1199 1199
 }
1200 1200
 
1201 1201
 /**
@@ -1218,11 +1218,11 @@  discard block
 block discarded – undo
1218 1218
  *     La date formatée
1219 1219
  **/
1220 1220
 function date_822($date_heure): string {
1221
-	[$annee, $mois, $jour] = recup_date($date_heure);
1222
-	[$heures, $minutes, $secondes] = recup_heure($date_heure);
1223
-	$time = mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1221
+    [$annee, $mois, $jour] = recup_date($date_heure);
1222
+    [$heures, $minutes, $secondes] = recup_heure($date_heure);
1223
+    $time = mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1224 1224
 
1225
-	return date('r', $time);
1225
+    return date('r', $time);
1226 1226
 }
1227 1227
 
1228 1228
 /**
@@ -1238,11 +1238,11 @@  discard block
 block discarded – undo
1238 1238
  *     Date au format `Ymd`
1239 1239
  **/
1240 1240
 function date_anneemoisjour($d): string {
1241
-	if (!$d) {
1242
-		$d = date('Y-m-d');
1243
-	}
1241
+    if (!$d) {
1242
+        $d = date('Y-m-d');
1243
+    }
1244 1244
 
1245
-	return substr($d, 0, 4) . substr($d, 5, 2) . substr($d, 8, 2);
1245
+    return substr($d, 0, 4) . substr($d, 5, 2) . substr($d, 8, 2);
1246 1246
 }
1247 1247
 
1248 1248
 /**
@@ -1258,11 +1258,11 @@  discard block
 block discarded – undo
1258 1258
  *     Date au format `Ym`
1259 1259
  **/
1260 1260
 function date_anneemois($d): string {
1261
-	if (!$d) {
1262
-		$d = date('Y-m-d');
1263
-	}
1261
+    if (!$d) {
1262
+        $d = date('Y-m-d');
1263
+    }
1264 1264
 
1265
-	return substr($d, 0, 4) . substr($d, 5, 2);
1265
+    return substr($d, 0, 4) . substr($d, 5, 2);
1266 1266
 }
1267 1267
 
1268 1268
 /**
@@ -1278,13 +1278,13 @@  discard block
 block discarded – undo
1278 1278
  *     Date au lundi de la même semaine au format `Ymd`
1279 1279
  **/
1280 1280
 function date_debut_semaine($annee, $mois, $jour): string {
1281
-	$w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1282
-	if ($w_day == 0) {
1283
-		$w_day = 7;
1284
-	} // Gaffe: le dimanche est zero
1285
-	$debut = $jour - $w_day + 1;
1281
+    $w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1282
+    if ($w_day == 0) {
1283
+        $w_day = 7;
1284
+    } // Gaffe: le dimanche est zero
1285
+    $debut = $jour - $w_day + 1;
1286 1286
 
1287
-	return date('Ymd', mktime(0, 0, 0, $mois, $debut, $annee));
1287
+    return date('Ymd', mktime(0, 0, 0, $mois, $debut, $annee));
1288 1288
 }
1289 1289
 
1290 1290
 /**
@@ -1300,11 +1300,11 @@  discard block
 block discarded – undo
1300 1300
  *     Date au dimanche de la même semaine au format `Ymd`
1301 1301
  **/
1302 1302
 function date_fin_semaine($annee, $mois, $jour): string {
1303
-	$w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1304
-	if ($w_day == 0) {
1305
-		$w_day = 7;
1306
-	} // Gaffe: le dimanche est zero
1307
-	$debut = $jour - $w_day + 1;
1303
+    $w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1304
+    if ($w_day == 0) {
1305
+        $w_day = 7;
1306
+    } // Gaffe: le dimanche est zero
1307
+    $debut = $jour - $w_day + 1;
1308 1308
 
1309
-	return date('Ymd', mktime(0, 0, 0, $mois, $debut + 6, $annee));
1309
+    return date('Ymd', mktime(0, 0, 0, $mois, $debut + 6, $annee));
1310 1310
 }
Please login to merge, or discard this patch.
ecrire/inc/texte.php 1 patch
Indentation   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 include_spip('inc/texte_mini');
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  * @return array Tablea ('','')
35 35
  */
36 36
 function definir_raccourcis_alineas() {
37
-	return ['', ''];
37
+    return ['', ''];
38 38
 }
39 39
 
40 40
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  * @return string
48 48
  */
49 49
 function traiter_tableau($bloc) {
50
-	return $bloc;
50
+    return $bloc;
51 51
 }
52 52
 
53 53
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
  * @return string
62 62
  */
63 63
 function traiter_listes($texte) {
64
-	return $texte;
64
+    return $texte;
65 65
 }
66 66
 
67 67
 /**
@@ -77,16 +77,16 @@  discard block
 block discarded – undo
77 77
  */
78 78
 function traiter_raccourcis($letexte) {
79 79
 
80
-	// Appeler les fonctions de pre_traitement
81
-	$letexte = pipeline('pre_propre', $letexte);
80
+    // Appeler les fonctions de pre_traitement
81
+    $letexte = pipeline('pre_propre', $letexte);
82 82
 
83
-	// APPELER ICI UN PIPELINE traiter_raccourcis ?
84
-	// $letexte = pipeline('traiter_raccourcis', $letexte);
83
+    // APPELER ICI UN PIPELINE traiter_raccourcis ?
84
+    // $letexte = pipeline('traiter_raccourcis', $letexte);
85 85
 
86
-	// Appeler les fonctions de post-traitement
87
-	$letexte = pipeline('post_propre', $letexte);
86
+    // Appeler les fonctions de post-traitement
87
+    $letexte = pipeline('post_propre', $letexte);
88 88
 
89
-	return $letexte;
89
+    return $letexte;
90 90
 }
91 91
 
92 92
 /*************************************************************************************************************************
@@ -102,22 +102,22 @@  discard block
 block discarded – undo
102 102
  * @return string
103 103
  */
104 104
 function echappe_js($t, $class = ' class = "echappe-js"') {
105
-	foreach (['script', 'iframe'] as $tag) {
106
-		if (
107
-			stripos($t, (string) "<$tag") !== false
108
-			and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
109
-		) {
110
-			foreach ($r as $regs) {
111
-				$t = str_replace(
112
-					$regs[0],
113
-					"<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
114
-					$t
115
-				);
116
-			}
117
-		}
118
-	}
119
-
120
-	return $t;
105
+    foreach (['script', 'iframe'] as $tag) {
106
+        if (
107
+            stripos($t, (string) "<$tag") !== false
108
+            and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
109
+        ) {
110
+            foreach ($r as $regs) {
111
+                $t = str_replace(
112
+                    $regs[0],
113
+                    "<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
114
+                    $t
115
+                );
116
+            }
117
+        }
118
+    }
119
+
120
+    return $t;
121 121
 }
122 122
 
123 123
 
@@ -146,55 +146,55 @@  discard block
 block discarded – undo
146 146
  *     Code protégé
147 147
  **/
148 148
 function interdire_scripts($arg, $mode_filtre = null) {
149
-	// on memorise le resultat sur les arguments non triviaux
150
-	static $dejavu = [];
151
-
152
-	// Attention, si ce n'est pas une chaine, laisser intact
153
-	if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
154
-		return $arg;
155
-	}
156
-
157
-	if (is_null($mode_filtre) or !in_array($mode_filtre, [-1, 0, 1])) {
158
-		$mode_filtre = $GLOBALS['filtrer_javascript'];
159
-	}
160
-
161
-	if (isset($dejavu[$mode_filtre][$arg])) {
162
-		return $dejavu[$mode_filtre][$arg];
163
-	}
164
-
165
-	// echapper les tags asp/php
166
-	$t = str_replace('<' . '%', '&lt;%', $arg);
167
-
168
-	// echapper le php
169
-	$t = str_replace('<' . '?', '&lt;?', $t);
170
-
171
-	// echapper le < script language=php >
172
-	$t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
173
-
174
-	// Pour le js, trois modes : parano (-1), prive (0), ok (1)
175
-	switch ($mode_filtre) {
176
-		case 0:
177
-			if (!_DIR_RESTREINT) {
178
-				$t = echappe_js($t);
179
-			}
180
-			break;
181
-		case -1:
182
-			$t = echappe_js($t);
183
-			break;
184
-	}
185
-
186
-	// pas de <base href /> svp !
187
-	$t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
188
-
189
-	// Reinserer les echappements des modeles
190
-	if (defined('_PROTEGE_JS_MODELES')) {
191
-		$t = echappe_retour($t, 'javascript' . _PROTEGE_JS_MODELES);
192
-	}
193
-	if (defined('_PROTEGE_PHP_MODELES')) {
194
-		$t = echappe_retour($t, 'php' . _PROTEGE_PHP_MODELES);
195
-	}
196
-
197
-	return $dejavu[$mode_filtre][$arg] = $t;
149
+    // on memorise le resultat sur les arguments non triviaux
150
+    static $dejavu = [];
151
+
152
+    // Attention, si ce n'est pas une chaine, laisser intact
153
+    if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
154
+        return $arg;
155
+    }
156
+
157
+    if (is_null($mode_filtre) or !in_array($mode_filtre, [-1, 0, 1])) {
158
+        $mode_filtre = $GLOBALS['filtrer_javascript'];
159
+    }
160
+
161
+    if (isset($dejavu[$mode_filtre][$arg])) {
162
+        return $dejavu[$mode_filtre][$arg];
163
+    }
164
+
165
+    // echapper les tags asp/php
166
+    $t = str_replace('<' . '%', '&lt;%', $arg);
167
+
168
+    // echapper le php
169
+    $t = str_replace('<' . '?', '&lt;?', $t);
170
+
171
+    // echapper le < script language=php >
172
+    $t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
173
+
174
+    // Pour le js, trois modes : parano (-1), prive (0), ok (1)
175
+    switch ($mode_filtre) {
176
+        case 0:
177
+            if (!_DIR_RESTREINT) {
178
+                $t = echappe_js($t);
179
+            }
180
+            break;
181
+        case -1:
182
+            $t = echappe_js($t);
183
+            break;
184
+    }
185
+
186
+    // pas de <base href /> svp !
187
+    $t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
188
+
189
+    // Reinserer les echappements des modeles
190
+    if (defined('_PROTEGE_JS_MODELES')) {
191
+        $t = echappe_retour($t, 'javascript' . _PROTEGE_JS_MODELES);
192
+    }
193
+    if (defined('_PROTEGE_PHP_MODELES')) {
194
+        $t = echappe_retour($t, 'php' . _PROTEGE_PHP_MODELES);
195
+    }
196
+
197
+    return $dejavu[$mode_filtre][$arg] = $t;
198 198
 }
199 199
 
200 200
 
@@ -223,66 +223,66 @@  discard block
 block discarded – undo
223 223
  *     texte transformé
224 224
  **/
225 225
 function typo($letexte, $echapper = true, $connect = null, $env = []) {
226
-	// Plus vite !
227
-	if (!$letexte) {
228
-		return $letexte;
229
-	}
230
-
231
-	// les appels directs a cette fonction depuis le php de l'espace
232
-	// prive etant historiquement ecrit sans argment $connect
233
-	// on utilise la presence de celui-ci pour distinguer les cas
234
-	// ou il faut passer interdire_script explicitement
235
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
236
-	// ne seront pas perturbes
237
-	$interdire_script = false;
238
-	if (is_null($connect)) {
239
-		$connect = '';
240
-		$interdire_script = true;
241
-		$env['espace_prive'] = test_espace_prive();
242
-	}
243
-
244
-	// Echapper les codes <html> etc
245
-	if ($echapper) {
246
-		$letexte = echappe_html($letexte, 'TYPO');
247
-	}
248
-
249
-	//
250
-	// Installer les modeles, notamment images et documents ;
251
-	//
252
-	// NOTE : propre() ne passe pas par ici mais directement par corriger_typo
253
-	// cf. inc/lien
254
-
255
-	$letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect ?? '', null, $env);
256
-	if ($letexte != $mem) {
257
-		$echapper = true;
258
-	}
259
-	unset($mem);
260
-
261
-	$letexte = corriger_typo($letexte);
262
-	$letexte = echapper_faux_tags($letexte);
263
-
264
-	// reintegrer les echappements
265
-	if ($echapper) {
266
-		$letexte = echappe_retour($letexte, 'TYPO');
267
-	}
268
-
269
-	// Dans les appels directs hors squelette, securiser ici aussi
270
-	if ($interdire_script) {
271
-		$letexte = interdire_scripts($letexte);
272
-	}
273
-
274
-	// Dans l'espace prive on se mefie de tout contenu dangereux
275
-	// https://core.spip.net/issues/3371
276
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
277
-	// https://core.spip.net/issues/4166
278
-	if (
279
-		$GLOBALS['filtrer_javascript'] == -1
280
-		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
281
-	) {
282
-		$letexte = echapper_html_suspect($letexte, [], $connect, $env);
283
-	}
284
-
285
-	return $letexte;
226
+    // Plus vite !
227
+    if (!$letexte) {
228
+        return $letexte;
229
+    }
230
+
231
+    // les appels directs a cette fonction depuis le php de l'espace
232
+    // prive etant historiquement ecrit sans argment $connect
233
+    // on utilise la presence de celui-ci pour distinguer les cas
234
+    // ou il faut passer interdire_script explicitement
235
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
236
+    // ne seront pas perturbes
237
+    $interdire_script = false;
238
+    if (is_null($connect)) {
239
+        $connect = '';
240
+        $interdire_script = true;
241
+        $env['espace_prive'] = test_espace_prive();
242
+    }
243
+
244
+    // Echapper les codes <html> etc
245
+    if ($echapper) {
246
+        $letexte = echappe_html($letexte, 'TYPO');
247
+    }
248
+
249
+    //
250
+    // Installer les modeles, notamment images et documents ;
251
+    //
252
+    // NOTE : propre() ne passe pas par ici mais directement par corriger_typo
253
+    // cf. inc/lien
254
+
255
+    $letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect ?? '', null, $env);
256
+    if ($letexte != $mem) {
257
+        $echapper = true;
258
+    }
259
+    unset($mem);
260
+
261
+    $letexte = corriger_typo($letexte);
262
+    $letexte = echapper_faux_tags($letexte);
263
+
264
+    // reintegrer les echappements
265
+    if ($echapper) {
266
+        $letexte = echappe_retour($letexte, 'TYPO');
267
+    }
268
+
269
+    // Dans les appels directs hors squelette, securiser ici aussi
270
+    if ($interdire_script) {
271
+        $letexte = interdire_scripts($letexte);
272
+    }
273
+
274
+    // Dans l'espace prive on se mefie de tout contenu dangereux
275
+    // https://core.spip.net/issues/3371
276
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
277
+    // https://core.spip.net/issues/4166
278
+    if (
279
+        $GLOBALS['filtrer_javascript'] == -1
280
+        or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
281
+    ) {
282
+        $letexte = echapper_html_suspect($letexte, [], $connect, $env);
283
+    }
284
+
285
+    return $letexte;
286 286
 }
287 287
 
288 288
 // Correcteur typographique
@@ -307,57 +307,57 @@  discard block
 block discarded – undo
307 307
  */
308 308
 function corriger_typo($letexte, $lang = '') {
309 309
 
310
-	// Plus vite !
311
-	if (!$letexte) {
312
-		return $letexte;
313
-	}
314
-
315
-	$letexte = pipeline('pre_typo', $letexte);
316
-
317
-	// Caracteres de controle "illegaux"
318
-	$letexte = corriger_caracteres($letexte);
319
-
320
-	// Proteger les caracteres typographiques a l'interieur des tags html
321
-	if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
322
-		foreach ($regs as $reg) {
323
-			$insert = $reg[0];
324
-			// hack: on transforme les caracteres a proteger en les remplacant
325
-			// par des caracteres "illegaux". (cf corriger_caracteres())
326
-			$insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
327
-			$letexte = str_replace($reg[0], $insert, $letexte);
328
-		}
329
-	}
330
-
331
-	// trouver les blocs idiomes et les traiter à part
332
-	$letexte = extraire_idiome($ei = $letexte, $lang, true);
333
-	$ei = ($ei !== $letexte);
334
-
335
-	// trouver les blocs multi et les traiter a part
336
-	$letexte = extraire_multi($em = $letexte, $lang, true);
337
-	$em = ($em !== $letexte);
338
-
339
-	// Charger & appliquer les fonctions de typographie
340
-	$typographie = charger_fonction(lang_typo($lang), 'typographie');
341
-	$letexte = $typographie($letexte);
342
-
343
-	// Les citations en une autre langue, s'il y a lieu
344
-	if ($em) {
345
-		$letexte = echappe_retour($letexte, 'multi');
346
-	}
347
-	if ($ei) {
348
-		$letexte = echappe_retour($letexte, 'idiome');
349
-	}
350
-
351
-	// Retablir les caracteres proteges
352
-	$letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
353
-
354
-	// pipeline
355
-	$letexte = pipeline('post_typo', $letexte);
356
-
357
-	# un message pour abs_url - on est passe en mode texte
358
-	$GLOBALS['mode_abs_url'] = 'texte';
359
-
360
-	return $letexte;
310
+    // Plus vite !
311
+    if (!$letexte) {
312
+        return $letexte;
313
+    }
314
+
315
+    $letexte = pipeline('pre_typo', $letexte);
316
+
317
+    // Caracteres de controle "illegaux"
318
+    $letexte = corriger_caracteres($letexte);
319
+
320
+    // Proteger les caracteres typographiques a l'interieur des tags html
321
+    if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
322
+        foreach ($regs as $reg) {
323
+            $insert = $reg[0];
324
+            // hack: on transforme les caracteres a proteger en les remplacant
325
+            // par des caracteres "illegaux". (cf corriger_caracteres())
326
+            $insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
327
+            $letexte = str_replace($reg[0], $insert, $letexte);
328
+        }
329
+    }
330
+
331
+    // trouver les blocs idiomes et les traiter à part
332
+    $letexte = extraire_idiome($ei = $letexte, $lang, true);
333
+    $ei = ($ei !== $letexte);
334
+
335
+    // trouver les blocs multi et les traiter a part
336
+    $letexte = extraire_multi($em = $letexte, $lang, true);
337
+    $em = ($em !== $letexte);
338
+
339
+    // Charger & appliquer les fonctions de typographie
340
+    $typographie = charger_fonction(lang_typo($lang), 'typographie');
341
+    $letexte = $typographie($letexte);
342
+
343
+    // Les citations en une autre langue, s'il y a lieu
344
+    if ($em) {
345
+        $letexte = echappe_retour($letexte, 'multi');
346
+    }
347
+    if ($ei) {
348
+        $letexte = echappe_retour($letexte, 'idiome');
349
+    }
350
+
351
+    // Retablir les caracteres proteges
352
+    $letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
353
+
354
+    // pipeline
355
+    $letexte = pipeline('post_typo', $letexte);
356
+
357
+    # un message pour abs_url - on est passe en mode texte
358
+    $GLOBALS['mode_abs_url'] = 'texte';
359
+
360
+    return $letexte;
361 361
 }
362 362
 
363 363
 
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
  * @return string
374 374
  */
375 375
 function paragrapher($letexte, $forcer = true) {
376
-	return $letexte;
376
+    return $letexte;
377 377
 }
378 378
 
379 379
 /**
@@ -385,11 +385,11 @@  discard block
 block discarded – undo
385 385
  * @return string texte
386 386
  **/
387 387
 function traiter_retours_chariots($letexte) {
388
-	$letexte = preg_replace(",\r\n?,S", "\n", $letexte);
389
-	$letexte = preg_replace(',<p[>[:space:]],iS', "\n\n\\0", $letexte);
390
-	$letexte = preg_replace(',</p[>[:space:]],iS', "\\0\n\n", $letexte);
388
+    $letexte = preg_replace(",\r\n?,S", "\n", $letexte);
389
+    $letexte = preg_replace(',<p[>[:space:]],iS', "\n\n\\0", $letexte);
390
+    $letexte = preg_replace(',</p[>[:space:]],iS', "\\0\n\n", $letexte);
391 391
 
392
-	return $letexte;
392
+    return $letexte;
393 393
 }
394 394
 
395 395
 
@@ -415,40 +415,40 @@  discard block
 block discarded – undo
415 415
  *     texte transformé
416 416
  **/
417 417
 function propre($t, $connect = null, $env = []) {
418
-	// les appels directs a cette fonction depuis le php de l'espace
419
-	// prive etant historiquement ecrits sans argment $connect
420
-	// on utilise la presence de celui-ci pour distinguer les cas
421
-	// ou il faut passer interdire_script explicitement
422
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
423
-	// ne seront pas perturbes
424
-	$interdire_script = false;
425
-	if (is_null($connect)) {
426
-		$connect = '';
427
-		$interdire_script = true;
428
-		$env['espace_prive'] = true;
429
-	}
430
-
431
-	if (!$t) {
432
-		return strval($t);
433
-	}
434
-
435
-	// Dans l'espace prive on se mefie de tout contenu dangereux
436
-	// avant echappement des balises <html>
437
-	// https://core.spip.net/issues/3371
438
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
439
-	// https://core.spip.net/issues/4166
440
-	if (
441
-		$interdire_script
442
-		or $GLOBALS['filtrer_javascript'] == -1
443
-		or (!empty($env['espace_prive']) and $GLOBALS['filtrer_javascript'] <= 0)
444
-		or (!empty($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript'] <= 0)
445
-	) {
446
-		$t = echapper_html_suspect($t, ['strict' => false], $connect, $env);
447
-	}
448
-	$t = echappe_html($t);
449
-	$t = expanser_liens($t, $connect, $env);
450
-	$t = traiter_raccourcis($t);
451
-	$t = echappe_retour_modeles($t, $interdire_script);
452
-
453
-	return $t;
418
+    // les appels directs a cette fonction depuis le php de l'espace
419
+    // prive etant historiquement ecrits sans argment $connect
420
+    // on utilise la presence de celui-ci pour distinguer les cas
421
+    // ou il faut passer interdire_script explicitement
422
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
423
+    // ne seront pas perturbes
424
+    $interdire_script = false;
425
+    if (is_null($connect)) {
426
+        $connect = '';
427
+        $interdire_script = true;
428
+        $env['espace_prive'] = true;
429
+    }
430
+
431
+    if (!$t) {
432
+        return strval($t);
433
+    }
434
+
435
+    // Dans l'espace prive on se mefie de tout contenu dangereux
436
+    // avant echappement des balises <html>
437
+    // https://core.spip.net/issues/3371
438
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
439
+    // https://core.spip.net/issues/4166
440
+    if (
441
+        $interdire_script
442
+        or $GLOBALS['filtrer_javascript'] == -1
443
+        or (!empty($env['espace_prive']) and $GLOBALS['filtrer_javascript'] <= 0)
444
+        or (!empty($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript'] <= 0)
445
+    ) {
446
+        $t = echapper_html_suspect($t, ['strict' => false], $connect, $env);
447
+    }
448
+    $t = echappe_html($t);
449
+    $t = expanser_liens($t, $connect, $env);
450
+    $t = traiter_raccourcis($t);
451
+    $t = echappe_retour_modeles($t, $interdire_script);
452
+
453
+    return $t;
454 454
 }
Please login to merge, or discard this patch.