Completed
Push — master ( ad4f09...6d727b )
by cam
01:02 queued 13s
created
ecrire/inc/definir_menus_favoris.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -19,19 +19,19 @@
 block discarded – undo
19 19
  * Retourne la liste des menus favoris par défaut ainsi que leur rang
20 20
  */
21 21
 function inc_definir_menus_favoris_dist() {
22
-	return [
22
+    return [
23 23
 
24
-		// Menu Édition,
25
-		'auteurs' => 1,
26
-		'rubriques' => 2,
27
-		'articles' => 3,
24
+        // Menu Édition,
25
+        'auteurs' => 1,
26
+        'rubriques' => 2,
27
+        'articles' => 3,
28 28
 
29
-		// Menu Maintenance
30
-		'admin_vider' => 1,
29
+        // Menu Maintenance
30
+        'admin_vider' => 1,
31 31
 
32
-		// Menu Configurations
33
-		'configurer_identite' => 1,
34
-		'admin_plugin' => 2,
32
+        // Menu Configurations
33
+        'configurer_identite' => 1,
34
+        'admin_plugin' => 2,
35 35
 
36
-	];
36
+    ];
37 37
 }
Please login to merge, or discard this patch.
ecrire/inc/admin.php 2 patches
Indentation   +134 added lines, -134 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -44,29 +44,29 @@  discard block
 block discarded – undo
44 44
  *     sinon code HTML de la page après le traitement effectué.
45 45
  **/
46 46
 function inc_admin_dist($script, $titre, $comment = '', $anonymous = false) {
47
-	$reprise = true;
48
-	if (
49
-		!isset($GLOBALS['meta'][$script])
50
-		|| !isset($GLOBALS['meta']['admin'])
51
-	) {
52
-		$reprise = false;
53
-		$res = debut_admin($script, $titre, $comment);
54
-		if ($res) {
55
-			return $res;
56
-		}
57
-		spip_log("meta: $script " . print_r($_POST, true));
58
-		ecrire_meta($script, serialize($_POST));
59
-	}
47
+    $reprise = true;
48
+    if (
49
+        !isset($GLOBALS['meta'][$script])
50
+        || !isset($GLOBALS['meta']['admin'])
51
+    ) {
52
+        $reprise = false;
53
+        $res = debut_admin($script, $titre, $comment);
54
+        if ($res) {
55
+            return $res;
56
+        }
57
+        spip_log("meta: $script " . print_r($_POST, true));
58
+        ecrire_meta($script, serialize($_POST));
59
+    }
60 60
 
61
-	$res = admin_verifie_session($script, $anonymous);
62
-	if ($res) {
63
-		return $res;
64
-	}
65
-	$base = charger_fonction($script, 'base');
66
-	$base($titre, $reprise);
67
-	fin_admin($script);
61
+    $res = admin_verifie_session($script, $anonymous);
62
+    if ($res) {
63
+        return $res;
64
+    }
65
+    $base = charger_fonction($script, 'base');
66
+    $base($titre, $reprise);
67
+    fin_admin($script);
68 68
 
69
-	return '';
69
+    return '';
70 70
 }
71 71
 
72 72
 /**
@@ -97,36 +97,36 @@  discard block
 block discarded – undo
97 97
  *     Code HTML si message d'erreur, '' sinon;
98 98
  */
99 99
 function admin_verifie_session($script, $anonymous = false) {
100
-	include_spip('base/abstract_sql');
101
-	$pref = sprintf('_%d_', $GLOBALS['visiteur_session']['id_auteur']);
102
-	$signal = fichier_admin($script, "$script$pref");
103
-	$valeur = sql_getfetsel('valeur', 'spip_meta', "nom='admin'");
104
-	if ($valeur === null) {
105
-		ecrire_meta('admin', $signal, 'non');
106
-	} else {
107
-		if (
108
-			!$anonymous
109
-			&& $valeur != $signal
110
-			&& (
111
-				!preg_match('/^(.*)_(\d+)_/', (string) $GLOBALS['meta']['admin'], $l)
112
-				|| (int) $l[2] != $GLOBALS['visiteur_session']['id_auteur']
113
-			)
114
-		) {
115
-			include_spip('inc/minipres');
116
-			spip_log("refus de lancer $script, priorite a $valeur");
117
-			return minipres(_T('info_travaux_texte'), '', ['status' => 503]);
118
-		}
119
-	}
120
-	$journal = 'spip';
121
-	if (autoriser('configurer')) {
122
-		// c'est une action webmestre, soit par ftp soit par statut webmestre
123
-		$journal = 'webmestre';
124
-	}
125
-	// on pourrait statuer automatiquement les webmestres a l'init d'une action auth par ftp ... ?
100
+    include_spip('base/abstract_sql');
101
+    $pref = sprintf('_%d_', $GLOBALS['visiteur_session']['id_auteur']);
102
+    $signal = fichier_admin($script, "$script$pref");
103
+    $valeur = sql_getfetsel('valeur', 'spip_meta', "nom='admin'");
104
+    if ($valeur === null) {
105
+        ecrire_meta('admin', $signal, 'non');
106
+    } else {
107
+        if (
108
+            !$anonymous
109
+            && $valeur != $signal
110
+            && (
111
+                !preg_match('/^(.*)_(\d+)_/', (string) $GLOBALS['meta']['admin'], $l)
112
+                || (int) $l[2] != $GLOBALS['visiteur_session']['id_auteur']
113
+            )
114
+        ) {
115
+            include_spip('inc/minipres');
116
+            spip_log("refus de lancer $script, priorite a $valeur");
117
+            return minipres(_T('info_travaux_texte'), '', ['status' => 503]);
118
+        }
119
+    }
120
+    $journal = 'spip';
121
+    if (autoriser('configurer')) {
122
+        // c'est une action webmestre, soit par ftp soit par statut webmestre
123
+        $journal = 'webmestre';
124
+    }
125
+    // on pourrait statuer automatiquement les webmestres a l'init d'une action auth par ftp ... ?
126 126
 
127
-	spip_log("admin $pref" . ($valeur ? ' (reprise)' : ' (init)'), $journal);
127
+    spip_log("admin $pref" . ($valeur ? ' (reprise)' : ' (init)'), $journal);
128 128
 
129
-	return '';
129
+    return '';
130 130
 }
131 131
 
132 132
 /**
@@ -139,11 +139,11 @@  discard block
 block discarded – undo
139 139
  *     Chemin du répertoire.
140 140
  **/
141 141
 function dir_admin() {
142
-	if (autoriser('configurer')) {
143
-		return _DIR_TMP;
144
-	} else {
145
-		return _DIR_TRANSFERT . $GLOBALS['visiteur_session']['login'] . '/';
146
-	}
142
+    if (autoriser('configurer')) {
143
+        return _DIR_TMP;
144
+    } else {
145
+        return _DIR_TRANSFERT . $GLOBALS['visiteur_session']['login'] . '/';
146
+    }
147 147
 }
148 148
 
149 149
 /**
@@ -160,8 +160,8 @@  discard block
 block discarded – undo
160 160
  *     Nom du fichier
161 161
  **/
162 162
 function fichier_admin($action, $pref = 'admin_') {
163
-	return $pref .
164
-	substr(md5($action . (time() & ~2047) . $GLOBALS['visiteur_session']['login']), 0, 10);
163
+    return $pref .
164
+    substr(md5($action . (time() & ~2047) . $GLOBALS['visiteur_session']['login']), 0, 10);
165 165
 }
166 166
 
167 167
 /**
@@ -187,76 +187,76 @@  discard block
 block discarded – undo
187 187
  *     sinon chaîne vide si déjà fait.
188 188
  **/
189 189
 function debut_admin($script, $action = '', $corps = '') {
190
-	if (
191
-		!$action
192
-		|| !autoriser('webmestre') && !autoriser('chargerftp')
193
-	) {
194
-		include_spip('inc/minipres');
190
+    if (
191
+        !$action
192
+        || !autoriser('webmestre') && !autoriser('chargerftp')
193
+    ) {
194
+        include_spip('inc/minipres');
195 195
 
196
-		return minipres();
197
-	} else {
198
-		$dir = dir_admin();
199
-		$signal = fichier_admin($script);
200
-		if (@file_exists($dir . $signal)) {
201
-			spip_log("Action admin: $action");
196
+        return minipres();
197
+    } else {
198
+        $dir = dir_admin();
199
+        $signal = fichier_admin($script);
200
+        if (@file_exists($dir . $signal)) {
201
+            spip_log("Action admin: $action");
202 202
 
203
-			return '';
204
-		}
205
-		include_spip('inc/minipres');
203
+            return '';
204
+        }
205
+        include_spip('inc/minipres');
206 206
 
207
-		// Si on est un super-admin, un bouton de validation suffit
208
-		// sauf dans les cas destroy
209
-		if (
210
-			(autoriser('webmestre') || $script === 'repair')
211
-			&& $script != 'delete_all'
212
-		) {
213
-			if (_request('validation_admin') == $signal) {
214
-				spip_log("Action super-admin: $action");
207
+        // Si on est un super-admin, un bouton de validation suffit
208
+        // sauf dans les cas destroy
209
+        if (
210
+            (autoriser('webmestre') || $script === 'repair')
211
+            && $script != 'delete_all'
212
+        ) {
213
+            if (_request('validation_admin') == $signal) {
214
+                spip_log("Action super-admin: $action");
215 215
 
216
-				return '';
217
-			}
218
-			$corps .= '<input type="hidden" name="validation_admin" value="' . $signal . '" />';
219
-			$suivant = _T('bouton_valider');
220
-			$js = '';
221
-		} else {
222
-			// cet appel permet d'assurer un copier-coller du nom du repertoire a creer dans tmp (esj)
223
-			// l'insertion du script a cet endroit n'est pas xhtml licite
224
-			// mais evite de l'embarquer dans toutes les pages minipres
225
-			$corps .= http_script('', 'spip_barre.js');
216
+                return '';
217
+            }
218
+            $corps .= '<input type="hidden" name="validation_admin" value="' . $signal . '" />';
219
+            $suivant = _T('bouton_valider');
220
+            $js = '';
221
+        } else {
222
+            // cet appel permet d'assurer un copier-coller du nom du repertoire a creer dans tmp (esj)
223
+            // l'insertion du script a cet endroit n'est pas xhtml licite
224
+            // mais evite de l'embarquer dans toutes les pages minipres
225
+            $corps .= http_script('', 'spip_barre.js');
226 226
 
227
-			$corps .= '<fieldset><legend>'
228
-				. _T('info_authentification_ftp')
229
-				. aider('ftp_auth')
230
-				. "</legend>\n<label for='fichier'>"
231
-				. _T('info_creer_repertoire')
232
-				. "</label>\n"
233
-				. "<span id='signal' class='formo'>" . $signal . '</span>'
234
-				. "<input type='hidden' id='fichier' name='fichier' value='"
235
-				. $signal
236
-				. "' />"
237
-				. _T('info_creer_repertoire_2', ['repertoire' => joli_repertoire($dir)])
238
-				. '</fieldset>';
227
+            $corps .= '<fieldset><legend>'
228
+                . _T('info_authentification_ftp')
229
+                . aider('ftp_auth')
230
+                . "</legend>\n<label for='fichier'>"
231
+                . _T('info_creer_repertoire')
232
+                . "</label>\n"
233
+                . "<span id='signal' class='formo'>" . $signal . '</span>'
234
+                . "<input type='hidden' id='fichier' name='fichier' value='"
235
+                . $signal
236
+                . "' />"
237
+                . _T('info_creer_repertoire_2', ['repertoire' => joli_repertoire($dir)])
238
+                . '</fieldset>';
239 239
 
240
-			$suivant = _T('bouton_recharger_page');
240
+            $suivant = _T('bouton_recharger_page');
241 241
 
242
-			// code volontairement tordu:
243
-			// provoquer la copie dans le presse papier du nom du repertoire
244
-			// en remettant a vide le champ pour que ca marche aussi en cas
245
-			// de JavaScript inactif.
246
-			$js = " onload='var range=document.createRange(); var signal = document.getElementById(\"signal\"); var userSelection = window.getSelection(); range.setStart(signal,0); range.setEnd(signal,1); userSelection.addRange(range);'";
247
-		}
242
+            // code volontairement tordu:
243
+            // provoquer la copie dans le presse papier du nom du repertoire
244
+            // en remettant a vide le champ pour que ca marche aussi en cas
245
+            // de JavaScript inactif.
246
+            $js = " onload='var range=document.createRange(); var signal = document.getElementById(\"signal\"); var userSelection = window.getSelection(); range.setStart(signal,0); range.setEnd(signal,1); userSelection.addRange(range);'";
247
+        }
248 248
 
249
-		// admin/xxx correspond
250
-		// a exec/base_xxx de preference
251
-		// et exec/xxx sinon (compat)
252
-		if (tester_url_ecrire("base_$script")) {
253
-			$script = "base_$script";
254
-		}
255
-		$form = copy_request($script, $corps, $suivant);
256
-		$info_action = _T('info_action', ['action' => "$action"]);
249
+        // admin/xxx correspond
250
+        // a exec/base_xxx de preference
251
+        // et exec/xxx sinon (compat)
252
+        if (tester_url_ecrire("base_$script")) {
253
+            $script = "base_$script";
254
+        }
255
+        $form = copy_request($script, $corps, $suivant);
256
+        $info_action = _T('info_action', ['action' => "$action"]);
257 257
 
258
-		return minipres($info_action, $form, ['onload' => $js]);
259
-	}
258
+        return minipres($info_action, $form, ['onload' => $js]);
259
+    }
260 260
 }
261 261
 
262 262
 /**
@@ -267,13 +267,13 @@  discard block
 block discarded – undo
267 267
  *     Nom de l'action (en base) qui a été exécutée
268 268
  **/
269 269
 function fin_admin($action) {
270
-	$signal = dir_admin() . fichier_admin($action);
271
-	spip_unlink($signal);
272
-	if ($action != 'delete_all') {
273
-		effacer_meta($action);
274
-		effacer_meta('admin');
275
-		spip_log("efface les meta admin et $action ");
276
-	}
270
+    $signal = dir_admin() . fichier_admin($action);
271
+    spip_unlink($signal);
272
+    if ($action != 'delete_all') {
273
+        effacer_meta($action);
274
+        effacer_meta('admin');
275
+        spip_log("efface les meta admin et $action ");
276
+    }
277 277
 }
278 278
 
279 279
 /**
@@ -292,14 +292,14 @@  discard block
 block discarded – undo
292 292
  *     Code HTML du formulaire
293 293
  **/
294 294
 function copy_request($script, $suite, $submit = '') {
295
-	include_spip('inc/filtres');
296
-	foreach ([...$_POST, ...$_GET] as $n => $c) {
297
-		if (!in_array($n, ['fichier', 'exec', 'validation_admin']) && !is_array($c)) {
298
-			$suite .= "\n<input type='hidden' name='" . spip_htmlspecialchars($n) . "' value='" .
299
-				entites_html($c) .
300
-				"'  />";
301
-		}
302
-	}
295
+    include_spip('inc/filtres');
296
+    foreach ([...$_POST, ...$_GET] as $n => $c) {
297
+        if (!in_array($n, ['fichier', 'exec', 'validation_admin']) && !is_array($c)) {
298
+            $suite .= "\n<input type='hidden' name='" . spip_htmlspecialchars($n) . "' value='" .
299
+                entites_html($c) .
300
+                "'  />";
301
+        }
302
+    }
303 303
 
304
-	return generer_form_ecrire($script, $suite, '', $submit);
304
+    return generer_form_ecrire($script, $suite, '', $submit);
305 305
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 		if ($res) {
55 55
 			return $res;
56 56
 		}
57
-		spip_log("meta: $script " . print_r($_POST, true));
57
+		spip_log("meta: $script ".print_r($_POST, true));
58 58
 		ecrire_meta($script, serialize($_POST));
59 59
 	}
60 60
 
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 	}
125 125
 	// on pourrait statuer automatiquement les webmestres a l'init d'une action auth par ftp ... ?
126 126
 
127
-	spip_log("admin $pref" . ($valeur ? ' (reprise)' : ' (init)'), $journal);
127
+	spip_log("admin $pref".($valeur ? ' (reprise)' : ' (init)'), $journal);
128 128
 
129 129
 	return '';
130 130
 }
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 	if (autoriser('configurer')) {
143 143
 		return _DIR_TMP;
144 144
 	} else {
145
-		return _DIR_TRANSFERT . $GLOBALS['visiteur_session']['login'] . '/';
145
+		return _DIR_TRANSFERT.$GLOBALS['visiteur_session']['login'].'/';
146 146
 	}
147 147
 }
148 148
 
@@ -160,8 +160,8 @@  discard block
 block discarded – undo
160 160
  *     Nom du fichier
161 161
  **/
162 162
 function fichier_admin($action, $pref = 'admin_') {
163
-	return $pref .
164
-	substr(md5($action . (time() & ~2047) . $GLOBALS['visiteur_session']['login']), 0, 10);
163
+	return $pref.
164
+	substr(md5($action.(time() & ~2047).$GLOBALS['visiteur_session']['login']), 0, 10);
165 165
 }
166 166
 
167 167
 /**
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 	} else {
198 198
 		$dir = dir_admin();
199 199
 		$signal = fichier_admin($script);
200
-		if (@file_exists($dir . $signal)) {
200
+		if (@file_exists($dir.$signal)) {
201 201
 			spip_log("Action admin: $action");
202 202
 
203 203
 			return '';
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 
216 216
 				return '';
217 217
 			}
218
-			$corps .= '<input type="hidden" name="validation_admin" value="' . $signal . '" />';
218
+			$corps .= '<input type="hidden" name="validation_admin" value="'.$signal.'" />';
219 219
 			$suivant = _T('bouton_valider');
220 220
 			$js = '';
221 221
 		} else {
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 				. "</legend>\n<label for='fichier'>"
231 231
 				. _T('info_creer_repertoire')
232 232
 				. "</label>\n"
233
-				. "<span id='signal' class='formo'>" . $signal . '</span>'
233
+				. "<span id='signal' class='formo'>".$signal.'</span>'
234 234
 				. "<input type='hidden' id='fichier' name='fichier' value='"
235 235
 				. $signal
236 236
 				. "' />"
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
  *     Nom de l'action (en base) qui a été exécutée
268 268
  **/
269 269
 function fin_admin($action) {
270
-	$signal = dir_admin() . fichier_admin($action);
270
+	$signal = dir_admin().fichier_admin($action);
271 271
 	spip_unlink($signal);
272 272
 	if ($action != 'delete_all') {
273 273
 		effacer_meta($action);
@@ -295,8 +295,8 @@  discard block
 block discarded – undo
295 295
 	include_spip('inc/filtres');
296 296
 	foreach ([...$_POST, ...$_GET] as $n => $c) {
297 297
 		if (!in_array($n, ['fichier', 'exec', 'validation_admin']) && !is_array($c)) {
298
-			$suite .= "\n<input type='hidden' name='" . spip_htmlspecialchars($n) . "' value='" .
299
-				entites_html($c) .
298
+			$suite .= "\n<input type='hidden' name='".spip_htmlspecialchars($n)."' value='".
299
+				entites_html($c).
300 300
 				"'  />";
301 301
 		}
302 302
 	}
Please login to merge, or discard this patch.
ecrire/inc/editer.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -336,8 +336,7 @@
 block discarded – undo
336 336
 		if (!autoriser('modifier', $type, (int) $id)) {
337 337
 			$contexte['editable'] = '';
338 338
 		}
339
-	}
340
-	else {
339
+	} else {
341 340
 		if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
342 341
 			$contexte['editable'] = '';
343 342
 		}
Please login to merge, or discard this patch.
Indentation   +413 added lines, -413 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 include_spip('base/abstract_sql');
22 22
 
@@ -58,56 +58,56 @@  discard block
 block discarded – undo
58 58
  *     Retour des traitements.
59 59
  **/
60 60
 function formulaires_editer_objet_traiter(
61
-	$type,
62
-	$id = 'new',
63
-	$id_parent = 0,
64
-	$lier_trad = 0,
65
-	$retour = '',
66
-	$config_fonc = 'articles_edit_config',
67
-	$row = [],
68
-	$hidden = ''
61
+    $type,
62
+    $id = 'new',
63
+    $id_parent = 0,
64
+    $lier_trad = 0,
65
+    $retour = '',
66
+    $config_fonc = 'articles_edit_config',
67
+    $row = [],
68
+    $hidden = ''
69 69
 ) {
70 70
 
71
-	$res = [];
72
-	// eviter la redirection forcee par l'action...
73
-	set_request('redirect');
74
-	if ($action_editer = charger_fonction("editer_$type", 'action', true)) {
75
-		[$id, $err] = $action_editer($id);
76
-	} else {
77
-		$action_editer = charger_fonction('editer_objet', 'action');
78
-		[$id, $err] = $action_editer($id, $type);
79
-	}
80
-	$id_table_objet = id_table_objet($type);
81
-	$res[$id_table_objet] = $id;
82
-	if ($err || !$id) {
83
-		$res['message_erreur'] = ($err ?: _T('erreur'));
84
-	} else {
85
-		// Un lien de trad a prendre en compte
86
-		if ($lier_trad) {
87
-			// referencer la traduction
88
-			$referencer_traduction = charger_fonction('referencer_traduction', 'action');
89
-			$referencer_traduction($type, $id, $lier_trad);
90
-			// actions de recopie de champs / liens sur le nouvel objet créé
91
-			$completer_traduction = charger_fonction('completer_traduction', 'inc');
92
-			$err = $completer_traduction($type, $id, $lier_trad);
93
-			if ($err) {
94
-				$res['message_erreur'] = $err;
95
-				return $res;
96
-			}
97
-		}
98
-
99
-		$res['message_ok'] = _T('info_modification_enregistree');
100
-		if ($retour) {
101
-			if (str_starts_with($retour, 'javascript:')) {
102
-				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
103
-				$res['editable'] = true;
104
-			} else {
105
-				$res['redirect'] = parametre_url($retour, $id_table_objet, $id);
106
-			}
107
-		}
108
-	}
109
-
110
-	return $res;
71
+    $res = [];
72
+    // eviter la redirection forcee par l'action...
73
+    set_request('redirect');
74
+    if ($action_editer = charger_fonction("editer_$type", 'action', true)) {
75
+        [$id, $err] = $action_editer($id);
76
+    } else {
77
+        $action_editer = charger_fonction('editer_objet', 'action');
78
+        [$id, $err] = $action_editer($id, $type);
79
+    }
80
+    $id_table_objet = id_table_objet($type);
81
+    $res[$id_table_objet] = $id;
82
+    if ($err || !$id) {
83
+        $res['message_erreur'] = ($err ?: _T('erreur'));
84
+    } else {
85
+        // Un lien de trad a prendre en compte
86
+        if ($lier_trad) {
87
+            // referencer la traduction
88
+            $referencer_traduction = charger_fonction('referencer_traduction', 'action');
89
+            $referencer_traduction($type, $id, $lier_trad);
90
+            // actions de recopie de champs / liens sur le nouvel objet créé
91
+            $completer_traduction = charger_fonction('completer_traduction', 'inc');
92
+            $err = $completer_traduction($type, $id, $lier_trad);
93
+            if ($err) {
94
+                $res['message_erreur'] = $err;
95
+                return $res;
96
+            }
97
+        }
98
+
99
+        $res['message_ok'] = _T('info_modification_enregistree');
100
+        if ($retour) {
101
+            if (str_starts_with($retour, 'javascript:')) {
102
+                $res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
103
+                $res['editable'] = true;
104
+            } else {
105
+                $res['redirect'] = parametre_url($retour, $id_table_objet, $id);
106
+            }
107
+        }
108
+    }
109
+
110
+    return $res;
111 111
 }
112 112
 
113 113
 /**
@@ -131,29 +131,29 @@  discard block
 block discarded – undo
131 131
  *     Tableau des erreurs
132 132
  **/
133 133
 function formulaires_editer_objet_verifier($type, $id = 'new', $oblis = []) {
134
-	$erreurs = [];
135
-	if ((int) $id) {
136
-		$conflits = controler_contenu($type, $id);
137
-		if ($conflits && (is_countable($conflits) ? count($conflits) : 0)) {
138
-			foreach ($conflits as $champ => $conflit) {
139
-				if (!isset($erreurs[$champ])) {
140
-					$erreurs[$champ] = '';
141
-				}
142
-				$erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
143
-			}
144
-		}
145
-	}
146
-	foreach ($oblis as $obli) {
147
-		$value = _request($obli);
148
-		if (is_null($value) || !(is_array($value) ? count($value) : strlen((string) $value))) {
149
-			if (!isset($erreurs[$obli])) {
150
-				$erreurs[$obli] = '';
151
-			}
152
-			$erreurs[$obli] .= _T('info_obligatoire');
153
-		}
154
-	}
155
-
156
-	return $erreurs;
134
+    $erreurs = [];
135
+    if ((int) $id) {
136
+        $conflits = controler_contenu($type, $id);
137
+        if ($conflits && (is_countable($conflits) ? count($conflits) : 0)) {
138
+            foreach ($conflits as $champ => $conflit) {
139
+                if (!isset($erreurs[$champ])) {
140
+                    $erreurs[$champ] = '';
141
+                }
142
+                $erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
143
+            }
144
+        }
145
+    }
146
+    foreach ($oblis as $obli) {
147
+        $value = _request($obli);
148
+        if (is_null($value) || !(is_array($value) ? count($value) : strlen((string) $value))) {
149
+            if (!isset($erreurs[$obli])) {
150
+                $erreurs[$obli] = '';
151
+            }
152
+            $erreurs[$obli] .= _T('info_obligatoire');
153
+        }
154
+    }
155
+
156
+    return $erreurs;
157 157
 }
158 158
 
159 159
 /**
@@ -198,150 +198,150 @@  discard block
 block discarded – undo
198 198
  *     Environnement du formulaire.
199 199
  **/
200 200
 function formulaires_editer_objet_charger(
201
-	$type,
202
-	$id = 'new',
203
-	$id_parent = 0,
204
-	$lier_trad = 0,
205
-	$retour = '',
206
-	$config_fonc = 'articles_edit_config',
207
-	$row = [],
208
-	$hidden = ''
201
+    $type,
202
+    $id = 'new',
203
+    $id_parent = 0,
204
+    $lier_trad = 0,
205
+    $retour = '',
206
+    $config_fonc = 'articles_edit_config',
207
+    $row = [],
208
+    $hidden = ''
209 209
 ) {
210 210
 
211
-	$table_objet = table_objet($type);
212
-	$table_objet_sql = table_objet_sql($type);
213
-	$id_table_objet = id_table_objet($type);
214
-	if (!is_array($row)) {
215
-		$row = [];
216
-	}
217
-
218
-	// on accepte pas une fonction de config inconnue si elle vient d'un modele
219
-	if (
220
-		$config_fonc
221
-		&& !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
222
-		&& $config_fonc !== $table_objet . '_edit_config'
223
-		&& ($args = test_formulaire_inclus_par_modele())
224
-		&& in_array($config_fonc, $args)
225
-	) {
226
-		$config_fonc = '';
227
-	}
228
-
229
-	$new = !is_numeric($id);
230
-	$lang_default = '';
231
-	// Appel direct dans un squelette
232
-	if (!$row) {
233
-		if (!$new || $lier_trad) {
234
-			if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
235
-				$row = $select($id, $id_parent, $lier_trad);
236
-				// si on a une fonction precharger, elle pu faire un reglage de langue
237
-				$lang_default = (empty($row['lang']) ? null : $row['lang']);
238
-			} else {
239
-				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . (int) $id);
240
-			}
241
-			if (!$new) {
242
-				$md5 = controles_md5($row ?: []);
243
-			}
244
-		}
245
-		if (!$row) {
246
-			$row = [];
247
-			$trouver_table = charger_fonction('trouver_table', 'base');
248
-			if ($desc = $trouver_table($table_objet)) {
249
-				foreach ($desc['field'] as $k => $v) {
250
-					$row[$k] = '';
251
-				}
252
-			}
253
-		}
254
-	}
255
-
256
-	// Gaffe: sans ceci, on ecrase systematiquement l'article d'origine
257
-	// (et donc: pas de lien de traduction)
258
-	$id = ($new || $lier_trad)
259
-		? 'oui'
260
-		: $row[$id_table_objet];
261
-	$row[$id_table_objet] = $id;
262
-
263
-	$contexte = $row;
264
-	if (is_numeric($id_parent) && strlen($id_parent) && (!isset($contexte['id_parent']) || $new)) {
265
-		if (!isset($contexte['id_parent'])) {
266
-			unset($contexte['id_rubrique']);
267
-		}
268
-		$contexte['id_parent'] = $id_parent;
269
-	} elseif (!isset($contexte['id_parent'])) {
270
-		// id_rubrique dans id_parent si possible
271
-		if (isset($contexte['id_rubrique'])) {
272
-			$contexte['id_parent'] = $contexte['id_rubrique'];
273
-			unset($contexte['id_rubrique']);
274
-		} else {
275
-			$contexte['id_parent'] = '';
276
-		}
277
-		if (
278
-			!$contexte['id_parent']
279
-			&& ($preselectionner_parent_nouvel_objet = charger_fonction('preselectionner_parent_nouvel_objet', 'inc', true))
280
-		) {
281
-			$contexte['id_parent'] = $preselectionner_parent_nouvel_objet($type, $row);
282
-		}
283
-	}
284
-
285
-	$config = [];
286
-	if ($config_fonc) {
287
-		$contexte['config'] = $config = $config_fonc($contexte);
288
-		if (!$lang_default) {
289
-			$lang_default = $config['langue'] ?? session_get('lang') ;
290
-		}
291
-	}
292
-	$config += [
293
-		'lignes' => 0,
294
-		'langue' => '',
295
-	];
296
-
297
-	$att_text = " class='textarea' "
298
-		. " rows='"
299
-		. ($config['lignes'] + 15)
300
-		. "' cols='40'";
301
-
302
-
303
-	// on veut conserver la langue de l'interface ;
304
-	// on passe cette donnee sous un autre nom, au cas ou le squelette
305
-	// voudrait l'exploiter
306
-	if (isset($contexte['lang'])) {
307
-		$contexte['langue'] = $contexte['lang'];
308
-		unset($contexte['lang']);
309
-	}
310
-
311
-	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
312
-		($lier_trad
313
-			 ? "\n<input type='hidden' name='lier_trad' value='" .
314
-				$lier_trad .
315
-				"' />" .
316
-				"\n<input type='hidden' name='changer_lang' value='" .
317
-				$lang_default .
318
-				"' />"
319
-			: '')
320
-		. $hidden
321
-		. ($md5 ?? '');
322
-
323
-	// preciser que le formulaire doit passer dans un pipeline
324
-	$contexte['_pipeline'] = ['editer_contenu_objet', ['type' => $type, 'id' => $id]];
325
-
326
-	// preciser que le formulaire doit etre securise auteur/action
327
-	// n'est plus utile lorsque l'action accepte l'id en argument direct
328
-	// on le garde pour compat
329
-	$contexte['_action'] = ["editer_$type", $id];
330
-
331
-	// et in fine placer l'autorisation
332
-	include_spip('inc/autoriser');
333
-	if ((int) $id) {
334
-		if (!autoriser('modifier', $type, (int) $id)) {
335
-			$contexte['editable'] = '';
336
-		}
337
-	}
338
-	else {
339
-		if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
340
-			$contexte['editable'] = '';
341
-		}
342
-	}
343
-
344
-	return $contexte;
211
+    $table_objet = table_objet($type);
212
+    $table_objet_sql = table_objet_sql($type);
213
+    $id_table_objet = id_table_objet($type);
214
+    if (!is_array($row)) {
215
+        $row = [];
216
+    }
217
+
218
+    // on accepte pas une fonction de config inconnue si elle vient d'un modele
219
+    if (
220
+        $config_fonc
221
+        && !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
222
+        && $config_fonc !== $table_objet . '_edit_config'
223
+        && ($args = test_formulaire_inclus_par_modele())
224
+        && in_array($config_fonc, $args)
225
+    ) {
226
+        $config_fonc = '';
227
+    }
228
+
229
+    $new = !is_numeric($id);
230
+    $lang_default = '';
231
+    // Appel direct dans un squelette
232
+    if (!$row) {
233
+        if (!$new || $lier_trad) {
234
+            if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
235
+                $row = $select($id, $id_parent, $lier_trad);
236
+                // si on a une fonction precharger, elle pu faire un reglage de langue
237
+                $lang_default = (empty($row['lang']) ? null : $row['lang']);
238
+            } else {
239
+                $row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . (int) $id);
240
+            }
241
+            if (!$new) {
242
+                $md5 = controles_md5($row ?: []);
243
+            }
244
+        }
245
+        if (!$row) {
246
+            $row = [];
247
+            $trouver_table = charger_fonction('trouver_table', 'base');
248
+            if ($desc = $trouver_table($table_objet)) {
249
+                foreach ($desc['field'] as $k => $v) {
250
+                    $row[$k] = '';
251
+                }
252
+            }
253
+        }
254
+    }
255
+
256
+    // Gaffe: sans ceci, on ecrase systematiquement l'article d'origine
257
+    // (et donc: pas de lien de traduction)
258
+    $id = ($new || $lier_trad)
259
+        ? 'oui'
260
+        : $row[$id_table_objet];
261
+    $row[$id_table_objet] = $id;
262
+
263
+    $contexte = $row;
264
+    if (is_numeric($id_parent) && strlen($id_parent) && (!isset($contexte['id_parent']) || $new)) {
265
+        if (!isset($contexte['id_parent'])) {
266
+            unset($contexte['id_rubrique']);
267
+        }
268
+        $contexte['id_parent'] = $id_parent;
269
+    } elseif (!isset($contexte['id_parent'])) {
270
+        // id_rubrique dans id_parent si possible
271
+        if (isset($contexte['id_rubrique'])) {
272
+            $contexte['id_parent'] = $contexte['id_rubrique'];
273
+            unset($contexte['id_rubrique']);
274
+        } else {
275
+            $contexte['id_parent'] = '';
276
+        }
277
+        if (
278
+            !$contexte['id_parent']
279
+            && ($preselectionner_parent_nouvel_objet = charger_fonction('preselectionner_parent_nouvel_objet', 'inc', true))
280
+        ) {
281
+            $contexte['id_parent'] = $preselectionner_parent_nouvel_objet($type, $row);
282
+        }
283
+    }
284
+
285
+    $config = [];
286
+    if ($config_fonc) {
287
+        $contexte['config'] = $config = $config_fonc($contexte);
288
+        if (!$lang_default) {
289
+            $lang_default = $config['langue'] ?? session_get('lang') ;
290
+        }
291
+    }
292
+    $config += [
293
+        'lignes' => 0,
294
+        'langue' => '',
295
+    ];
296
+
297
+    $att_text = " class='textarea' "
298
+        . " rows='"
299
+        . ($config['lignes'] + 15)
300
+        . "' cols='40'";
301
+
302
+
303
+    // on veut conserver la langue de l'interface ;
304
+    // on passe cette donnee sous un autre nom, au cas ou le squelette
305
+    // voudrait l'exploiter
306
+    if (isset($contexte['lang'])) {
307
+        $contexte['langue'] = $contexte['lang'];
308
+        unset($contexte['lang']);
309
+    }
310
+
311
+    $contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
312
+        ($lier_trad
313
+             ? "\n<input type='hidden' name='lier_trad' value='" .
314
+                $lier_trad .
315
+                "' />" .
316
+                "\n<input type='hidden' name='changer_lang' value='" .
317
+                $lang_default .
318
+                "' />"
319
+            : '')
320
+        . $hidden
321
+        . ($md5 ?? '');
322
+
323
+    // preciser que le formulaire doit passer dans un pipeline
324
+    $contexte['_pipeline'] = ['editer_contenu_objet', ['type' => $type, 'id' => $id]];
325
+
326
+    // preciser que le formulaire doit etre securise auteur/action
327
+    // n'est plus utile lorsque l'action accepte l'id en argument direct
328
+    // on le garde pour compat
329
+    $contexte['_action'] = ["editer_$type", $id];
330
+
331
+    // et in fine placer l'autorisation
332
+    include_spip('inc/autoriser');
333
+    if ((int) $id) {
334
+        if (!autoriser('modifier', $type, (int) $id)) {
335
+            $contexte['editable'] = '';
336
+        }
337
+    }
338
+    else {
339
+        if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
340
+            $contexte['editable'] = '';
341
+        }
342
+    }
343
+
344
+    return $contexte;
345 345
 }
346 346
 
347 347
 /**
@@ -352,29 +352,29 @@  discard block
 block discarded – undo
352 352
  * @return array
353 353
  */
354 354
 function coupe_trop_long($texte) {
355
-	$aider = charger_fonction('aider', 'inc');
356
-	if (strlen($texte) > 28 * 1024) {
357
-		$texte = str_replace("\r\n", "\n", $texte);
358
-		$pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
359
-		if ($pos > 0 && $pos < 32 * 1024) {
360
-			$debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
361
-			$suite = substr($texte, $pos + 2);
362
-		} else {
363
-			$pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
364
-			if (!($pos > 0 && $pos < 32 * 1024)) {
365
-				$pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
366
-				$decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
367
-			} else {
368
-				$decalage = 1;
369
-			}
370
-			$debut = substr($texte, 0, $pos + $decalage); // Il faut conserver l'espace s'il y en a un
371
-			$suite = substr($texte, $pos + $decalage);
372
-		}
373
-
374
-		return ([$debut, $suite]);
375
-	} else {
376
-		return ([$texte, '']);
377
-	}
355
+    $aider = charger_fonction('aider', 'inc');
356
+    if (strlen($texte) > 28 * 1024) {
357
+        $texte = str_replace("\r\n", "\n", $texte);
358
+        $pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
359
+        if ($pos > 0 && $pos < 32 * 1024) {
360
+            $debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
361
+            $suite = substr($texte, $pos + 2);
362
+        } else {
363
+            $pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
364
+            if (!($pos > 0 && $pos < 32 * 1024)) {
365
+                $pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
366
+                $decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
367
+            } else {
368
+                $decalage = 1;
369
+            }
370
+            $debut = substr($texte, 0, $pos + $decalage); // Il faut conserver l'espace s'il y en a un
371
+            $suite = substr($texte, $pos + $decalage);
372
+        }
373
+
374
+        return ([$debut, $suite]);
375
+    } else {
376
+        return ([$texte, '']);
377
+    }
378 378
 }
379 379
 
380 380
 /**
@@ -385,13 +385,13 @@  discard block
 block discarded – undo
385 385
  * @param int $longueur
386 386
  */
387 387
 function titre_automatique($champ_titre, $champs_contenu, $longueur = null) {
388
-	if (!_request($champ_titre)) {
389
-		$titrer_contenu = charger_fonction('titrer_contenu', 'inc');
390
-		$t = is_null($longueur) ? $titrer_contenu($champs_contenu) : $titrer_contenu($champs_contenu, null, $longueur);
391
-		if ($t) {
392
-			set_request($champ_titre, $t);
393
-		}
394
-	}
388
+    if (!_request($champ_titre)) {
389
+        $titrer_contenu = charger_fonction('titrer_contenu', 'inc');
390
+        $t = is_null($longueur) ? $titrer_contenu($champs_contenu) : $titrer_contenu($champs_contenu, null, $longueur);
391
+        if ($t) {
392
+            set_request($champ_titre, $t);
393
+        }
394
+    }
395 395
 }
396 396
 
397 397
 /**
@@ -411,20 +411,20 @@  discard block
 block discarded – undo
411 411
  * @return string
412 412
  */
413 413
 function inc_titrer_contenu_dist($champs_contenu, $c = null, $longueur = 50) {
414
-	// trouver un champ texte non vide
415
-	$t = '';
416
-	foreach ($champs_contenu as $champ) {
417
-		if ($t = _request($champ, $c)) {
418
-			break;
419
-		}
420
-	}
421
-
422
-	if ($t) {
423
-		include_spip('inc/texte_mini');
424
-		$t = couper($t, $longueur, '...');
425
-	}
426
-
427
-	return $t;
414
+    // trouver un champ texte non vide
415
+    $t = '';
416
+    foreach ($champs_contenu as $champ) {
417
+        if ($t = _request($champ, $c)) {
418
+            break;
419
+        }
420
+    }
421
+
422
+    if ($t) {
423
+        include_spip('inc/texte_mini');
424
+        $t = couper($t, $longueur, '...');
425
+    }
426
+
427
+    return $t;
428 428
 }
429 429
 
430 430
 /**
@@ -446,22 +446,22 @@  discard block
 block discarded – undo
446 446
  *      - array sinon couples ('$prefixe$colonne => md5)
447 447
  **/
448 448
 function controles_md5(array $data, string $prefixe = 'ctr_', string $format = 'html') {
449
-	$ctr = [];
450
-	foreach ($data as $key => $val) {
451
-		$m = md5($val ?? '');
452
-		$k = $prefixe . $key;
453
-
454
-		$ctr[$k] = match ($format) {
455
-			'html' => "<input type='hidden' value='$m' name='$k' />",
456
-			default => $m,
457
-		};
458
-	}
459
-
460
-	if ($format === 'html') {
461
-		return "\n\n<!-- controles md5 -->\n" . implode("\n", $ctr) . "\n\n";
462
-	} else {
463
-		return $ctr;
464
-	}
449
+    $ctr = [];
450
+    foreach ($data as $key => $val) {
451
+        $m = md5($val ?? '');
452
+        $k = $prefixe . $key;
453
+
454
+        $ctr[$k] = match ($format) {
455
+            'html' => "<input type='hidden' value='$m' name='$k' />",
456
+            default => $m,
457
+        };
458
+    }
459
+
460
+    if ($format === 'html') {
461
+        return "\n\n<!-- controles md5 -->\n" . implode("\n", $ctr) . "\n\n";
462
+    } else {
463
+        return $ctr;
464
+    }
465 465
 }
466 466
 
467 467
 /**
@@ -500,80 +500,80 @@  discard block
 block discarded – undo
500 500
  *     - post : le contenu posté
501 501
  **/
502 502
 function controler_contenu($type, $id, $options = [], $c = false, $serveur = '') {
503
-	include_spip('inc/filtres');
504
-
505
-	$table_objet = table_objet($type);
506
-	$spip_table_objet = table_objet_sql($type);
507
-	$trouver_table = charger_fonction('trouver_table', 'base');
508
-	$desc = $trouver_table($table_objet, $serveur);
509
-
510
-	// Appels incomplets (sans $c)
511
-	if (!is_array($c)) {
512
-		$c = [];
513
-		foreach ($desc['field'] as $champ => $ignore) {
514
-			if (_request($champ)) {
515
-				$c[$champ] = _request($champ);
516
-			}
517
-		}
518
-	}
519
-
520
-	// Securite : certaines variables ne sont jamais acceptees ici
521
-	// car elles ne relevent pas de autoriser(article, modifier) ;
522
-	// il faut passer par instituer_XX()
523
-	// TODO: faut-il passer ces variables interdites
524
-	// dans un fichier de description separe ?
525
-	unset($c['statut']);
526
-	unset($c['id_parent']);
527
-	unset($c['id_rubrique']);
528
-	unset($c['id_secteur']);
529
-
530
-	// Gerer les champs non vides
531
-	if (isset($options['nonvide']) && is_array($options['nonvide'])) {
532
-		foreach ($options['nonvide'] as $champ => $sinon) {
533
-			if ($c[$champ] === '') {
534
-				$c[$champ] = $sinon;
535
-			}
536
-		}
537
-	}
538
-
539
-	// N'accepter que les champs qui existent
540
-	// [TODO] ici aussi on peut valider les contenus en fonction du type
541
-	$champs = [];
542
-	foreach ($desc['field'] as $champ => $ignore) {
543
-		if (isset($c[$champ])) {
544
-			$champs[$champ] = $c[$champ];
545
-		}
546
-	}
547
-
548
-	// Nettoyer les valeurs
549
-	$champs = array_map('corriger_caracteres', $champs);
550
-
551
-	// Envoyer aux plugins
552
-	$champs = pipeline(
553
-		'pre_edition',
554
-		[
555
-			'args' => [
556
-				'table' => $spip_table_objet, // compatibilite
557
-				'table_objet' => $table_objet,
558
-				'spip_table_objet' => $spip_table_objet,
559
-				'type' => $type,
560
-				'id_objet' => $id,
561
-				'champs' => $options['champs'] ?? [], // [doc] c'est quoi ?
562
-				'action' => 'controler',
563
-				'serveur' => $serveur,
564
-			],
565
-			'data' => $champs
566
-		]
567
-	);
568
-
569
-	if (!$champs) {
570
-		return false;
571
-	}
572
-
573
-	// Verifier si les mises a jour sont pertinentes, datees, en conflit etc
574
-	$conflits = controler_md5($champs, $_POST, $type, $id, $serveur, $options['prefix'] ?? 'ctr_');
575
-
576
-	return $conflits;
503
+    include_spip('inc/filtres');
504
+
505
+    $table_objet = table_objet($type);
506
+    $spip_table_objet = table_objet_sql($type);
507
+    $trouver_table = charger_fonction('trouver_table', 'base');
508
+    $desc = $trouver_table($table_objet, $serveur);
509
+
510
+    // Appels incomplets (sans $c)
511
+    if (!is_array($c)) {
512
+        $c = [];
513
+        foreach ($desc['field'] as $champ => $ignore) {
514
+            if (_request($champ)) {
515
+                $c[$champ] = _request($champ);
516
+            }
517
+        }
518
+    }
519
+
520
+    // Securite : certaines variables ne sont jamais acceptees ici
521
+    // car elles ne relevent pas de autoriser(article, modifier) ;
522
+    // il faut passer par instituer_XX()
523
+    // TODO: faut-il passer ces variables interdites
524
+    // dans un fichier de description separe ?
525
+    unset($c['statut']);
526
+    unset($c['id_parent']);
527
+    unset($c['id_rubrique']);
528
+    unset($c['id_secteur']);
529
+
530
+    // Gerer les champs non vides
531
+    if (isset($options['nonvide']) && is_array($options['nonvide'])) {
532
+        foreach ($options['nonvide'] as $champ => $sinon) {
533
+            if ($c[$champ] === '') {
534
+                $c[$champ] = $sinon;
535
+            }
536
+        }
537
+    }
538
+
539
+    // N'accepter que les champs qui existent
540
+    // [TODO] ici aussi on peut valider les contenus en fonction du type
541
+    $champs = [];
542
+    foreach ($desc['field'] as $champ => $ignore) {
543
+        if (isset($c[$champ])) {
544
+            $champs[$champ] = $c[$champ];
545
+        }
546
+    }
547
+
548
+    // Nettoyer les valeurs
549
+    $champs = array_map('corriger_caracteres', $champs);
550
+
551
+    // Envoyer aux plugins
552
+    $champs = pipeline(
553
+        'pre_edition',
554
+        [
555
+            'args' => [
556
+                'table' => $spip_table_objet, // compatibilite
557
+                'table_objet' => $table_objet,
558
+                'spip_table_objet' => $spip_table_objet,
559
+                'type' => $type,
560
+                'id_objet' => $id,
561
+                'champs' => $options['champs'] ?? [], // [doc] c'est quoi ?
562
+                'action' => 'controler',
563
+                'serveur' => $serveur,
564
+            ],
565
+            'data' => $champs
566
+        ]
567
+    );
568
+
569
+    if (!$champs) {
570
+        return false;
571
+    }
572
+
573
+    // Verifier si les mises a jour sont pertinentes, datees, en conflit etc
574
+    $conflits = controler_md5($champs, $_POST, $type, $id, $serveur, $options['prefix'] ?? 'ctr_');
575
+
576
+    return $conflits;
577 577
 }
578 578
 
579 579
 
@@ -603,66 +603,66 @@  discard block
 block discarded – undo
603 603
  *     - post : le contenu posté
604 604
  **/
605 605
 function controler_md5(&$champs, $ctr, $type, $id, $serveur, $prefix = 'ctr_') {
606
-	$spip_table_objet = table_objet_sql($type);
607
-	$id_table_objet = id_table_objet($type);
608
-
609
-	// Controle des MD5 envoyes
610
-	// On elimine les donnees non modifiees par le formulaire (mais
611
-	// potentiellement modifiees entre temps par un autre utilisateur)
612
-	foreach ($champs as $key => $val) {
613
-		if (
614
-			isset($ctr[$prefix . $key])
615
-			&& ($m = $ctr[$prefix . $key])
616
-			&& (is_scalar($val) && $m == md5($val))
617
-		) {
618
-			unset($champs[$key]);
619
-		}
620
-	}
621
-	if (!$champs) {
622
-		return;
623
-	}
624
-
625
-	// On veut savoir si notre modif va avoir un impact
626
-	// par rapport aux donnees contenues dans la base
627
-	// (qui peuvent etre differentes de celles ayant servi a calculer le ctr)
628
-	$s = sql_fetsel(array_keys($champs), $spip_table_objet, "$id_table_objet=$id", $serveur);
629
-	$intact = true;
630
-	foreach ($champs as $ch => $val) {
631
-		$intact &= ($s[$ch] == $val);
632
-	}
633
-	if ($intact) {
634
-		return;
635
-	}
636
-
637
-	// Detection de conflits :
638
-	// On verifie si notre modif ne provient pas d'un formulaire
639
-	// genere a partir de donnees modifiees dans l'intervalle ; ici
640
-	// on compare a ce qui est dans la base, et on bloque en cas
641
-	// de conflit.
642
-	$ctrh = $ctrq = $conflits = [];
643
-	foreach (array_keys($champs) as $key) {
644
-		if (isset($ctr[$prefix . $key]) && ($m = $ctr[$prefix . $key])) {
645
-			$ctrh[$key] = $m;
646
-			$ctrq[] = $key;
647
-		}
648
-	}
649
-	if ($ctrq) {
650
-		$ctrq = sql_fetsel($ctrq, $spip_table_objet, "$id_table_objet=$id", $serveur);
651
-		foreach ($ctrh as $key => $m) {
652
-			if (
653
-				$m != md5((string) $ctrq[$key])
654
-				&& $champs[$key] !== $ctrq[$key]
655
-			) {
656
-				$conflits[$key] = [
657
-					'base' => $ctrq[$key],
658
-					'post' => $champs[$key]
659
-				];
660
-				unset($champs[$key]); # stocker quand meme les modifs ?
661
-			}
662
-		}
663
-	}
664
-
665
-	return $conflits;
606
+    $spip_table_objet = table_objet_sql($type);
607
+    $id_table_objet = id_table_objet($type);
608
+
609
+    // Controle des MD5 envoyes
610
+    // On elimine les donnees non modifiees par le formulaire (mais
611
+    // potentiellement modifiees entre temps par un autre utilisateur)
612
+    foreach ($champs as $key => $val) {
613
+        if (
614
+            isset($ctr[$prefix . $key])
615
+            && ($m = $ctr[$prefix . $key])
616
+            && (is_scalar($val) && $m == md5($val))
617
+        ) {
618
+            unset($champs[$key]);
619
+        }
620
+    }
621
+    if (!$champs) {
622
+        return;
623
+    }
624
+
625
+    // On veut savoir si notre modif va avoir un impact
626
+    // par rapport aux donnees contenues dans la base
627
+    // (qui peuvent etre differentes de celles ayant servi a calculer le ctr)
628
+    $s = sql_fetsel(array_keys($champs), $spip_table_objet, "$id_table_objet=$id", $serveur);
629
+    $intact = true;
630
+    foreach ($champs as $ch => $val) {
631
+        $intact &= ($s[$ch] == $val);
632
+    }
633
+    if ($intact) {
634
+        return;
635
+    }
636
+
637
+    // Detection de conflits :
638
+    // On verifie si notre modif ne provient pas d'un formulaire
639
+    // genere a partir de donnees modifiees dans l'intervalle ; ici
640
+    // on compare a ce qui est dans la base, et on bloque en cas
641
+    // de conflit.
642
+    $ctrh = $ctrq = $conflits = [];
643
+    foreach (array_keys($champs) as $key) {
644
+        if (isset($ctr[$prefix . $key]) && ($m = $ctr[$prefix . $key])) {
645
+            $ctrh[$key] = $m;
646
+            $ctrq[] = $key;
647
+        }
648
+    }
649
+    if ($ctrq) {
650
+        $ctrq = sql_fetsel($ctrq, $spip_table_objet, "$id_table_objet=$id", $serveur);
651
+        foreach ($ctrh as $key => $m) {
652
+            if (
653
+                $m != md5((string) $ctrq[$key])
654
+                && $champs[$key] !== $ctrq[$key]
655
+            ) {
656
+                $conflits[$key] = [
657
+                    'base' => $ctrq[$key],
658
+                    'post' => $champs[$key]
659
+                ];
660
+                unset($champs[$key]); # stocker quand meme les modifs ?
661
+            }
662
+        }
663
+    }
664
+
665
+    return $conflits;
666 666
 }
667 667
 
668 668
 /**
@@ -674,9 +674,9 @@  discard block
 block discarded – undo
674 674
  * @return string
675 675
  */
676 676
 function display_conflit_champ($x) {
677
-	if (strstr($x, "\n") || strlen($x) > 80) {
678
-		return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
679
-	} else {
680
-		return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
681
-	}
677
+    if (strstr($x, "\n") || strlen($x) > 80) {
678
+        return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
679
+    } else {
680
+        return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
681
+    }
682 682
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 		$res['message_ok'] = _T('info_modification_enregistree');
100 100
 		if ($retour) {
101 101
 			if (str_starts_with($retour, 'javascript:')) {
102
-				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
102
+				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/'.substr($retour, 11).'/*]]>*/</script>';
103 103
 				$res['editable'] = true;
104 104
 			} else {
105 105
 				$res['redirect'] = parametre_url($retour, $id_table_objet, $id);
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 				if (!isset($erreurs[$champ])) {
140 140
 					$erreurs[$champ] = '';
141 141
 				}
142
-				$erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
142
+				$erreurs[$champ] .= _T('alerte_modif_info_concourante')."<br /><textarea readonly='readonly' class='forml'>".entites_html($conflit['base']).'</textarea>';
143 143
 			}
144 144
 		}
145 145
 	}
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 	if (
220 220
 		$config_fonc
221 221
 		&& !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
222
-		&& $config_fonc !== $table_objet . '_edit_config'
222
+		&& $config_fonc !== $table_objet.'_edit_config'
223 223
 		&& ($args = test_formulaire_inclus_par_modele())
224 224
 		&& in_array($config_fonc, $args)
225 225
 	) {
@@ -231,12 +231,12 @@  discard block
 block discarded – undo
231 231
 	// Appel direct dans un squelette
232 232
 	if (!$row) {
233 233
 		if (!$new || $lier_trad) {
234
-			if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
234
+			if ($select = charger_fonction('precharger_'.$type, 'inc', true)) {
235 235
 				$row = $select($id, $id_parent, $lier_trad);
236 236
 				// si on a une fonction precharger, elle pu faire un reglage de langue
237 237
 				$lang_default = (empty($row['lang']) ? null : $row['lang']);
238 238
 			} else {
239
-				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . (int) $id);
239
+				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet.'='.(int) $id);
240 240
 			}
241 241
 			if (!$new) {
242 242
 				$md5 = controles_md5($row ?: []);
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 	if ($config_fonc) {
287 287
 		$contexte['config'] = $config = $config_fonc($contexte);
288 288
 		if (!$lang_default) {
289
-			$lang_default = $config['langue'] ?? session_get('lang') ;
289
+			$lang_default = $config['langue'] ?? session_get('lang');
290 290
 		}
291 291
 	}
292 292
 	$config += [
@@ -308,13 +308,13 @@  discard block
 block discarded – undo
308 308
 		unset($contexte['lang']);
309 309
 	}
310 310
 
311
-	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
311
+	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n".
312 312
 		($lier_trad
313
-			 ? "\n<input type='hidden' name='lier_trad' value='" .
314
-				$lier_trad .
315
-				"' />" .
316
-				"\n<input type='hidden' name='changer_lang' value='" .
317
-				$lang_default .
313
+			 ? "\n<input type='hidden' name='lier_trad' value='".
314
+				$lier_trad.
315
+				"' />".
316
+				"\n<input type='hidden' name='changer_lang' value='".
317
+				$lang_default.
318 318
 				"' />"
319 319
 			: '')
320 320
 		. $hidden
@@ -355,14 +355,14 @@  discard block
 block discarded – undo
355 355
 	$aider = charger_fonction('aider', 'inc');
356 356
 	if (strlen($texte) > 28 * 1024) {
357 357
 		$texte = str_replace("\r\n", "\n", $texte);
358
-		$pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
358
+		$pos = strpos($texte, "\n\n", 28 * 1024); // coupe para > 28 ko
359 359
 		if ($pos > 0 && $pos < 32 * 1024) {
360
-			$debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
360
+			$debut = substr($texte, 0, $pos)."\n\n<!--SPIP-->\n";
361 361
 			$suite = substr($texte, $pos + 2);
362 362
 		} else {
363
-			$pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
363
+			$pos = strpos($texte, ' ', 28 * 1024); // sinon coupe espace
364 364
 			if (!($pos > 0 && $pos < 32 * 1024)) {
365
-				$pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
365
+				$pos = 28 * 1024; // au pire (pas d'espace trouv'e)
366 366
 				$decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
367 367
 			} else {
368 368
 				$decalage = 1;
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
 	$ctr = [];
450 450
 	foreach ($data as $key => $val) {
451 451
 		$m = md5($val ?? '');
452
-		$k = $prefixe . $key;
452
+		$k = $prefixe.$key;
453 453
 
454 454
 		$ctr[$k] = match ($format) {
455 455
 			'html' => "<input type='hidden' value='$m' name='$k' />",
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 	}
459 459
 
460 460
 	if ($format === 'html') {
461
-		return "\n\n<!-- controles md5 -->\n" . implode("\n", $ctr) . "\n\n";
461
+		return "\n\n<!-- controles md5 -->\n".implode("\n", $ctr)."\n\n";
462 462
 	} else {
463 463
 		return $ctr;
464 464
 	}
@@ -611,8 +611,8 @@  discard block
 block discarded – undo
611 611
 	// potentiellement modifiees entre temps par un autre utilisateur)
612 612
 	foreach ($champs as $key => $val) {
613 613
 		if (
614
-			isset($ctr[$prefix . $key])
615
-			&& ($m = $ctr[$prefix . $key])
614
+			isset($ctr[$prefix.$key])
615
+			&& ($m = $ctr[$prefix.$key])
616 616
 			&& (is_scalar($val) && $m == md5($val))
617 617
 		) {
618 618
 			unset($champs[$key]);
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 	// de conflit.
642 642
 	$ctrh = $ctrq = $conflits = [];
643 643
 	foreach (array_keys($champs) as $key) {
644
-		if (isset($ctr[$prefix . $key]) && ($m = $ctr[$prefix . $key])) {
644
+		if (isset($ctr[$prefix.$key]) && ($m = $ctr[$prefix.$key])) {
645 645
 			$ctrh[$key] = $m;
646 646
 			$ctrq[] = $key;
647 647
 		}
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
  */
676 676
 function display_conflit_champ($x) {
677 677
 	if (strstr($x, "\n") || strlen($x) > 80) {
678
-		return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
678
+		return "<textarea style='width:99%; height:10em;'>".entites_html($x)."</textarea>\n";
679 679
 	} else {
680
-		return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
680
+		return "<input type='text' size='40' style='width:99%' value=\"".entites_html($x)."\" />\n";
681 681
 	}
682 682
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_mini.php 2 patches
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 
@@ -34,20 +34,20 @@  discard block
 block discarded – undo
34 34
  * @return string URL nettoyée
35 35
  **/
36 36
 function resolve_path($url) {
37
-	[$url, $query] = array_pad(explode('?', $url, 2), 2, null);
38
-	while (
39
-		preg_match(',/\.?/,', (string) $url, $regs) # supprime // et /./
40
-		|| preg_match(',/[^/]*/\.\./,S', (string) $url, $regs)  # supprime /toto/../
41
-		|| preg_match(',^/\.\./,S', (string) $url, $regs) # supprime les /../ du haut
42
-	) {
43
-		$url = str_replace($regs[0], '/', (string) $url);
44
-	}
37
+    [$url, $query] = array_pad(explode('?', $url, 2), 2, null);
38
+    while (
39
+        preg_match(',/\.?/,', (string) $url, $regs) # supprime // et /./
40
+        || preg_match(',/[^/]*/\.\./,S', (string) $url, $regs)  # supprime /toto/../
41
+        || preg_match(',^/\.\./,S', (string) $url, $regs) # supprime les /../ du haut
42
+    ) {
43
+        $url = str_replace($regs[0], '/', (string) $url);
44
+    }
45 45
 
46
-	if ($query) {
47
-		$url .= '?' . $query;
48
-	}
46
+    if ($query) {
47
+        $url .= '?' . $query;
48
+    }
49 49
 
50
-	return '/' . preg_replace(',^/,S', '', (string) $url);
50
+    return '/' . preg_replace(',^/,S', '', (string) $url);
51 51
 }
52 52
 
53 53
 
@@ -68,40 +68,40 @@  discard block
 block discarded – undo
68 68
  **/
69 69
 function suivre_lien($url, $lien) {
70 70
 
71
-	$mot = null;
72
-	$get = null;
73
-	$hash = null;
74
-	if (preg_match(',^(mailto|javascript|data|tel|callto|file|ftp):,iS', $lien)) {
75
-		return $lien;
76
-	}
77
-	if (preg_match(';^((?:[a-z]{3,33}:)?//.*?)(/.*)?$;iS', $lien, $r)) {
78
-		$r = array_pad($r, 3, '');
71
+    $mot = null;
72
+    $get = null;
73
+    $hash = null;
74
+    if (preg_match(',^(mailto|javascript|data|tel|callto|file|ftp):,iS', $lien)) {
75
+        return $lien;
76
+    }
77
+    if (preg_match(';^((?:[a-z]{3,33}:)?//.*?)(/.*)?$;iS', $lien, $r)) {
78
+        $r = array_pad($r, 3, '');
79 79
 
80
-		return $r[1] . resolve_path($r[2]);
81
-	}
80
+        return $r[1] . resolve_path($r[2]);
81
+    }
82 82
 
83
-	# L'url site spip est un lien absolu aussi
84
-	if (isset($GLOBALS['meta']['adresse_site']) && $lien == $GLOBALS['meta']['adresse_site']) {
85
-		return $lien;
86
-	}
83
+    # L'url site spip est un lien absolu aussi
84
+    if (isset($GLOBALS['meta']['adresse_site']) && $lien == $GLOBALS['meta']['adresse_site']) {
85
+        return $lien;
86
+    }
87 87
 
88
-	# lien relatif, il faut verifier l'url de base
89
-	# commencer par virer la chaine de get de l'url de base
90
-	$dir = '/';
91
-	$debut = '';
92
-	if (preg_match(';^((?:[a-z]{3,7}:)?//[^/]+)(/.*?/?)?([^/#?]*)([?][^#]*)?(#.*)?$;S', $url, $regs)) {
93
-		$debut = $regs[1];
94
-		$dir = strlen($regs[2]) ? $regs[2] : '/';
95
-		$mot = $regs[3];
96
-		$get = $regs[4] ?? '';
97
-		$hash = $regs[5] ?? '';
98
-	}
99
-	return match (substr($lien, 0, 1)) {
100
-		'/' => $debut . resolve_path($lien),
101
-		'#' => $debut . resolve_path($dir . $mot . $get . $lien),
102
-		'' => $debut . resolve_path($dir . $mot . $get . $hash),
103
-		default => $debut . resolve_path($dir . $lien),
104
-	};
88
+    # lien relatif, il faut verifier l'url de base
89
+    # commencer par virer la chaine de get de l'url de base
90
+    $dir = '/';
91
+    $debut = '';
92
+    if (preg_match(';^((?:[a-z]{3,7}:)?//[^/]+)(/.*?/?)?([^/#?]*)([?][^#]*)?(#.*)?$;S', $url, $regs)) {
93
+        $debut = $regs[1];
94
+        $dir = strlen($regs[2]) ? $regs[2] : '/';
95
+        $mot = $regs[3];
96
+        $get = $regs[4] ?? '';
97
+        $hash = $regs[5] ?? '';
98
+    }
99
+    return match (substr($lien, 0, 1)) {
100
+        '/' => $debut . resolve_path($lien),
101
+        '#' => $debut . resolve_path($dir . $mot . $get . $lien),
102
+        '' => $debut . resolve_path($dir . $mot . $get . $hash),
103
+        default => $debut . resolve_path($dir . $lien),
104
+    };
105 105
 }
106 106
 
107 107
 
@@ -124,15 +124,15 @@  discard block
 block discarded – undo
124 124
  * @return string texte ou URL (en absolus)
125 125
  **/
126 126
 function url_absolue($url, $base = '') {
127
-	$url = trim((string) $url);
128
-	if (strlen($url = trim($url)) == 0) {
129
-		return '';
130
-	}
131
-	if (!$base) {
132
-		$base = url_de_base() . (_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
133
-	}
127
+    $url = trim((string) $url);
128
+    if (strlen($url = trim($url)) == 0) {
129
+        return '';
130
+    }
131
+    if (!$base) {
132
+        $base = url_de_base() . (_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
133
+    }
134 134
 
135
-	return suivre_lien($base, $url);
135
+    return suivre_lien($base, $url);
136 136
 }
137 137
 
138 138
 /**
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
  * @return string
144 144
  */
145 145
 function protocole_implicite($url_absolue) {
146
-	return preg_replace(';^[a-z]{3,7}://;i', '//', $url_absolue);
146
+    return preg_replace(';^[a-z]{3,7}://;i', '//', $url_absolue);
147 147
 }
148 148
 
149 149
 /**
@@ -154,16 +154,16 @@  discard block
 block discarded – undo
154 154
  */
155 155
 function protocole_verifier($url_absolue, $protocoles_autorises = ['http','https']) {
156 156
 
157
-	if (preg_match(';^([a-z]{3,7})://;i', $url_absolue, $m)) {
158
-		$protocole = $m[1];
159
-		if (
160
-			in_array($protocole, $protocoles_autorises)
161
-			|| in_array(strtolower($protocole), array_map('strtolower', $protocoles_autorises))
162
-		) {
163
-			return true;
164
-		}
165
-	}
166
-	return false;
157
+    if (preg_match(';^([a-z]{3,7})://;i', $url_absolue, $m)) {
158
+        $protocole = $m[1];
159
+        if (
160
+            in_array($protocole, $protocoles_autorises)
161
+            || in_array(strtolower($protocole), array_map('strtolower', $protocoles_autorises))
162
+        ) {
163
+            return true;
164
+        }
165
+    }
166
+    return false;
167 167
 }
168 168
 
169 169
 /**
@@ -180,28 +180,28 @@  discard block
 block discarded – undo
180 180
  * @return string texte avec des URLs absolues
181 181
  **/
182 182
 function liens_absolus($texte, $base = '') {
183
-	if (preg_match_all(',(<(a|link|image|img|script)\s[^<>]*(href|src)=[^<>]*>),imsS', $texte, $liens, PREG_SET_ORDER)) {
184
-		if (!function_exists('extraire_attribut')) {
185
-			include_spip('inc/filtres');
186
-		}
187
-		foreach ($liens as $lien) {
188
-			foreach (['href', 'src'] as $attr) {
189
-				$href = extraire_attribut($lien[0], $attr) ?? '';
190
-				if (
191
-					strlen((string) $href) > 0
192
-					&& !preg_match(';^((?:[a-z]{3,7}:)?//);iS', (string) $href)
193
-				) {
194
-					$abs = url_absolue($href, $base);
195
-					if (rtrim((string) $href, '/') !== rtrim($abs, '/') && !preg_match('/^#/', (string) $href)) {
196
-						$texte_lien = inserer_attribut($lien[0], $attr, $abs);
197
-						$texte = str_replace($lien[0], $texte_lien, $texte);
198
-					}
199
-				}
200
-			}
201
-		}
202
-	}
183
+    if (preg_match_all(',(<(a|link|image|img|script)\s[^<>]*(href|src)=[^<>]*>),imsS', $texte, $liens, PREG_SET_ORDER)) {
184
+        if (!function_exists('extraire_attribut')) {
185
+            include_spip('inc/filtres');
186
+        }
187
+        foreach ($liens as $lien) {
188
+            foreach (['href', 'src'] as $attr) {
189
+                $href = extraire_attribut($lien[0], $attr) ?? '';
190
+                if (
191
+                    strlen((string) $href) > 0
192
+                    && !preg_match(';^((?:[a-z]{3,7}:)?//);iS', (string) $href)
193
+                ) {
194
+                    $abs = url_absolue($href, $base);
195
+                    if (rtrim((string) $href, '/') !== rtrim($abs, '/') && !preg_match('/^#/', (string) $href)) {
196
+                        $texte_lien = inserer_attribut($lien[0], $attr, $abs);
197
+                        $texte = str_replace($lien[0], $texte_lien, $texte);
198
+                    }
199
+                }
200
+            }
201
+        }
202
+    }
203 203
 
204
-	return $texte;
204
+    return $texte;
205 205
 }
206 206
 
207 207
 
@@ -217,11 +217,11 @@  discard block
 block discarded – undo
217 217
  * @return string texte ou URL (en absolus)
218 218
  **/
219 219
 function abs_url($texte, $base = '') {
220
-	if ($GLOBALS['mode_abs_url'] == 'url') {
221
-		return url_absolue($texte, $base);
222
-	} else {
223
-		return liens_absolus($texte, $base);
224
-	}
220
+    if ($GLOBALS['mode_abs_url'] == 'url') {
221
+        return url_absolue($texte, $base);
222
+    } else {
223
+        return liens_absolus($texte, $base);
224
+    }
225 225
 }
226 226
 
227 227
 /**
@@ -234,11 +234,11 @@  discard block
 block discarded – undo
234 234
  * @return string
235 235
  */
236 236
 function spip_htmlspecialchars($string, $flags = null, $encoding = 'UTF-8', $double_encode = true) {
237
-	if (is_null($flags)) {
238
-		$flags = ENT_COMPAT | ENT_HTML401;
239
-	}
237
+    if (is_null($flags)) {
238
+        $flags = ENT_COMPAT | ENT_HTML401;
239
+    }
240 240
 
241
-	return htmlspecialchars($string, $flags, $encoding, $double_encode);
241
+    return htmlspecialchars($string, $flags, $encoding, $double_encode);
242 242
 }
243 243
 
244 244
 /**
@@ -251,9 +251,9 @@  discard block
 block discarded – undo
251 251
  * @return string
252 252
  */
253 253
 function spip_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = true) {
254
-	if (is_null($flags)) {
255
-		$flags = ENT_COMPAT | ENT_HTML401;
256
-	}
254
+    if (is_null($flags)) {
255
+        $flags = ENT_COMPAT | ENT_HTML401;
256
+    }
257 257
 
258
-	return htmlentities($string, $flags, $encoding, $double_encode);
258
+    return htmlentities($string, $flags, $encoding, $double_encode);
259 259
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -44,10 +44,10 @@  discard block
 block discarded – undo
44 44
 	}
45 45
 
46 46
 	if ($query) {
47
-		$url .= '?' . $query;
47
+		$url .= '?'.$query;
48 48
 	}
49 49
 
50
-	return '/' . preg_replace(',^/,S', '', (string) $url);
50
+	return '/'.preg_replace(',^/,S', '', (string) $url);
51 51
 }
52 52
 
53 53
 
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	if (preg_match(';^((?:[a-z]{3,33}:)?//.*?)(/.*)?$;iS', $lien, $r)) {
78 78
 		$r = array_pad($r, 3, '');
79 79
 
80
-		return $r[1] . resolve_path($r[2]);
80
+		return $r[1].resolve_path($r[2]);
81 81
 	}
82 82
 
83 83
 	# L'url site spip est un lien absolu aussi
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
 		$hash = $regs[5] ?? '';
98 98
 	}
99 99
 	return match (substr($lien, 0, 1)) {
100
-		'/' => $debut . resolve_path($lien),
101
-		'#' => $debut . resolve_path($dir . $mot . $get . $lien),
102
-		'' => $debut . resolve_path($dir . $mot . $get . $hash),
103
-		default => $debut . resolve_path($dir . $lien),
100
+		'/' => $debut.resolve_path($lien),
101
+		'#' => $debut.resolve_path($dir.$mot.$get.$lien),
102
+		'' => $debut.resolve_path($dir.$mot.$get.$hash),
103
+		default => $debut.resolve_path($dir.$lien),
104 104
 	};
105 105
 }
106 106
 
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 		return '';
130 130
 	}
131 131
 	if (!$base) {
132
-		$base = url_de_base() . (_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
132
+		$base = url_de_base().(_DIR_RACINE ? _DIR_RESTREINT_ABS : '');
133 133
 	}
134 134
 
135 135
 	return suivre_lien($base, $url);
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
  * @param array $protocoles_autorises
153 153
  * @return bool
154 154
  */
155
-function protocole_verifier($url_absolue, $protocoles_autorises = ['http','https']) {
155
+function protocole_verifier($url_absolue, $protocoles_autorises = ['http', 'https']) {
156 156
 
157 157
 	if (preg_match(';^([a-z]{3,7})://;i', $url_absolue, $m)) {
158 158
 		$protocole = $m[1];
Please login to merge, or discard this patch.
ecrire/inc/surligne.php 2 patches
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * @package SPIP\Core\Surligne
16 16
  **/
17 17
 if (!defined('_ECRIRE_INC_VERSION')) {
18
-	return;
18
+    return;
19 19
 }
20 20
 
21 21
 /**
@@ -34,43 +34,43 @@  discard block
 block discarded – undo
34 34
  *     Page HTML
35 35
  **/
36 36
 function surligner_mots($page, $surcharge_surligne = '') {
37
-	$surlignejs_engines = [
38
-		[
39
-			',' . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']) . ',i',
40
-			',recherche=([^&]+),i'
41
-		], //SPIP
42
-		[',^http://(www\.)?google\.,i', ',q=([^&]+),i'], // Google
43
-		[',^http://(www\.)?search\.yahoo\.,i', ',p=([^&]+),i'], // Yahoo
44
-		[',^http://(www\.)?search\.msn\.,i', ',q=([^&]+),i'], // MSN
45
-		[',^http://(www\.)?search\.live\.,i', ',query=([^&]+),i'], // MSN Live
46
-		[',^http://(www\.)?search\.aol\.,i', ',userQuery=([^&]+),i'], // AOL
47
-		[',^http://(www\.)?ask\.com,i', ',q=([^&]+),i'], // Ask.com
48
-		[',^http://(www\.)?altavista\.,i', ',q=([^&]+),i'], // AltaVista
49
-		[',^http://(www\.)?feedster\.,i', ',q=([^&]+),i'], // Feedster
50
-		[',^http://(www\.)?search\.lycos\.,i', ',q=([^&]+),i'], // Lycos
51
-		[',^http://(www\.)?alltheweb\.,i', ',q=([^&]+),i'], // AllTheWeb
52
-		[',^http://(www\.)?technorati\.com,i', ',([^\?\/]+)(?:\?.*)$,i'], // Technorati
53
-	];
37
+    $surlignejs_engines = [
38
+        [
39
+            ',' . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']) . ',i',
40
+            ',recherche=([^&]+),i'
41
+        ], //SPIP
42
+        [',^http://(www\.)?google\.,i', ',q=([^&]+),i'], // Google
43
+        [',^http://(www\.)?search\.yahoo\.,i', ',p=([^&]+),i'], // Yahoo
44
+        [',^http://(www\.)?search\.msn\.,i', ',q=([^&]+),i'], // MSN
45
+        [',^http://(www\.)?search\.live\.,i', ',query=([^&]+),i'], // MSN Live
46
+        [',^http://(www\.)?search\.aol\.,i', ',userQuery=([^&]+),i'], // AOL
47
+        [',^http://(www\.)?ask\.com,i', ',q=([^&]+),i'], // Ask.com
48
+        [',^http://(www\.)?altavista\.,i', ',q=([^&]+),i'], // AltaVista
49
+        [',^http://(www\.)?feedster\.,i', ',q=([^&]+),i'], // Feedster
50
+        [',^http://(www\.)?search\.lycos\.,i', ',q=([^&]+),i'], // Lycos
51
+        [',^http://(www\.)?alltheweb\.,i', ',q=([^&]+),i'], // AllTheWeb
52
+        [',^http://(www\.)?technorati\.com,i', ',([^\?\/]+)(?:\?.*)$,i'], // Technorati
53
+    ];
54 54
 
55 55
 
56
-	$ref = $_SERVER['HTTP_REFERER'] ?? null;
57
-	//avoid a js injection
58
-	if ($surcharge_surligne) {
59
-		$surcharge_surligne = preg_replace(",(?<!\\\\)((?:(?>\\\\){2})*)('),", '$1\\\$2', $surcharge_surligne);
60
-		$surcharge_surligne = str_replace('\\', '\\\\', $surcharge_surligne);
61
-		if ($GLOBALS['meta']['charset'] == 'utf-8') {
62
-			include_spip('inc/charsets');
63
-			if (!is_utf8($surcharge_surligne)) {
64
-				$surcharge_surligne = mb_convert_encoding($surcharge_surligne, 'UTF-8', 'ISO-8859-1');
65
-			}
66
-		}
67
-		$surcharge_surligne = preg_replace(',\*$,', '', trim($surcharge_surligne)); # supprimer un * final
68
-	}
69
-	foreach ($surlignejs_engines as $engine) {
70
-		if ($surcharge_surligne || (preg_match($engine[0], (string) $ref) && preg_match($engine[1], (string) $ref))) {
71
-			//good referrer found or var_recherche is not null
72
-			include_spip('inc/filtres');
73
-			$script = "
56
+    $ref = $_SERVER['HTTP_REFERER'] ?? null;
57
+    //avoid a js injection
58
+    if ($surcharge_surligne) {
59
+        $surcharge_surligne = preg_replace(",(?<!\\\\)((?:(?>\\\\){2})*)('),", '$1\\\$2', $surcharge_surligne);
60
+        $surcharge_surligne = str_replace('\\', '\\\\', $surcharge_surligne);
61
+        if ($GLOBALS['meta']['charset'] == 'utf-8') {
62
+            include_spip('inc/charsets');
63
+            if (!is_utf8($surcharge_surligne)) {
64
+                $surcharge_surligne = mb_convert_encoding($surcharge_surligne, 'UTF-8', 'ISO-8859-1');
65
+            }
66
+        }
67
+        $surcharge_surligne = preg_replace(',\*$,', '', trim($surcharge_surligne)); # supprimer un * final
68
+    }
69
+    foreach ($surlignejs_engines as $engine) {
70
+        if ($surcharge_surligne || (preg_match($engine[0], (string) $ref) && preg_match($engine[1], (string) $ref))) {
71
+            //good referrer found or var_recherche is not null
72
+            include_spip('inc/filtres');
73
+            $script = "
74 74
       <script type='text/javascript' src='" . url_absolue(find_in_path('javascript/SearchHighlight.js')) . "'></script>
75 75
       <script type='text/javascript'>
76 76
        var highlighter = function() {
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
             engines:[/^" . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']) . "/i,/recherche=([^&]+)/i],
83 83
             highlight:'.surlignable',
84 84
             nohighlight:'.pas_surlignable'" .
85
-				($surcharge_surligne ? ",
85
+                ($surcharge_surligne ? ",
86 86
             keys:'$surcharge_surligne'" : '') . ',
87 87
             min_length: 3
88 88
           });
@@ -93,14 +93,14 @@  discard block
 block discarded – undo
93 93
       };
94 94
       </script>
95 95
       ';
96
-			// on l'insere juste avant </head>, sinon tout en bas
97
-			if (is_null($l = strpos($page, '</head>'))) {
98
-				$l = strlen($page);
99
-			}
100
-			$page = substr_replace($page, $script, $l, 0);
101
-			break;
102
-		}
103
-	}
96
+            // on l'insere juste avant </head>, sinon tout en bas
97
+            if (is_null($l = strpos($page, '</head>'))) {
98
+                $l = strlen($page);
99
+            }
100
+            $page = substr_replace($page, $script, $l, 0);
101
+            break;
102
+        }
103
+    }
104 104
 
105
-	return $page;
105
+    return $page;
106 106
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 function surligner_mots($page, $surcharge_surligne = '') {
37 37
 	$surlignejs_engines = [
38 38
 		[
39
-			',' . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']) . ',i',
39
+			','.str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']).',i',
40 40
 			',recherche=([^&]+),i'
41 41
 		], //SPIP
42 42
 		[',^http://(www\.)?google\.,i', ',q=([^&]+),i'], // Google
@@ -71,19 +71,19 @@  discard block
 block discarded – undo
71 71
 			//good referrer found or var_recherche is not null
72 72
 			include_spip('inc/filtres');
73 73
 			$script = "
74
-      <script type='text/javascript' src='" . url_absolue(find_in_path('javascript/SearchHighlight.js')) . "'></script>
74
+      <script type='text/javascript' src='" . url_absolue(find_in_path('javascript/SearchHighlight.js'))."'></script>
75 75
       <script type='text/javascript'>
76 76
        var highlighter = function() {
77 77
 		  jQuery(this).SearchHighlight({
78
-            tag_name:'" . (html5_permis() ? 'mark' : 'span') . "',
78
+            tag_name:'" . (html5_permis() ? 'mark' : 'span')."',
79 79
             style_name:'spip_surligne',
80 80
             exact:'whole',
81 81
             style_name_suffix:false,
82
-            engines:[/^" . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site']) . "/i,/recherche=([^&]+)/i],
82
+            engines:[/^" . str_replace(['/', '.'], ['\/', '\.'], (string) $GLOBALS['meta']['adresse_site'])."/i,/recherche=([^&]+)/i],
83 83
             highlight:'.surlignable',
84 84
             nohighlight:'.pas_surlignable'" .
85 85
 				($surcharge_surligne ? ",
86
-            keys:'$surcharge_surligne'" : '') . ',
86
+            keys:'$surcharge_surligne'" : '').',
87 87
             min_length: 3
88 88
           });
89 89
 	  }
Please login to merge, or discard this patch.
ecrire/inc/xml.php 2 patches
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 
@@ -46,24 +46,24 @@  discard block
 block discarded – undo
46 46
  *     - false si l'arbre xml ne peut être créé ou est vide
47 47
  **/
48 48
 function spip_xml_load($fichier, $strict = true, $clean = true, $taille_max = 1_048_576, $datas = '', $profondeur = -1) {
49
-	$contenu = '';
50
-	if (tester_url_absolue($fichier)) {
51
-		include_spip('inc/distant');
52
-		$contenu = recuperer_url($fichier, ['taille_max' => $taille_max, 'datas' => $datas]);
53
-		$contenu = $contenu['page'] ?? '';
54
-	} else {
55
-		lire_fichier($fichier, $contenu);
56
-	}
57
-	$arbre = [];
58
-	if ($contenu) {
59
-		$arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
60
-	}
49
+    $contenu = '';
50
+    if (tester_url_absolue($fichier)) {
51
+        include_spip('inc/distant');
52
+        $contenu = recuperer_url($fichier, ['taille_max' => $taille_max, 'datas' => $datas]);
53
+        $contenu = $contenu['page'] ?? '';
54
+    } else {
55
+        lire_fichier($fichier, $contenu);
56
+    }
57
+    $arbre = [];
58
+    if ($contenu) {
59
+        $arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
60
+    }
61 61
 
62
-	return count($arbre) ? $arbre : false;
62
+    return count($arbre) ? $arbre : false;
63 63
 }
64 64
 
65 65
 if (!defined('_SPIP_XML_TAG_SPLIT')) {
66
-	define('_SPIP_XML_TAG_SPLIT', '{<([^:>][^>]*?)>}sS');
66
+    define('_SPIP_XML_TAG_SPLIT', '{<([^:>][^>]*?)>}sS');
67 67
 }
68 68
 
69 69
 /**
@@ -82,150 +82,150 @@  discard block
 block discarded – undo
82 82
  *     - false si l'arbre xml ne peut être créé ou est vide
83 83
  **/
84 84
 function spip_xml_parse(&$texte, $strict = true, $clean = true, $profondeur = -1) {
85
-	$out = [];
86
-	// enlever les commentaires
87
-	$charset = 'AUTO';
88
-	if ($clean) {
89
-		if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
90
-			$charset = $regs[2];
91
-		}
92
-		$texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
93
-		$texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
94
-		include_spip('inc/charsets');
95
-		$clean = $charset;
96
-		//$texte = importer_charset($texte,$charset);
97
-	}
98
-	if (is_string($clean)) {
99
-		$charset = $clean;
100
-	}
101
-	$txt = $texte;
85
+    $out = [];
86
+    // enlever les commentaires
87
+    $charset = 'AUTO';
88
+    if ($clean) {
89
+        if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
90
+            $charset = $regs[2];
91
+        }
92
+        $texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
93
+        $texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
94
+        include_spip('inc/charsets');
95
+        $clean = $charset;
96
+        //$texte = importer_charset($texte,$charset);
97
+    }
98
+    if (is_string($clean)) {
99
+        $charset = $clean;
100
+    }
101
+    $txt = $texte;
102 102
 
103
-	// tant qu'il y a des tags
104
-	$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
105
-	while ((is_countable($chars) ? count($chars) : 0) >= 2) {
106
-		// tag ouvrant
107
-		//$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
103
+    // tant qu'il y a des tags
104
+    $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
105
+    while ((is_countable($chars) ? count($chars) : 0) >= 2) {
106
+        // tag ouvrant
107
+        //$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
108 108
 
109
-		// $before doit etre vide ou des espaces uniquements!
110
-		$before = trim($chars[0]);
109
+        // $before doit etre vide ou des espaces uniquements!
110
+        $before = trim($chars[0]);
111 111
 
112
-		if (strlen($before) > 0) {
113
-			return importer_charset($texte, $charset);
114
-		}//$texte; // before non vide, donc on est dans du texte
112
+        if (strlen($before) > 0) {
113
+            return importer_charset($texte, $charset);
114
+        }//$texte; // before non vide, donc on est dans du texte
115 115
 
116
-		$tag = rtrim($chars[1]);
117
-		$txt = $chars[2];
116
+        $tag = rtrim($chars[1]);
117
+        $txt = $chars[2];
118 118
 
119
-		if (str_starts_with($tag, '![CDATA[')) {
120
-			return importer_charset($texte, $charset);
121
-		}//$texte;
122
-		if (str_ends_with($tag, '/')) { // self closing tag
123
-			$tag = rtrim(substr($tag, 0, strlen($tag) - 1));
124
-			$out[$tag][] = '';
125
-		} else {
126
-			$closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
127
-			$closing_tag = reset($closing_tag);
128
-			// tag fermant
129
-			$ncclos = strlen("</$closing_tag>");
130
-			$p = strpos($txt, (string) "</$closing_tag>");
131
-			if ($p !== false && strpos($txt, '<') < $p) {
132
-				$nclose = 0;
133
-				$nopen = 0;
134
-				$d = 0;
135
-				while (
136
-					$p !== false
137
-					&& ($morceau = substr($txt, $d, $p - $d))
138
-					&& ($nopen += preg_match_all(
139
-						'{<' . preg_quote((string) $closing_tag) . '(\s*>|\s[^>]*[^/>]>)}is',
140
-						$morceau,
141
-						$matches,
142
-						PREG_SET_ORDER
143
-					)) > $nclose
144
-				) {
145
-					$nclose++;
146
-					$d = $p + $ncclos;
147
-					$p = strpos($txt, (string) "</$closing_tag>", $d);
148
-				}
149
-			}
150
-			if ($p === false) {
151
-				if ($strict) {
152
-					$out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
119
+        if (str_starts_with($tag, '![CDATA[')) {
120
+            return importer_charset($texte, $charset);
121
+        }//$texte;
122
+        if (str_ends_with($tag, '/')) { // self closing tag
123
+            $tag = rtrim(substr($tag, 0, strlen($tag) - 1));
124
+            $out[$tag][] = '';
125
+        } else {
126
+            $closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
127
+            $closing_tag = reset($closing_tag);
128
+            // tag fermant
129
+            $ncclos = strlen("</$closing_tag>");
130
+            $p = strpos($txt, (string) "</$closing_tag>");
131
+            if ($p !== false && strpos($txt, '<') < $p) {
132
+                $nclose = 0;
133
+                $nopen = 0;
134
+                $d = 0;
135
+                while (
136
+                    $p !== false
137
+                    && ($morceau = substr($txt, $d, $p - $d))
138
+                    && ($nopen += preg_match_all(
139
+                        '{<' . preg_quote((string) $closing_tag) . '(\s*>|\s[^>]*[^/>]>)}is',
140
+                        $morceau,
141
+                        $matches,
142
+                        PREG_SET_ORDER
143
+                    )) > $nclose
144
+                ) {
145
+                    $nclose++;
146
+                    $d = $p + $ncclos;
147
+                    $p = strpos($txt, (string) "</$closing_tag>", $d);
148
+                }
149
+            }
150
+            if ($p === false) {
151
+                if ($strict) {
152
+                    $out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
153 153
 
154
-					return $out;
155
-				} else {
156
-					return importer_charset($texte, $charset);
157
-				}//$texte // un tag qui constitue du texte a reporter dans $before
158
-			}
159
-			$content = substr($txt, 0, $p);
160
-			$txt = substr($txt, $p + $ncclos);
161
-			if ($profondeur == 0 || !str_contains($content, '<')) { // eviter une recursion si pas utile
162
-			$out[$tag][] = importer_charset($content, $charset);
163
-			}//$content;
164
-			else {
165
-				$out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
166
-			}
167
-		}
168
-		$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
169
-	}
170
-	if (count($out) && (strlen(trim($txt)) == 0)) {
171
-		return $out;
172
-	} else {
173
-		return importer_charset($texte, $charset);
174
-	}//$texte;
154
+                    return $out;
155
+                } else {
156
+                    return importer_charset($texte, $charset);
157
+                }//$texte // un tag qui constitue du texte a reporter dans $before
158
+            }
159
+            $content = substr($txt, 0, $p);
160
+            $txt = substr($txt, $p + $ncclos);
161
+            if ($profondeur == 0 || !str_contains($content, '<')) { // eviter une recursion si pas utile
162
+            $out[$tag][] = importer_charset($content, $charset);
163
+            }//$content;
164
+            else {
165
+                $out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
166
+            }
167
+        }
168
+        $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
169
+    }
170
+    if (count($out) && (strlen(trim($txt)) == 0)) {
171
+        return $out;
172
+    } else {
173
+        return importer_charset($texte, $charset);
174
+    }//$texte;
175 175
 }
176 176
 
177 177
 function spip_xml_aplatit($arbre, $separateur = ' ') {
178
-	$s = '';
179
-	if (is_array($arbre)) {
180
-		foreach ($arbre as $tag => $feuille) {
181
-			if (is_array($feuille)) {
182
-				if ($tag !== (int) $tag) {
183
-					$f = spip_xml_aplatit($feuille, $separateur);
184
-					if (strlen((string) $f)) {
185
-						$tagf = explode(' ', $tag);
186
-						$tagf = $tagf[0];
187
-						$s .= "<$tag>$f</$tagf>";
188
-					} else {
189
-						$s .= "<$tag />";
190
-					}
191
-				} else {
192
-					$s .= spip_xml_aplatit($feuille);
193
-				}
194
-				$s .= $separateur;
195
-			} else {
196
-				$s .= "$feuille$separateur";
197
-			}
198
-		}
199
-	}
178
+    $s = '';
179
+    if (is_array($arbre)) {
180
+        foreach ($arbre as $tag => $feuille) {
181
+            if (is_array($feuille)) {
182
+                if ($tag !== (int) $tag) {
183
+                    $f = spip_xml_aplatit($feuille, $separateur);
184
+                    if (strlen((string) $f)) {
185
+                        $tagf = explode(' ', $tag);
186
+                        $tagf = $tagf[0];
187
+                        $s .= "<$tag>$f</$tagf>";
188
+                    } else {
189
+                        $s .= "<$tag />";
190
+                    }
191
+                } else {
192
+                    $s .= spip_xml_aplatit($feuille);
193
+                }
194
+                $s .= $separateur;
195
+            } else {
196
+                $s .= "$feuille$separateur";
197
+            }
198
+        }
199
+    }
200 200
 
201
-	return strlen((string) $separateur) ? substr($s, 0, -strlen((string) $separateur)) : $s;
201
+    return strlen((string) $separateur) ? substr($s, 0, -strlen((string) $separateur)) : $s;
202 202
 }
203 203
 
204 204
 function spip_xml_tagname($tag) {
205
-	if (preg_match(',^([a-z][\w:]*),i', (string) $tag, $reg)) {
206
-		return $reg[1];
207
-	}
205
+    if (preg_match(',^([a-z][\w:]*),i', (string) $tag, $reg)) {
206
+        return $reg[1];
207
+    }
208 208
 
209
-	return '';
209
+    return '';
210 210
 }
211 211
 
212 212
 function spip_xml_decompose_tag($tag) {
213
-	$tagname = spip_xml_tagname($tag);
214
-	$liste = [];
215
-	$tag = ltrim(strpbrk((string) $tag, " \n\t"));
216
-	$p = strpos($tag, '=');
217
-	while ($p !== false) {
218
-		$attr = trim(substr($tag, 0, $p));
219
-		$tag = ltrim(substr($tag, $p + 1));
220
-		$quote = $tag[0];
221
-		$p = strpos($tag, $quote, 1);
222
-		$cont = substr($tag, 1, $p - 1);
223
-		$liste[$attr] = $cont;
224
-		$tag = substr($tag, $p + 1);
225
-		$p = strpos($tag, '=');
226
-	}
213
+    $tagname = spip_xml_tagname($tag);
214
+    $liste = [];
215
+    $tag = ltrim(strpbrk((string) $tag, " \n\t"));
216
+    $p = strpos($tag, '=');
217
+    while ($p !== false) {
218
+        $attr = trim(substr($tag, 0, $p));
219
+        $tag = ltrim(substr($tag, $p + 1));
220
+        $quote = $tag[0];
221
+        $p = strpos($tag, $quote, 1);
222
+        $cont = substr($tag, 1, $p - 1);
223
+        $liste[$attr] = $cont;
224
+        $tag = substr($tag, $p + 1);
225
+        $p = strpos($tag, '=');
226
+    }
227 227
 
228
-	return [$tagname, $liste];
228
+    return [$tagname, $liste];
229 229
 }
230 230
 
231 231
 /**
@@ -248,21 +248,21 @@  discard block
 block discarded – undo
248 248
  *     false si aucun élément ne valide l'expression régulière, true sinon.
249 249
  **/
250 250
 function spip_xml_match_nodes($regexp, &$arbre, &$matches, $init = true) {
251
-	if ($init) {
252
-		$matches = [];
253
-	}
254
-	if (is_array($arbre) && count($arbre)) {
255
-		foreach (array_keys($arbre) as $tag) {
256
-			if (preg_match($regexp, $tag)) {
257
-				$matches[$tag] = &$arbre[$tag];
258
-			}
259
-			if (is_array($arbre[$tag])) {
260
-				foreach (array_keys($arbre[$tag]) as $occurences) {
261
-					spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
262
-				}
263
-			}
264
-		}
265
-	}
251
+    if ($init) {
252
+        $matches = [];
253
+    }
254
+    if (is_array($arbre) && count($arbre)) {
255
+        foreach (array_keys($arbre) as $tag) {
256
+            if (preg_match($regexp, $tag)) {
257
+                $matches[$tag] = &$arbre[$tag];
258
+            }
259
+            if (is_array($arbre[$tag])) {
260
+                foreach (array_keys($arbre[$tag]) as $occurences) {
261
+                    spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
262
+                }
263
+            }
264
+        }
265
+    }
266 266
 
267
-	return (is_countable($matches) ? count($matches) : 0);
267
+    return (is_countable($matches) ? count($matches) : 0);
268 268
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -136,7 +136,7 @@
 block discarded – undo
136 136
 					$p !== false
137 137
 					&& ($morceau = substr($txt, $d, $p - $d))
138 138
 					&& ($nopen += preg_match_all(
139
-						'{<' . preg_quote((string) $closing_tag) . '(\s*>|\s[^>]*[^/>]>)}is',
139
+						'{<'.preg_quote((string) $closing_tag).'(\s*>|\s[^>]*[^/>]>)}is',
140 140
 						$morceau,
141 141
 						$matches,
142 142
 						PREG_SET_ORDER
Please login to merge, or discard this patch.
ecrire/inc/distant.php 3 patches
Indentation   +1079 added lines, -1079 removed lines patch added patch discarded remove patch
@@ -17,32 +17,32 @@  discard block
 block discarded – undo
17 17
  * @package SPIP\Core\Distant
18 18
  **/
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
24
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
25 25
 }
26 26
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
27
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28 28
 }
29 29
 if (!defined('_INC_DISTANT_USER_AGENT')) {
30
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31 31
 }
32 32
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
33
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
33
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
34 34
 }
35 35
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
36
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37 37
 }
38 38
 
39 39
 define('_REGEXP_COPIE_LOCALE', ',' 	.
40
-	preg_replace(
41
-		'@^https?:@',
42
-		'https?:',
43
-		($GLOBALS['meta']['adresse_site'] ?? '')
44
-	)
45
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
40
+    preg_replace(
41
+        '@^https?:@',
42
+        'https?:',
43
+        ($GLOBALS['meta']['adresse_site'] ?? '')
44
+    )
45
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
46 46
 
47 47
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
48 48
 
@@ -71,106 +71,106 @@  discard block
 block discarded – undo
71 71
  */
72 72
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
73 73
 
74
-	// si c'est la protection de soi-meme, retourner le path
75
-	if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
-		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
-
78
-		return @file_exists($source) ? $source : false;
79
-	}
80
-
81
-	if (is_null($local)) {
82
-		$local = fichier_copie_locale($source);
83
-	} else {
84
-		if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
-			$local = substr($local, strlen((string) _DIR_RACINE));
86
-		}
87
-	}
88
-
89
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
-	// par exemple un fichier qui ne figure pas dans nos documents ;
91
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
-	if (!$local) {
93
-		return false;
94
-	}
95
-
96
-	$localrac = _DIR_RACINE . $local;
97
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
98
-
99
-	// test d'existence du fichier
100
-	if ($mode === 'test') {
101
-		return $t ? $local : '';
102
-	}
103
-
104
-	// sinon voir si on doit/peut le telecharger
105
-	if ($local === $source || !tester_url_absolue($source)) {
106
-		return $t ? $local : '';
107
-	}
108
-
109
-	if ($mode === 'modif' || !$t) {
110
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
-		// et des eventuelles recuperations concurantes
112
-		include_spip('inc/acces');
113
-		if (!$taille_max) {
114
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
115
-		}
116
-		$localrac_tmp = $localrac . '.tmp';
117
-		$res = recuperer_url(
118
-			$source,
119
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
-		);
121
-
122
-		if (!$res || !$res['length'] && $res['status'] != 304) {
123
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
-			@unlink($localrac_tmp);
125
-		}
126
-		else {
127
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
128
-		}
129
-		if (!$res || !$res['length']) {
130
-			// si $t c'est sans doute juste un not-modified-since
131
-			return $t ? $local : false;
132
-		}
133
-
134
-		// si option valider url, verifions que l'URL finale est acceptable
135
-		if (
136
-			$callback_valider_url
137
-			&& is_callable($callback_valider_url)
138
-			&& !$callback_valider_url($res['url'])
139
-		) {
140
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
141
-			@unlink($localrac_tmp);
142
-			return $t ? $local : false;
143
-		}
144
-
145
-		// on peut renommer le fichier tmp
146
-		@rename($localrac_tmp, $localrac);
147
-
148
-		// si on retrouve l'extension
149
-		if (
150
-			!empty($res['headers'])
151
-			&& ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
152
-			&& ($sanitizer = charger_fonction($extension, 'sanitizer', true))
153
-		) {
154
-			$sanitizer($localrac);
155
-		}
156
-
157
-		// pour une eventuelle indexation
158
-		pipeline(
159
-			'post_edition',
160
-			[
161
-				'args' => [
162
-					'operation' => 'copie_locale',
163
-					'source' => $source,
164
-					'fichier' => $local,
165
-					'http_res' => $res['length'],
166
-					'url' => $res['url'],
167
-				],
168
-				'data' => null
169
-			]
170
-		);
171
-	}
172
-
173
-	return $local;
74
+    // si c'est la protection de soi-meme, retourner le path
75
+    if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
+        $source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
+
78
+        return @file_exists($source) ? $source : false;
79
+    }
80
+
81
+    if (is_null($local)) {
82
+        $local = fichier_copie_locale($source);
83
+    } else {
84
+        if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
+            $local = substr($local, strlen((string) _DIR_RACINE));
86
+        }
87
+    }
88
+
89
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
+    // par exemple un fichier qui ne figure pas dans nos documents ;
91
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
+    if (!$local) {
93
+        return false;
94
+    }
95
+
96
+    $localrac = _DIR_RACINE . $local;
97
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
98
+
99
+    // test d'existence du fichier
100
+    if ($mode === 'test') {
101
+        return $t ? $local : '';
102
+    }
103
+
104
+    // sinon voir si on doit/peut le telecharger
105
+    if ($local === $source || !tester_url_absolue($source)) {
106
+        return $t ? $local : '';
107
+    }
108
+
109
+    if ($mode === 'modif' || !$t) {
110
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
+        // et des eventuelles recuperations concurantes
112
+        include_spip('inc/acces');
113
+        if (!$taille_max) {
114
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
115
+        }
116
+        $localrac_tmp = $localrac . '.tmp';
117
+        $res = recuperer_url(
118
+            $source,
119
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
+        );
121
+
122
+        if (!$res || !$res['length'] && $res['status'] != 304) {
123
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
+            @unlink($localrac_tmp);
125
+        }
126
+        else {
127
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
128
+        }
129
+        if (!$res || !$res['length']) {
130
+            // si $t c'est sans doute juste un not-modified-since
131
+            return $t ? $local : false;
132
+        }
133
+
134
+        // si option valider url, verifions que l'URL finale est acceptable
135
+        if (
136
+            $callback_valider_url
137
+            && is_callable($callback_valider_url)
138
+            && !$callback_valider_url($res['url'])
139
+        ) {
140
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
141
+            @unlink($localrac_tmp);
142
+            return $t ? $local : false;
143
+        }
144
+
145
+        // on peut renommer le fichier tmp
146
+        @rename($localrac_tmp, $localrac);
147
+
148
+        // si on retrouve l'extension
149
+        if (
150
+            !empty($res['headers'])
151
+            && ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
152
+            && ($sanitizer = charger_fonction($extension, 'sanitizer', true))
153
+        ) {
154
+            $sanitizer($localrac);
155
+        }
156
+
157
+        // pour une eventuelle indexation
158
+        pipeline(
159
+            'post_edition',
160
+            [
161
+                'args' => [
162
+                    'operation' => 'copie_locale',
163
+                    'source' => $source,
164
+                    'fichier' => $local,
165
+                    'http_res' => $res['length'],
166
+                    'url' => $res['url'],
167
+                ],
168
+                'data' => null
169
+            ]
170
+        );
171
+    }
172
+
173
+    return $local;
174 174
 }
175 175
 
176 176
 /**
@@ -185,97 +185,97 @@  discard block
 block discarded – undo
185 185
  *   url ou false en cas d'echec
186 186
  */
187 187
 function valider_url_distante($url, $known_hosts = []) {
188
-	if (!function_exists('protocole_verifier')) {
189
-		include_spip('inc/filtres_mini');
190
-	}
191
-
192
-	if (!protocole_verifier($url, ['http', 'https'])) {
193
-		return false;
194
-	}
195
-
196
-	$parsed_url = parse_url($url);
197
-	if (!$parsed_url || empty($parsed_url['host'])) {
198
-		return false;
199
-	}
200
-
201
-	if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
202
-		return false;
203
-	}
204
-
205
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
206
-		return false;
207
-	}
208
-
209
-	if (!is_array($known_hosts)) {
210
-		$known_hosts = [$known_hosts];
211
-	}
212
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
213
-	$known_hosts[] = url_de_base();
214
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
215
-
216
-	$is_known_host = false;
217
-	foreach ($known_hosts as $known_host) {
218
-		$parse_known = parse_url((string) $known_host);
219
-		if (
220
-			$parse_known
221
-			&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
222
-		) {
223
-			$is_known_host = true;
224
-			break;
225
-		}
226
-	}
227
-
228
-	if (!$is_known_host) {
229
-		$host = trim($parsed_url['host'], '.');
230
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
231
-			$ip = gethostbyname($host);
232
-			if ($ip === $host) {
233
-				// Error condition for gethostbyname()
234
-				$ip = false;
235
-			}
236
-			if ($records = dns_get_record($host)) {
237
-				foreach ($records as $record) {
238
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
239
-					// se fasse sur la meme IP
240
-					if ($record['ttl'] < 10) {
241
-						$ip = false;
242
-						break;
243
-					}
244
-				}
245
-			}
246
-			else {
247
-				$ip = false;
248
-			}
249
-		}
250
-		if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
251
-			return false;
252
-		}
253
-	}
254
-
255
-	if (empty($parsed_url['port'])) {
256
-		return $url;
257
-	}
258
-
259
-	$port = $parsed_url['port'];
260
-	if ($port === 80 || $port === 443 || $port === 8080) {
261
-		return $url;
262
-	}
263
-
264
-	if ($is_known_host) {
265
-		foreach ($known_hosts as $known_host) {
266
-			$parse_known = parse_url((string) $known_host);
267
-			if (
268
-				$parse_known
269
-				&& !empty($parse_known['port'])
270
-				&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
271
-				&& $parse_known['port'] == $port
272
-			) {
273
-				return $url;
274
-			}
275
-		}
276
-	}
277
-
278
-	return false;
188
+    if (!function_exists('protocole_verifier')) {
189
+        include_spip('inc/filtres_mini');
190
+    }
191
+
192
+    if (!protocole_verifier($url, ['http', 'https'])) {
193
+        return false;
194
+    }
195
+
196
+    $parsed_url = parse_url($url);
197
+    if (!$parsed_url || empty($parsed_url['host'])) {
198
+        return false;
199
+    }
200
+
201
+    if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
202
+        return false;
203
+    }
204
+
205
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
206
+        return false;
207
+    }
208
+
209
+    if (!is_array($known_hosts)) {
210
+        $known_hosts = [$known_hosts];
211
+    }
212
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
213
+    $known_hosts[] = url_de_base();
214
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
215
+
216
+    $is_known_host = false;
217
+    foreach ($known_hosts as $known_host) {
218
+        $parse_known = parse_url((string) $known_host);
219
+        if (
220
+            $parse_known
221
+            && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
222
+        ) {
223
+            $is_known_host = true;
224
+            break;
225
+        }
226
+    }
227
+
228
+    if (!$is_known_host) {
229
+        $host = trim($parsed_url['host'], '.');
230
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
231
+            $ip = gethostbyname($host);
232
+            if ($ip === $host) {
233
+                // Error condition for gethostbyname()
234
+                $ip = false;
235
+            }
236
+            if ($records = dns_get_record($host)) {
237
+                foreach ($records as $record) {
238
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
239
+                    // se fasse sur la meme IP
240
+                    if ($record['ttl'] < 10) {
241
+                        $ip = false;
242
+                        break;
243
+                    }
244
+                }
245
+            }
246
+            else {
247
+                $ip = false;
248
+            }
249
+        }
250
+        if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
251
+            return false;
252
+        }
253
+    }
254
+
255
+    if (empty($parsed_url['port'])) {
256
+        return $url;
257
+    }
258
+
259
+    $port = $parsed_url['port'];
260
+    if ($port === 80 || $port === 443 || $port === 8080) {
261
+        return $url;
262
+    }
263
+
264
+    if ($is_known_host) {
265
+        foreach ($known_hosts as $known_host) {
266
+            $parse_known = parse_url((string) $known_host);
267
+            if (
268
+                $parse_known
269
+                && !empty($parse_known['port'])
270
+                && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
271
+                && $parse_known['port'] == $port
272
+            ) {
273
+                return $url;
274
+            }
275
+        }
276
+    }
277
+
278
+    return false;
279 279
 }
280 280
 
281 281
 /**
@@ -295,86 +295,86 @@  discard block
 block discarded – undo
295 295
  */
296 296
 function prepare_donnees_post($donnees, $boundary = '') {
297 297
 
298
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
299
-	// pour un appel soap par exemple
300
-	// l'entete est separe des donnees par un double retour a la ligne
301
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
302
-	$chaine = '';
303
-	if (is_string($donnees) && strlen($donnees)) {
304
-		$entete = '';
305
-		// on repasse tous les \r\n et \r en simples \n
306
-		$donnees = str_replace("\r\n", "\n", $donnees);
307
-		$donnees = str_replace("\r", "\n", $donnees);
308
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
309
-		$p = strpos($donnees, "\n\n");
310
-		if ($p !== false) {
311
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
312
-			$donnees = substr($donnees, $p + 2);
313
-		}
314
-		$chaine = str_replace("\n", "\r\n", $donnees);
315
-	} else {
316
-		/* boundary automatique */
317
-		// Si on a plus de 500 octects de donnees, on "boundarise"
318
-		if ($boundary === '') {
319
-			$taille = 0;
320
-			foreach ($donnees as $cle => $valeur) {
321
-				if (is_array($valeur)) {
322
-					foreach ($valeur as $val2) {
323
-						$taille += strlen((string) $val2);
324
-					}
325
-				} else {
326
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
327
-					$taille += strlen((string) $valeur);
328
-				}
329
-			}
330
-			if ($taille > 500) {
331
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
332
-			}
333
-		}
334
-
335
-		if (is_string($boundary) && strlen($boundary)) {
336
-			// fabrique une chaine HTTP pour un POST avec boundary
337
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
338
-			if (is_array($donnees)) {
339
-				foreach ($donnees as $cle => $valeur) {
340
-					if (is_array($valeur)) {
341
-						foreach ($valeur as $val2) {
342
-							$chaine .= "\r\n--$boundary\r\n";
343
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
344
-							$chaine .= "\r\n";
345
-							$chaine .= $val2;
346
-						}
347
-					} else {
348
-						$chaine .= "\r\n--$boundary\r\n";
349
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
350
-						$chaine .= "\r\n";
351
-						$chaine .= $valeur;
352
-					}
353
-				}
354
-				$chaine .= "\r\n--$boundary\r\n";
355
-			}
356
-		} else {
357
-			// fabrique une chaine HTTP simple pour un POST
358
-			$entete = "Content-Type: application/x-www-form-urlencoded\r\n";
359
-			if (is_array($donnees)) {
360
-				$chaine = [];
361
-				foreach ($donnees as $cle => $valeur) {
362
-					if (is_array($valeur)) {
363
-						foreach ($valeur as $val2) {
364
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
365
-						}
366
-					} else {
367
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
368
-					}
369
-				}
370
-				$chaine = implode('&', $chaine);
371
-			} else {
372
-				$chaine = $donnees;
373
-			}
374
-		}
375
-	}
376
-
377
-	return [$entete, $chaine];
298
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
299
+    // pour un appel soap par exemple
300
+    // l'entete est separe des donnees par un double retour a la ligne
301
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
302
+    $chaine = '';
303
+    if (is_string($donnees) && strlen($donnees)) {
304
+        $entete = '';
305
+        // on repasse tous les \r\n et \r en simples \n
306
+        $donnees = str_replace("\r\n", "\n", $donnees);
307
+        $donnees = str_replace("\r", "\n", $donnees);
308
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
309
+        $p = strpos($donnees, "\n\n");
310
+        if ($p !== false) {
311
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
312
+            $donnees = substr($donnees, $p + 2);
313
+        }
314
+        $chaine = str_replace("\n", "\r\n", $donnees);
315
+    } else {
316
+        /* boundary automatique */
317
+        // Si on a plus de 500 octects de donnees, on "boundarise"
318
+        if ($boundary === '') {
319
+            $taille = 0;
320
+            foreach ($donnees as $cle => $valeur) {
321
+                if (is_array($valeur)) {
322
+                    foreach ($valeur as $val2) {
323
+                        $taille += strlen((string) $val2);
324
+                    }
325
+                } else {
326
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
327
+                    $taille += strlen((string) $valeur);
328
+                }
329
+            }
330
+            if ($taille > 500) {
331
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
332
+            }
333
+        }
334
+
335
+        if (is_string($boundary) && strlen($boundary)) {
336
+            // fabrique une chaine HTTP pour un POST avec boundary
337
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
338
+            if (is_array($donnees)) {
339
+                foreach ($donnees as $cle => $valeur) {
340
+                    if (is_array($valeur)) {
341
+                        foreach ($valeur as $val2) {
342
+                            $chaine .= "\r\n--$boundary\r\n";
343
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
344
+                            $chaine .= "\r\n";
345
+                            $chaine .= $val2;
346
+                        }
347
+                    } else {
348
+                        $chaine .= "\r\n--$boundary\r\n";
349
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
350
+                        $chaine .= "\r\n";
351
+                        $chaine .= $valeur;
352
+                    }
353
+                }
354
+                $chaine .= "\r\n--$boundary\r\n";
355
+            }
356
+        } else {
357
+            // fabrique une chaine HTTP simple pour un POST
358
+            $entete = "Content-Type: application/x-www-form-urlencoded\r\n";
359
+            if (is_array($donnees)) {
360
+                $chaine = [];
361
+                foreach ($donnees as $cle => $valeur) {
362
+                    if (is_array($valeur)) {
363
+                        foreach ($valeur as $val2) {
364
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
365
+                        }
366
+                    } else {
367
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
368
+                    }
369
+                }
370
+                $chaine = implode('&', $chaine);
371
+            } else {
372
+                $chaine = $donnees;
373
+            }
374
+        }
375
+    }
376
+
377
+    return [$entete, $chaine];
378 378
 }
379 379
 
380 380
 /**
@@ -385,19 +385,19 @@  discard block
 block discarded – undo
385 385
  */
386 386
 function url_to_ascii($url_idn) {
387 387
 
388
-	if ($parts = parse_url($url_idn)) {
389
-		$host = $parts['host'];
390
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
-			$converter = new ToIdn();
392
-			$host_ascii = $converter->convert($host);
393
-			$url_idn = explode($host, $url_idn, 2);
394
-			$url_idn = implode($host_ascii, $url_idn);
395
-		}
396
-		// et on urlencode les char utf si besoin dans le path
397
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
-	}
399
-
400
-	return $url_idn;
388
+    if ($parts = parse_url($url_idn)) {
389
+        $host = $parts['host'];
390
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
+            $converter = new ToIdn();
392
+            $host_ascii = $converter->convert($host);
393
+            $url_idn = explode($host, $url_idn, 2);
394
+            $url_idn = implode($host_ascii, $url_idn);
395
+        }
396
+        // et on urlencode les char utf si besoin dans le path
397
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
+    }
399
+
400
+    return $url_idn;
401 401
 }
402 402
 
403 403
 /**
@@ -438,209 +438,209 @@  discard block
 block discarded – undo
438 438
  *     string file : nom du fichier si enregistre dans un fichier
439 439
  */
440 440
 function recuperer_url($url, $options = []) {
441
-	// Conserve la mémoire de la méthode fournit éventuellement
442
-	$methode_demandee = $options['methode'] ?? '';
443
-	$default = [
444
-		'transcoder' => false,
445
-		'methode' => 'GET',
446
-		'taille_max' => null,
447
-		'headers' => [],
448
-		'datas' => '',
449
-		'boundary' => '',
450
-		'refuser_gz' => false,
451
-		'if_modified_since' => '',
452
-		'uri_referer' => '',
453
-		'file' => '',
454
-		'follow_location' => 10,
455
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
456
-	];
457
-	$options = array_merge($default, $options);
458
-	// copier directement dans un fichier ?
459
-	$copy = $options['file'];
460
-
461
-	if ($options['methode'] == 'HEAD') {
462
-		$options['taille_max'] = 0;
463
-	}
464
-	if (is_null($options['taille_max'])) {
465
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
466
-	}
467
-
468
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
469
-
470
-	// Ajout des en-têtes spécifiques si besoin
471
-	$formatted_data = '';
472
-	if (!empty($options['headers'])) {
473
-		foreach ($options['headers'] as $champ => $valeur) {
474
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
475
-		}
476
-	}
477
-
478
-	if (!empty($options['datas'])) {
479
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
480
-		$head .= $formatted_data;
481
-		if (stripos($head, 'Content-Length:') === false) {
482
-			$head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
483
-		}
484
-		$formatted_data = $head . "\r\n" . $postdata;
485
-		if (
486
-			strlen((string) $postdata) && !$methode_demandee
487
-		) {
488
-			$options['methode'] = 'POST';
489
-		}
490
-	} elseif ($formatted_data) {
491
-		$formatted_data .= "\r\n";
492
-	}
493
-
494
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
495
-	$url = preg_replace(',^feed://,i', 'http://', $url);
496
-	if (!tester_url_absolue($url)) {
497
-		$url = 'http://' . $url;
498
-	} elseif (str_starts_with($url, '//')) {
499
-		$url = 'http:' . $url;
500
-	}
501
-
502
-	$url = url_to_ascii($url);
503
-
504
-	$result = [
505
-		'status' => 0,
506
-		'headers' => '',
507
-		'page' => '',
508
-		'length' => 0,
509
-		'last_modified' => '',
510
-		'location' => '',
511
-		'url' => $url
512
-	];
513
-
514
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
515
-	$refuser_gz = ($options['refuser_gz'] || $copy);
516
-
517
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
518
-	[$handle, $fopen] = init_http(
519
-		$options['methode'],
520
-		$url,
521
-		$refuser_gz,
522
-		$options['uri_referer'],
523
-		$formatted_data,
524
-		$options['version_http'],
525
-		$options['if_modified_since']
526
-	);
527
-	if (!$handle) {
528
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
529
-
530
-		return false;
531
-	}
532
-
533
-	// Sauf en fopen, envoyer le flux d'entree
534
-	// et recuperer les en-tetes de reponses
535
-	if (!$fopen) {
536
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
537
-		if (!$res) {
538
-			fclose($handle);
539
-			$t = @parse_url($url);
540
-			$host = $t['host'];
541
-			// Chinoisierie inexplicable pour contrer
542
-			// les actions liberticides de l'empire du milieu
543
-			if (
544
-				!need_proxy($host)
545
-				&& ($res = @file_get_contents($url))
546
-			) {
547
-				$result['length'] = strlen($res);
548
-				if ($copy) {
549
-					ecrire_fichier($copy, $res);
550
-					$result['file'] = $copy;
551
-				} else {
552
-					$result['page'] = $res;
553
-				}
554
-				$res = [
555
-					'status' => 200,
556
-				];
557
-			} else {
558
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
559
-				return false;
560
-			}
561
-		} elseif ($res['location'] && $options['follow_location']) {
562
-			$options['follow_location']--;
563
-			fclose($handle);
564
-			include_spip('inc/filtres');
565
-			$url = suivre_lien($url, $res['location']);
566
-
567
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
568
-			if (
569
-				$options['methode'] !== 'GET'
570
-				&& (empty($res['status']) || !in_array($res['status'], [307, 308]))
571
-			) {
572
-				$options['methode'] = 'GET';
573
-				$options['datas'] = '';
574
-			}
575
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
576
-
577
-			return recuperer_url($url, $options);
578
-		} elseif ($res['status'] !== 200) {
579
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
580
-		}
581
-		$result['status'] = $res['status'];
582
-		if (isset($res['headers'])) {
583
-			$result['headers'] = $res['headers'];
584
-		}
585
-		if (isset($res['last_modified'])) {
586
-			$result['last_modified'] = $res['last_modified'];
587
-		}
588
-		if (isset($res['location'])) {
589
-			$result['location'] = $res['location'];
590
-		}
591
-	}
592
-
593
-	// on ne veut que les entetes
594
-	if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
595
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
596
-		return $result;
597
-	}
598
-
599
-
600
-	// s'il faut deballer, le faire via un fichier temporaire
601
-	// sinon la memoire explose pour les gros flux
602
-
603
-	$gz = false;
604
-	if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
605
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
606
-	}
607
-
608
-	// si on a pas deja recuperer le contenu par une methode detournee
609
-	if (!$result['length']) {
610
-		$res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
611
-		fclose($handle);
612
-		if ($copy) {
613
-			$result['length'] = $res;
614
-			$result['file'] = $copy;
615
-		} elseif ($res) {
616
-			$result['page'] = &$res;
617
-			$result['length'] = strlen($result['page']);
618
-		}
619
-		if (!$result['status']) {
620
-			$result['status'] = 200; // on a reussi, donc !
621
-		}
622
-	}
623
-	if (!$result['page']) {
624
-		return $result;
625
-	}
626
-
627
-	// Decompresser au besoin
628
-	if ($gz) {
629
-		$result['page'] = implode('', gzfile($gz));
630
-		supprimer_fichier($gz);
631
-	}
632
-
633
-	// Faut-il l'importer dans notre charset local ?
634
-	if ($options['transcoder']) {
635
-		include_spip('inc/charsets');
636
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
637
-	}
638
-
639
-	$trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
640
-	$trace['page'] = '...';
641
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
642
-
643
-	return $result;
441
+    // Conserve la mémoire de la méthode fournit éventuellement
442
+    $methode_demandee = $options['methode'] ?? '';
443
+    $default = [
444
+        'transcoder' => false,
445
+        'methode' => 'GET',
446
+        'taille_max' => null,
447
+        'headers' => [],
448
+        'datas' => '',
449
+        'boundary' => '',
450
+        'refuser_gz' => false,
451
+        'if_modified_since' => '',
452
+        'uri_referer' => '',
453
+        'file' => '',
454
+        'follow_location' => 10,
455
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
456
+    ];
457
+    $options = array_merge($default, $options);
458
+    // copier directement dans un fichier ?
459
+    $copy = $options['file'];
460
+
461
+    if ($options['methode'] == 'HEAD') {
462
+        $options['taille_max'] = 0;
463
+    }
464
+    if (is_null($options['taille_max'])) {
465
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
466
+    }
467
+
468
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
469
+
470
+    // Ajout des en-têtes spécifiques si besoin
471
+    $formatted_data = '';
472
+    if (!empty($options['headers'])) {
473
+        foreach ($options['headers'] as $champ => $valeur) {
474
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
475
+        }
476
+    }
477
+
478
+    if (!empty($options['datas'])) {
479
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
480
+        $head .= $formatted_data;
481
+        if (stripos($head, 'Content-Length:') === false) {
482
+            $head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
483
+        }
484
+        $formatted_data = $head . "\r\n" . $postdata;
485
+        if (
486
+            strlen((string) $postdata) && !$methode_demandee
487
+        ) {
488
+            $options['methode'] = 'POST';
489
+        }
490
+    } elseif ($formatted_data) {
491
+        $formatted_data .= "\r\n";
492
+    }
493
+
494
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
495
+    $url = preg_replace(',^feed://,i', 'http://', $url);
496
+    if (!tester_url_absolue($url)) {
497
+        $url = 'http://' . $url;
498
+    } elseif (str_starts_with($url, '//')) {
499
+        $url = 'http:' . $url;
500
+    }
501
+
502
+    $url = url_to_ascii($url);
503
+
504
+    $result = [
505
+        'status' => 0,
506
+        'headers' => '',
507
+        'page' => '',
508
+        'length' => 0,
509
+        'last_modified' => '',
510
+        'location' => '',
511
+        'url' => $url
512
+    ];
513
+
514
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
515
+    $refuser_gz = ($options['refuser_gz'] || $copy);
516
+
517
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
518
+    [$handle, $fopen] = init_http(
519
+        $options['methode'],
520
+        $url,
521
+        $refuser_gz,
522
+        $options['uri_referer'],
523
+        $formatted_data,
524
+        $options['version_http'],
525
+        $options['if_modified_since']
526
+    );
527
+    if (!$handle) {
528
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
529
+
530
+        return false;
531
+    }
532
+
533
+    // Sauf en fopen, envoyer le flux d'entree
534
+    // et recuperer les en-tetes de reponses
535
+    if (!$fopen) {
536
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
537
+        if (!$res) {
538
+            fclose($handle);
539
+            $t = @parse_url($url);
540
+            $host = $t['host'];
541
+            // Chinoisierie inexplicable pour contrer
542
+            // les actions liberticides de l'empire du milieu
543
+            if (
544
+                !need_proxy($host)
545
+                && ($res = @file_get_contents($url))
546
+            ) {
547
+                $result['length'] = strlen($res);
548
+                if ($copy) {
549
+                    ecrire_fichier($copy, $res);
550
+                    $result['file'] = $copy;
551
+                } else {
552
+                    $result['page'] = $res;
553
+                }
554
+                $res = [
555
+                    'status' => 200,
556
+                ];
557
+            } else {
558
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
559
+                return false;
560
+            }
561
+        } elseif ($res['location'] && $options['follow_location']) {
562
+            $options['follow_location']--;
563
+            fclose($handle);
564
+            include_spip('inc/filtres');
565
+            $url = suivre_lien($url, $res['location']);
566
+
567
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
568
+            if (
569
+                $options['methode'] !== 'GET'
570
+                && (empty($res['status']) || !in_array($res['status'], [307, 308]))
571
+            ) {
572
+                $options['methode'] = 'GET';
573
+                $options['datas'] = '';
574
+            }
575
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
576
+
577
+            return recuperer_url($url, $options);
578
+        } elseif ($res['status'] !== 200) {
579
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
580
+        }
581
+        $result['status'] = $res['status'];
582
+        if (isset($res['headers'])) {
583
+            $result['headers'] = $res['headers'];
584
+        }
585
+        if (isset($res['last_modified'])) {
586
+            $result['last_modified'] = $res['last_modified'];
587
+        }
588
+        if (isset($res['location'])) {
589
+            $result['location'] = $res['location'];
590
+        }
591
+    }
592
+
593
+    // on ne veut que les entetes
594
+    if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
595
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
596
+        return $result;
597
+    }
598
+
599
+
600
+    // s'il faut deballer, le faire via un fichier temporaire
601
+    // sinon la memoire explose pour les gros flux
602
+
603
+    $gz = false;
604
+    if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
605
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
606
+    }
607
+
608
+    // si on a pas deja recuperer le contenu par une methode detournee
609
+    if (!$result['length']) {
610
+        $res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
611
+        fclose($handle);
612
+        if ($copy) {
613
+            $result['length'] = $res;
614
+            $result['file'] = $copy;
615
+        } elseif ($res) {
616
+            $result['page'] = &$res;
617
+            $result['length'] = strlen($result['page']);
618
+        }
619
+        if (!$result['status']) {
620
+            $result['status'] = 200; // on a reussi, donc !
621
+        }
622
+    }
623
+    if (!$result['page']) {
624
+        return $result;
625
+    }
626
+
627
+    // Decompresser au besoin
628
+    if ($gz) {
629
+        $result['page'] = implode('', gzfile($gz));
630
+        supprimer_fichier($gz);
631
+    }
632
+
633
+    // Faut-il l'importer dans notre charset local ?
634
+    if ($options['transcoder']) {
635
+        include_spip('inc/charsets');
636
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
637
+    }
638
+
639
+    $trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
640
+    $trace['page'] = '...';
641
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
642
+
643
+    return $result;
644 644
 }
645 645
 
646 646
 /**
@@ -656,73 +656,73 @@  discard block
 block discarded – undo
656 656
  * @return array|bool|mixed
657 657
  */
658 658
 function recuperer_url_cache($url, $options = []) {
659
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
660
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
661
-	}
662
-	$default = [
663
-		'transcoder' => false,
664
-		'methode' => 'GET',
665
-		'taille_max' => null,
666
-		'datas' => '',
667
-		'boundary' => '',
668
-		'refuser_gz' => false,
669
-		'if_modified_since' => '',
670
-		'uri_referer' => '',
671
-		'file' => '',
672
-		'follow_location' => 10,
673
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
674
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
675
-	];
676
-	$options = array_merge($default, $options);
677
-
678
-	// cas ou il n'est pas possible de cacher
679
-	if (!empty($options['data']) || $options['methode'] == 'POST') {
680
-		return recuperer_url($url, $options);
681
-	}
682
-
683
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
684
-	static $errors = [];
685
-	if (isset($errors[$url])) {
686
-		return $errors[$url];
687
-	}
688
-
689
-	$sig = $options;
690
-	unset($sig['if_modified_since']);
691
-	unset($sig['delai_cache']);
692
-	$sig['url'] = $url;
693
-
694
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
695
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
696
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
697
-	$cache = "$sub$cache";
698
-
699
-	$res = false;
700
-	$is_cached = file_exists($cache);
701
-	if (
702
-		$is_cached
703
-		&& filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
704
-	) {
705
-		lire_fichier($cache, $res);
706
-		if ($res = unserialize($res)) {
707
-			// mettre le last_modified et le status=304 ?
708
-		}
709
-	}
710
-	if (!$res) {
711
-		$res = recuperer_url($url, $options);
712
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
713
-		if (!$res) {
714
-			if ($is_cached) {
715
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
716
-				lire_fichier($cache, $res);
717
-				$res = unserialize($res);
718
-			}
719
-
720
-			return $errors[$url] = $res;
721
-		}
722
-		ecrire_fichier($cache, serialize($res));
723
-	}
724
-
725
-	return $res;
659
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
660
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
661
+    }
662
+    $default = [
663
+        'transcoder' => false,
664
+        'methode' => 'GET',
665
+        'taille_max' => null,
666
+        'datas' => '',
667
+        'boundary' => '',
668
+        'refuser_gz' => false,
669
+        'if_modified_since' => '',
670
+        'uri_referer' => '',
671
+        'file' => '',
672
+        'follow_location' => 10,
673
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
674
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
675
+    ];
676
+    $options = array_merge($default, $options);
677
+
678
+    // cas ou il n'est pas possible de cacher
679
+    if (!empty($options['data']) || $options['methode'] == 'POST') {
680
+        return recuperer_url($url, $options);
681
+    }
682
+
683
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
684
+    static $errors = [];
685
+    if (isset($errors[$url])) {
686
+        return $errors[$url];
687
+    }
688
+
689
+    $sig = $options;
690
+    unset($sig['if_modified_since']);
691
+    unset($sig['delai_cache']);
692
+    $sig['url'] = $url;
693
+
694
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
695
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
696
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
697
+    $cache = "$sub$cache";
698
+
699
+    $res = false;
700
+    $is_cached = file_exists($cache);
701
+    if (
702
+        $is_cached
703
+        && filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
704
+    ) {
705
+        lire_fichier($cache, $res);
706
+        if ($res = unserialize($res)) {
707
+            // mettre le last_modified et le status=304 ?
708
+        }
709
+    }
710
+    if (!$res) {
711
+        $res = recuperer_url($url, $options);
712
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
713
+        if (!$res) {
714
+            if ($is_cached) {
715
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
716
+                lire_fichier($cache, $res);
717
+                $res = unserialize($res);
718
+            }
719
+
720
+            return $errors[$url] = $res;
721
+        }
722
+        ecrire_fichier($cache, serialize($res));
723
+    }
724
+
725
+    return $res;
726 726
 }
727 727
 
728 728
 /**
@@ -740,42 +740,42 @@  discard block
 block discarded – undo
740 740
  *   string contenu de la resource
741 741
  */
742 742
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
743
-	$tmpfile = null;
744
-	$taille = 0;
745
-	$result = '';
746
-	$fp = false;
747
-	if ($fichier) {
748
-		include_spip('inc/acces');
749
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
750
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
751
-		if (!$fp && file_exists($fichier)) {
752
-			return filesize($fichier);
753
-		}
754
-		if (!$fp) {
755
-			return false;
756
-		}
757
-		$result = 0; // on renvoie la taille du fichier
758
-	}
759
-	while (!feof($handle) && $taille < $taille_max) {
760
-		$res = fread($handle, 16384);
761
-		$taille += strlen($res);
762
-		if ($fp) {
763
-			fwrite($fp, $res);
764
-			$result = $taille;
765
-		} else {
766
-			$result .= $res;
767
-		}
768
-	}
769
-	if ($fp) {
770
-		spip_fclose_unlock($fp);
771
-		spip_unlink($fichier);
772
-		@rename($tmpfile, $fichier);
773
-		if (!file_exists($fichier)) {
774
-			return false;
775
-		}
776
-	}
777
-
778
-	return $result;
743
+    $tmpfile = null;
744
+    $taille = 0;
745
+    $result = '';
746
+    $fp = false;
747
+    if ($fichier) {
748
+        include_spip('inc/acces');
749
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
750
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
751
+        if (!$fp && file_exists($fichier)) {
752
+            return filesize($fichier);
753
+        }
754
+        if (!$fp) {
755
+            return false;
756
+        }
757
+        $result = 0; // on renvoie la taille du fichier
758
+    }
759
+    while (!feof($handle) && $taille < $taille_max) {
760
+        $res = fread($handle, 16384);
761
+        $taille += strlen($res);
762
+        if ($fp) {
763
+            fwrite($fp, $res);
764
+            $result = $taille;
765
+        } else {
766
+            $result .= $res;
767
+        }
768
+    }
769
+    if ($fp) {
770
+        spip_fclose_unlock($fp);
771
+        spip_unlink($fichier);
772
+        @rename($tmpfile, $fichier);
773
+        if (!file_exists($fichier)) {
774
+            return false;
775
+        }
776
+    }
777
+
778
+    return $result;
779 779
 }
780 780
 
781 781
 /**
@@ -797,35 +797,35 @@  discard block
 block discarded – undo
797 797
  *   string location
798 798
  */
799 799
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
800
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
801
-
802
-	$s = @trim(fgets($handle, 16384));
803
-	if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
804
-		return false;
805
-	}
806
-	$result['status'] = (int) $r[1];
807
-	while ($s = trim(fgets($handle, 16384))) {
808
-		$result['headers'][] = $s . "\n";
809
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
810
-		[, $d, $v] = $r;
811
-		if (strtolower(trim($d)) == 'location' && $result['status'] >= 300 && $result['status'] < 400) {
812
-			$result['location'] = $v;
813
-		} elseif ($d == 'Last-Modified') {
814
-			$result['last_modified'] = strtotime($v);
815
-		}
816
-	}
817
-	if (
818
-		$if_modified_since
819
-		&& $result['last_modified']
820
-		&& $if_modified_since > $result['last_modified']
821
-		&& $result['status'] == 200
822
-	) {
823
-		$result['status'] = 304;
824
-	}
825
-
826
-	$result['headers'] = implode('', $result['headers']);
827
-
828
-	return $result;
800
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
801
+
802
+    $s = @trim(fgets($handle, 16384));
803
+    if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
804
+        return false;
805
+    }
806
+    $result['status'] = (int) $r[1];
807
+    while ($s = trim(fgets($handle, 16384))) {
808
+        $result['headers'][] = $s . "\n";
809
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
810
+        [, $d, $v] = $r;
811
+        if (strtolower(trim($d)) == 'location' && $result['status'] >= 300 && $result['status'] < 400) {
812
+            $result['location'] = $v;
813
+        } elseif ($d == 'Last-Modified') {
814
+            $result['last_modified'] = strtotime($v);
815
+        }
816
+    }
817
+    if (
818
+        $if_modified_since
819
+        && $result['last_modified']
820
+        && $if_modified_since > $result['last_modified']
821
+        && $result['status'] == 200
822
+    ) {
823
+        $result['status'] = 304;
824
+    }
825
+
826
+    $result['headers'] = implode('', $result['headers']);
827
+
828
+    return $result;
829 829
 }
830 830
 
831 831
 /**
@@ -847,22 +847,22 @@  discard block
 block discarded – undo
847 847
  *     Nom du fichier pour copie locale
848 848
  **/
849 849
 function nom_fichier_copie_locale($source, $extension) {
850
-	include_spip('inc/documents');
850
+    include_spip('inc/documents');
851 851
 
852
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
853
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
852
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
853
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
854 854
 
855
-	// on se place tout le temps comme si on etait a la racine
856
-	if (_DIR_RACINE) {
857
-		$d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
858
-	}
855
+    // on se place tout le temps comme si on etait a la racine
856
+    if (_DIR_RACINE) {
857
+        $d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
858
+    }
859 859
 
860
-	$m = md5($source);
860
+    $m = md5($source);
861 861
 
862
-	return $d
863
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
864
-	. substr($m, 0, 4)
865
-	. ".$extension";
862
+    return $d
863
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
864
+    . substr($m, 0, 4)
865
+    . ".$extension";
866 866
 }
867 867
 
868 868
 /**
@@ -881,72 +881,72 @@  discard block
 block discarded – undo
881 881
  *      - null: Copie locale impossible
882 882
  **/
883 883
 function fichier_copie_locale($source) {
884
-	// Si c'est deja local pas de souci
885
-	if (!tester_url_absolue($source)) {
886
-		if (_DIR_RACINE) {
887
-			$source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
888
-		}
889
-
890
-		return $source;
891
-	}
892
-
893
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
894
-	// a deja ete copie en local avec cette extension
895
-	// dans ce cas elle est fiable, pas la peine de requeter en base
896
-	$path_parts = pathinfo($source);
897
-	if (!isset($path_parts['extension'])) {
898
-		$path_parts['extension'] = '';
899
-	}
900
-	$ext = $path_parts ? $path_parts['extension'] : '';
901
-	if (
902
-		$ext
903
-		&& preg_match(',^\w+$,', $ext)
904
-		&& ($f = nom_fichier_copie_locale($source, $ext))
905
-		&& file_exists(_DIR_RACINE . $f)
906
-	) {
907
-		return $f;
908
-	}
909
-
910
-
911
-	// Si c'est deja dans la table des documents,
912
-	// ramener le nom de sa copie potentielle
913
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
914
-
915
-	if ($ext) {
916
-		return nom_fichier_copie_locale($source, $ext);
917
-	}
918
-
919
-	// voir si l'extension indiquee dans le nom du fichier est ok
920
-	// et si il n'aurait pas deja ete rapatrie
921
-
922
-	$ext = $path_parts ? $path_parts['extension'] : '';
923
-
924
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
925
-		$f = nom_fichier_copie_locale($source, $ext);
926
-		if (file_exists(_DIR_RACINE . $f)) {
927
-			return $f;
928
-		}
929
-	}
930
-
931
-	// Ping  pour voir si son extension est connue et autorisee
932
-	// avec mise en cache du resultat du ping
933
-
934
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
935
-	if (
936
-		!@file_exists($cache)
937
-		|| !($path_parts = @unserialize(spip_file_get_contents($cache)))
938
-		|| _request('var_mode') === 'recalcul'
939
-	) {
940
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
941
-		ecrire_fichier($cache, serialize($path_parts));
942
-	}
943
-	$ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
944
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
945
-		return nom_fichier_copie_locale($source, $ext);
946
-	}
947
-
948
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
949
-	return null;
884
+    // Si c'est deja local pas de souci
885
+    if (!tester_url_absolue($source)) {
886
+        if (_DIR_RACINE) {
887
+            $source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
888
+        }
889
+
890
+        return $source;
891
+    }
892
+
893
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
894
+    // a deja ete copie en local avec cette extension
895
+    // dans ce cas elle est fiable, pas la peine de requeter en base
896
+    $path_parts = pathinfo($source);
897
+    if (!isset($path_parts['extension'])) {
898
+        $path_parts['extension'] = '';
899
+    }
900
+    $ext = $path_parts ? $path_parts['extension'] : '';
901
+    if (
902
+        $ext
903
+        && preg_match(',^\w+$,', $ext)
904
+        && ($f = nom_fichier_copie_locale($source, $ext))
905
+        && file_exists(_DIR_RACINE . $f)
906
+    ) {
907
+        return $f;
908
+    }
909
+
910
+
911
+    // Si c'est deja dans la table des documents,
912
+    // ramener le nom de sa copie potentielle
913
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
914
+
915
+    if ($ext) {
916
+        return nom_fichier_copie_locale($source, $ext);
917
+    }
918
+
919
+    // voir si l'extension indiquee dans le nom du fichier est ok
920
+    // et si il n'aurait pas deja ete rapatrie
921
+
922
+    $ext = $path_parts ? $path_parts['extension'] : '';
923
+
924
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
925
+        $f = nom_fichier_copie_locale($source, $ext);
926
+        if (file_exists(_DIR_RACINE . $f)) {
927
+            return $f;
928
+        }
929
+    }
930
+
931
+    // Ping  pour voir si son extension est connue et autorisee
932
+    // avec mise en cache du resultat du ping
933
+
934
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
935
+    if (
936
+        !@file_exists($cache)
937
+        || !($path_parts = @unserialize(spip_file_get_contents($cache)))
938
+        || _request('var_mode') === 'recalcul'
939
+    ) {
940
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
941
+        ecrire_fichier($cache, serialize($path_parts));
942
+    }
943
+    $ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
944
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
945
+        return nom_fichier_copie_locale($source, $ext);
946
+    }
947
+
948
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
949
+    return null;
950 950
 }
951 951
 
952 952
 
@@ -975,112 +975,112 @@  discard block
 block discarded – undo
975 975
  **/
976 976
 function recuperer_infos_distantes($source, $options = []) {
977 977
 
978
-	// pas la peine de perdre son temps
979
-	if (!tester_url_absolue($source)) {
980
-		return false;
981
-	}
982
-
983
-	$taille_max = $options['taille_max'] ?? 0;
984
-	$charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
985
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
986
-
987
-	# charger les alias des types mime
988
-	include_spip('base/typedoc');
989
-
990
-	$a = [];
991
-	$mime_type = '';
992
-	// On va directement charger le debut des images et des fichiers html,
993
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
994
-	// ca echoue l'utilisateur devra les entrer...
995
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
996
-	if (
997
-		$callback_valider_url
998
-		&& is_callable($callback_valider_url)
999
-		&& !$callback_valider_url($reponse['url'])
1000
-	) {
1001
-		return false;
1002
-	}
1003
-	$headers = $reponse['headers'] ?? '';
1004
-	$a['body'] = $reponse['page'] ?? '';
1005
-	if ($headers) {
1006
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1007
-			return false;
1008
-		}
1009
-
1010
-		$a['extension'] = $extension;
1011
-
1012
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1013
-			$a['taille'] = (int) $regs[1];
1014
-		}
1015
-	}
1016
-
1017
-	// Echec avec HEAD, on tente avec GET
1018
-	if (!$a && !$taille_max) {
1019
-		spip_log("tenter GET $source", 'distant');
1020
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1021
-		$a = recuperer_infos_distantes($source, $options);
1022
-	}
1023
-
1024
-	// si on a rien trouve pas la peine d'insister
1025
-	if (!$a) {
1026
-		return false;
1027
-	}
1028
-
1029
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1030
-	// recharger le document en GET et recuperer des donnees supplementaires...
1031
-	include_spip('inc/filtres_images_lib_mini');
1032
-	if (
1033
-		str_starts_with($mime_type, 'image/')
1034
-		&& ($extension = _image_trouver_extension_depuis_mime($mime_type))
1035
-	) {
1036
-		if (
1037
-			$taille_max == 0
1038
-			&& (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1039
-			&& in_array($extension, formats_image_acceptables())
1040
-			&& $charger_si_petite_image
1041
-		) {
1042
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1043
-			$a = recuperer_infos_distantes($source, $options);
1044
-		} else {
1045
-			if ($a['body']) {
1046
-				$a['extension'] = $extension;
1047
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1048
-				ecrire_fichier($a['fichier'], $a['body']);
1049
-				$size_image = @spip_getimagesize($a['fichier']);
1050
-				$a['largeur'] = (int) $size_image[0];
1051
-				$a['hauteur'] = (int) $size_image[1];
1052
-				$a['type_image'] = true;
1053
-			}
1054
-		}
1055
-	}
1056
-
1057
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1058
-	// ce sera mieux que 0x0
1059
-	// Flash is dead!
1060
-	if (
1061
-		$a
1062
-		&& isset($a['extension'])
1063
-		&& $a['extension'] == 'swf'
1064
-		&& empty($a['largeur'])
1065
-	) {
1066
-		$a['largeur'] = 425;
1067
-		$a['hauteur'] = 350;
1068
-	}
1069
-
1070
-	if ($mime_type == 'text/html') {
1071
-		include_spip('inc/filtres');
1072
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1073
-		$page = $page['page'] ?? '';
1074
-		if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1075
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1076
-		}
1077
-		if (!isset($a['taille']) || !$a['taille']) {
1078
-			$a['taille'] = strlen((string) $page); # a peu pres
1079
-		}
1080
-	}
1081
-	$a['mime_type'] = $mime_type;
1082
-
1083
-	return $a;
978
+    // pas la peine de perdre son temps
979
+    if (!tester_url_absolue($source)) {
980
+        return false;
981
+    }
982
+
983
+    $taille_max = $options['taille_max'] ?? 0;
984
+    $charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
985
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
986
+
987
+    # charger les alias des types mime
988
+    include_spip('base/typedoc');
989
+
990
+    $a = [];
991
+    $mime_type = '';
992
+    // On va directement charger le debut des images et des fichiers html,
993
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
994
+    // ca echoue l'utilisateur devra les entrer...
995
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
996
+    if (
997
+        $callback_valider_url
998
+        && is_callable($callback_valider_url)
999
+        && !$callback_valider_url($reponse['url'])
1000
+    ) {
1001
+        return false;
1002
+    }
1003
+    $headers = $reponse['headers'] ?? '';
1004
+    $a['body'] = $reponse['page'] ?? '';
1005
+    if ($headers) {
1006
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1007
+            return false;
1008
+        }
1009
+
1010
+        $a['extension'] = $extension;
1011
+
1012
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1013
+            $a['taille'] = (int) $regs[1];
1014
+        }
1015
+    }
1016
+
1017
+    // Echec avec HEAD, on tente avec GET
1018
+    if (!$a && !$taille_max) {
1019
+        spip_log("tenter GET $source", 'distant');
1020
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1021
+        $a = recuperer_infos_distantes($source, $options);
1022
+    }
1023
+
1024
+    // si on a rien trouve pas la peine d'insister
1025
+    if (!$a) {
1026
+        return false;
1027
+    }
1028
+
1029
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1030
+    // recharger le document en GET et recuperer des donnees supplementaires...
1031
+    include_spip('inc/filtres_images_lib_mini');
1032
+    if (
1033
+        str_starts_with($mime_type, 'image/')
1034
+        && ($extension = _image_trouver_extension_depuis_mime($mime_type))
1035
+    ) {
1036
+        if (
1037
+            $taille_max == 0
1038
+            && (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1039
+            && in_array($extension, formats_image_acceptables())
1040
+            && $charger_si_petite_image
1041
+        ) {
1042
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1043
+            $a = recuperer_infos_distantes($source, $options);
1044
+        } else {
1045
+            if ($a['body']) {
1046
+                $a['extension'] = $extension;
1047
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1048
+                ecrire_fichier($a['fichier'], $a['body']);
1049
+                $size_image = @spip_getimagesize($a['fichier']);
1050
+                $a['largeur'] = (int) $size_image[0];
1051
+                $a['hauteur'] = (int) $size_image[1];
1052
+                $a['type_image'] = true;
1053
+            }
1054
+        }
1055
+    }
1056
+
1057
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1058
+    // ce sera mieux que 0x0
1059
+    // Flash is dead!
1060
+    if (
1061
+        $a
1062
+        && isset($a['extension'])
1063
+        && $a['extension'] == 'swf'
1064
+        && empty($a['largeur'])
1065
+    ) {
1066
+        $a['largeur'] = 425;
1067
+        $a['hauteur'] = 350;
1068
+    }
1069
+
1070
+    if ($mime_type == 'text/html') {
1071
+        include_spip('inc/filtres');
1072
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1073
+        $page = $page['page'] ?? '';
1074
+        if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1075
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1076
+        }
1077
+        if (!isset($a['taille']) || !$a['taille']) {
1078
+            $a['taille'] = strlen((string) $page); # a peu pres
1079
+        }
1080
+    }
1081
+    $a['mime_type'] = $mime_type;
1082
+
1083
+    return $a;
1084 1084
 }
1085 1085
 
1086 1086
 /**
@@ -1089,63 +1089,63 @@  discard block
 block discarded – undo
1089 1089
  * @return false|mixed
1090 1090
  */
1091 1091
 function distant_trouver_extension_selon_headers($source, $headers) {
1092
-	$mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1093
-
1094
-	// Appliquer les alias
1095
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1096
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1097
-	}
1098
-
1099
-	// pour corriger_extension()
1100
-	include_spip('inc/documents');
1101
-
1102
-	// Si on a un mime-type insignifiant
1103
-	// text/plain,application/octet-stream ou vide
1104
-	// c'est peut-etre que le serveur ne sait pas
1105
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1106
-	// ou le Content-Disposition: attachment; filename=...
1107
-	$t = null;
1108
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1109
-		if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1110
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1111
-		}
1112
-		if (
1113
-			!$t
1114
-			&& preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1115
-			&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1116
-		) {
1117
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1118
-		}
1119
-	}
1120
-
1121
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1122
-	if (!$t) {
1123
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1124
-	}
1125
-
1126
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1127
-	// On essaie de nouveau avec l'extension
1128
-	if (
1129
-		!$t
1130
-		&& $mime_type != 'text/plain'
1131
-		&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1132
-	) {
1133
-		# eviter xxx.3 => 3gp (> SPIP 3)
1134
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1135
-	}
1136
-
1137
-	if ($t) {
1138
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1139
-		return $t['extension'];
1140
-	} else {
1141
-		# par defaut on retombe sur '.bin' si c'est autorise
1142
-		spip_log("mime-type $mime_type inconnu", 'distant');
1143
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1144
-		if (!$t) {
1145
-			return false;
1146
-		}
1147
-		return $t['extension'];
1148
-	}
1092
+    $mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1093
+
1094
+    // Appliquer les alias
1095
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1096
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1097
+    }
1098
+
1099
+    // pour corriger_extension()
1100
+    include_spip('inc/documents');
1101
+
1102
+    // Si on a un mime-type insignifiant
1103
+    // text/plain,application/octet-stream ou vide
1104
+    // c'est peut-etre que le serveur ne sait pas
1105
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1106
+    // ou le Content-Disposition: attachment; filename=...
1107
+    $t = null;
1108
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1109
+        if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1110
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1111
+        }
1112
+        if (
1113
+            !$t
1114
+            && preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1115
+            && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1116
+        ) {
1117
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1118
+        }
1119
+    }
1120
+
1121
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1122
+    if (!$t) {
1123
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1124
+    }
1125
+
1126
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1127
+    // On essaie de nouveau avec l'extension
1128
+    if (
1129
+        !$t
1130
+        && $mime_type != 'text/plain'
1131
+        && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1132
+    ) {
1133
+        # eviter xxx.3 => 3gp (> SPIP 3)
1134
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1135
+    }
1136
+
1137
+    if ($t) {
1138
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1139
+        return $t['extension'];
1140
+    } else {
1141
+        # par defaut on retombe sur '.bin' si c'est autorise
1142
+        spip_log("mime-type $mime_type inconnu", 'distant');
1143
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1144
+        if (!$t) {
1145
+            return false;
1146
+        }
1147
+        return $t['extension'];
1148
+    }
1149 1149
 }
1150 1150
 
1151 1151
 /**
@@ -1161,45 +1161,45 @@  discard block
 block discarded – undo
1161 1161
  */
1162 1162
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1163 1163
 
1164
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1165
-
1166
-	// rien a faire si pas de proxy :)
1167
-	if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1168
-		return '';
1169
-	}
1170
-
1171
-	if (is_null($http_noproxy)) {
1172
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1173
-	}
1174
-	// si pas d'exception, on retourne le proxy
1175
-	if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1176
-		return $http_proxy;
1177
-	}
1178
-
1179
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1180
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1181
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1182
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1183
-	$http_noproxy = " $http_noproxy ";
1184
-	$domain = $host;
1185
-	// si le domaine exact www.example.org est dans les exceptions
1186
-	if (str_contains($http_noproxy, (string) " $domain ")) {
1187
-		return '';
1188
-	}
1189
-
1190
-	while (str_contains($domain, '.')) {
1191
-		$domain = explode('.', $domain);
1192
-		array_shift($domain);
1193
-		$domain = implode('.', $domain);
1194
-
1195
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1196
-		if (str_contains($http_noproxy, (string) " .$domain ")) {
1197
-			return '';
1198
-		}
1199
-	}
1200
-
1201
-	// ok c'est pas une exception
1202
-	return $http_proxy;
1164
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1165
+
1166
+    // rien a faire si pas de proxy :)
1167
+    if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1168
+        return '';
1169
+    }
1170
+
1171
+    if (is_null($http_noproxy)) {
1172
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1173
+    }
1174
+    // si pas d'exception, on retourne le proxy
1175
+    if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1176
+        return $http_proxy;
1177
+    }
1178
+
1179
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1180
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1181
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1182
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1183
+    $http_noproxy = " $http_noproxy ";
1184
+    $domain = $host;
1185
+    // si le domaine exact www.example.org est dans les exceptions
1186
+    if (str_contains($http_noproxy, (string) " $domain ")) {
1187
+        return '';
1188
+    }
1189
+
1190
+    while (str_contains($domain, '.')) {
1191
+        $domain = explode('.', $domain);
1192
+        array_shift($domain);
1193
+        $domain = implode('.', $domain);
1194
+
1195
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1196
+        if (str_contains($http_noproxy, (string) " .$domain ")) {
1197
+            return '';
1198
+        }
1199
+    }
1200
+
1201
+    // ok c'est pas une exception
1202
+    return $http_proxy;
1203 1203
 }
1204 1204
 
1205 1205
 
@@ -1222,59 +1222,59 @@  discard block
 block discarded – undo
1222 1222
  * @return array
1223 1223
  */
1224 1224
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1225
-	$user = $via_proxy = $proxy_user = '';
1226
-	$fopen = false;
1227
-
1228
-	$t = @parse_url($url);
1229
-	$host = $t['host'];
1230
-	if ($t['scheme'] == 'http') {
1231
-		$scheme = 'http';
1232
-		$noproxy = '';
1233
-	} elseif ($t['scheme'] == 'https') {
1234
-		$scheme = 'ssl';
1235
-		$noproxy = 'ssl://';
1236
-		if (!isset($t['port']) || !($port = $t['port'])) {
1237
-			$t['port'] = 443;
1238
-		}
1239
-	} else {
1240
-		$scheme = $t['scheme'];
1241
-		$noproxy = $scheme . '://';
1242
-	}
1243
-	if (isset($t['user'])) {
1244
-		$user = [$t['user'], $t['pass']];
1245
-	}
1246
-
1247
-	if (!isset($t['port']) || !($port = $t['port'])) {
1248
-		$port = 80;
1249
-	}
1250
-	if (!isset($t['path']) || !($path = $t['path'])) {
1251
-		$path = '/';
1252
-	}
1253
-
1254
-	if (!empty($t['query'])) {
1255
-		$path .= '?' . $t['query'];
1256
-	}
1257
-
1258
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1259
-	if (!$f || !is_resource($f)) {
1260
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1261
-		// ce qui correspond a $f===110
1262
-		if (
1263
-			$f !== 110
1264
-			&& !need_proxy($host)
1265
-			&& !_request('tester_proxy')
1266
-			&& (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1267
-		) {
1268
-			$f = @fopen($url, 'rb');
1269
-			spip_log("connexion vers $url par simple fopen", 'distant');
1270
-			$fopen = true;
1271
-		} else {
1272
-			// echec total
1273
-			$f = false;
1274
-		}
1275
-	}
1276
-
1277
-	return [$f, $fopen];
1225
+    $user = $via_proxy = $proxy_user = '';
1226
+    $fopen = false;
1227
+
1228
+    $t = @parse_url($url);
1229
+    $host = $t['host'];
1230
+    if ($t['scheme'] == 'http') {
1231
+        $scheme = 'http';
1232
+        $noproxy = '';
1233
+    } elseif ($t['scheme'] == 'https') {
1234
+        $scheme = 'ssl';
1235
+        $noproxy = 'ssl://';
1236
+        if (!isset($t['port']) || !($port = $t['port'])) {
1237
+            $t['port'] = 443;
1238
+        }
1239
+    } else {
1240
+        $scheme = $t['scheme'];
1241
+        $noproxy = $scheme . '://';
1242
+    }
1243
+    if (isset($t['user'])) {
1244
+        $user = [$t['user'], $t['pass']];
1245
+    }
1246
+
1247
+    if (!isset($t['port']) || !($port = $t['port'])) {
1248
+        $port = 80;
1249
+    }
1250
+    if (!isset($t['path']) || !($path = $t['path'])) {
1251
+        $path = '/';
1252
+    }
1253
+
1254
+    if (!empty($t['query'])) {
1255
+        $path .= '?' . $t['query'];
1256
+    }
1257
+
1258
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1259
+    if (!$f || !is_resource($f)) {
1260
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1261
+        // ce qui correspond a $f===110
1262
+        if (
1263
+            $f !== 110
1264
+            && !need_proxy($host)
1265
+            && !_request('tester_proxy')
1266
+            && (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1267
+        ) {
1268
+            $f = @fopen($url, 'rb');
1269
+            spip_log("connexion vers $url par simple fopen", 'distant');
1270
+            $fopen = true;
1271
+        } else {
1272
+            // echec total
1273
+            $f = false;
1274
+        }
1275
+    }
1276
+
1277
+    return [$f, $fopen];
1278 1278
 }
1279 1279
 
1280 1280
 /**
@@ -1309,124 +1309,124 @@  discard block
 block discarded – undo
1309 1309
  *   resource socket vers l'url demandee
1310 1310
  */
1311 1311
 function lance_requete(
1312
-	$method,
1313
-	$scheme,
1314
-	$user,
1315
-	$host,
1316
-	$path,
1317
-	$port,
1318
-	$noproxy,
1319
-	$refuse_gz = false,
1320
-	$referer = '',
1321
-	$datas = '',
1322
-	$vers = 'HTTP/1.0',
1323
-	$date = ''
1312
+    $method,
1313
+    $scheme,
1314
+    $user,
1315
+    $host,
1316
+    $path,
1317
+    $port,
1318
+    $noproxy,
1319
+    $refuse_gz = false,
1320
+    $referer = '',
1321
+    $datas = '',
1322
+    $vers = 'HTTP/1.0',
1323
+    $date = ''
1324 1324
 ) {
1325 1325
 
1326
-	$proxy_user = '';
1327
-	$http_proxy = need_proxy($host);
1328
-	if ($user) {
1329
-		$user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1330
-	}
1331
-
1332
-	$connect = '';
1333
-	if ($http_proxy) {
1334
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1335
-			$path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1336
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1337
-				. "Host: $path_host\r\n"
1338
-				. "Proxy-Connection: Keep-Alive\r\n";
1339
-		} else {
1340
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1341
-				. ($user ? "$user@" : '')
1342
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1343
-		}
1344
-		$t2 = @parse_url($http_proxy);
1345
-		$first_host = $t2['host'];
1346
-		$first_port = ($t2['port'] ?? null) ?: 80;
1347
-		if ($t2['user'] ?? null) {
1348
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1349
-		}
1350
-	} else {
1351
-		$first_host = $noproxy . $host;
1352
-		$first_port = $port;
1353
-	}
1354
-
1355
-	if ($connect) {
1356
-		$streamContext = stream_context_create([
1357
-			'ssl' => [
1358
-				'verify_peer' => false,
1359
-				'allow_self_signed' => true,
1360
-				'SNI_enabled' => true,
1361
-				'peer_name' => $host,
1362
-			]
1363
-		]);
1364
-		$f = @stream_socket_client(
1365
-			"tcp://$first_host:$first_port",
1366
-			$errno,
1367
-			$errstr,
1368
-			_INC_DISTANT_CONNECT_TIMEOUT,
1369
-			STREAM_CLIENT_CONNECT,
1370
-			$streamContext
1371
-		);
1372
-		spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1373
-		if (!$f) {
1374
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1375
-			return $errno;
1376
-		}
1377
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1378
-
1379
-		fwrite($f, $connect);
1380
-		fwrite($f, "\r\n");
1381
-		$res = fread($f, 1024);
1382
-		if (
1383
-			!$res
1384
-			|| ($res = explode(' ', $res)) === []
1385
-			|| $res[1] !== '200'
1386
-		) {
1387
-			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1388
-			fclose($f);
1389
-
1390
-			return false;
1391
-		}
1392
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1393
-		stream_set_blocking($f, true);
1394
-		// envoyer le handshake
1395
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1396
-		spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1397
-	} else {
1398
-		$ntry = 3;
1399
-		do {
1400
-			$f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1401
-		} while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1402
-		spip_log("Recuperer $path sur $first_host:$first_port par $f");
1403
-		if (!$f) {
1404
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1405
-
1406
-			return $errno;
1407
-		}
1408
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1409
-	}
1410
-
1411
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1412
-
1413
-	$host_port = $host;
1414
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1415
-		$host_port .= ":$port";
1416
-	}
1417
-	$req = "$method $path $vers\r\n"
1418
-		. "Host: $host_port\r\n"
1419
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1420
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1421
-		. ($site ? "Referer: $site/$referer\r\n" : '')
1422
-		. ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1423
-		. ($user ? 'Authorization: Basic ' . base64_encode($user) . "\r\n" : '')
1424
-		. ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1425
-		. (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1326
+    $proxy_user = '';
1327
+    $http_proxy = need_proxy($host);
1328
+    if ($user) {
1329
+        $user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1330
+    }
1331
+
1332
+    $connect = '';
1333
+    if ($http_proxy) {
1334
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1335
+            $path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1336
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1337
+                . "Host: $path_host\r\n"
1338
+                . "Proxy-Connection: Keep-Alive\r\n";
1339
+        } else {
1340
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1341
+                . ($user ? "$user@" : '')
1342
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1343
+        }
1344
+        $t2 = @parse_url($http_proxy);
1345
+        $first_host = $t2['host'];
1346
+        $first_port = ($t2['port'] ?? null) ?: 80;
1347
+        if ($t2['user'] ?? null) {
1348
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1349
+        }
1350
+    } else {
1351
+        $first_host = $noproxy . $host;
1352
+        $first_port = $port;
1353
+    }
1354
+
1355
+    if ($connect) {
1356
+        $streamContext = stream_context_create([
1357
+            'ssl' => [
1358
+                'verify_peer' => false,
1359
+                'allow_self_signed' => true,
1360
+                'SNI_enabled' => true,
1361
+                'peer_name' => $host,
1362
+            ]
1363
+        ]);
1364
+        $f = @stream_socket_client(
1365
+            "tcp://$first_host:$first_port",
1366
+            $errno,
1367
+            $errstr,
1368
+            _INC_DISTANT_CONNECT_TIMEOUT,
1369
+            STREAM_CLIENT_CONNECT,
1370
+            $streamContext
1371
+        );
1372
+        spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1373
+        if (!$f) {
1374
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1375
+            return $errno;
1376
+        }
1377
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1378
+
1379
+        fwrite($f, $connect);
1380
+        fwrite($f, "\r\n");
1381
+        $res = fread($f, 1024);
1382
+        if (
1383
+            !$res
1384
+            || ($res = explode(' ', $res)) === []
1385
+            || $res[1] !== '200'
1386
+        ) {
1387
+            spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1388
+            fclose($f);
1389
+
1390
+            return false;
1391
+        }
1392
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1393
+        stream_set_blocking($f, true);
1394
+        // envoyer le handshake
1395
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1396
+        spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1397
+    } else {
1398
+        $ntry = 3;
1399
+        do {
1400
+            $f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1401
+        } while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1402
+        spip_log("Recuperer $path sur $first_host:$first_port par $f");
1403
+        if (!$f) {
1404
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1405
+
1406
+            return $errno;
1407
+        }
1408
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1409
+    }
1410
+
1411
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1412
+
1413
+    $host_port = $host;
1414
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1415
+        $host_port .= ":$port";
1416
+    }
1417
+    $req = "$method $path $vers\r\n"
1418
+        . "Host: $host_port\r\n"
1419
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1420
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1421
+        . ($site ? "Referer: $site/$referer\r\n" : '')
1422
+        . ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1423
+        . ($user ? 'Authorization: Basic ' . base64_encode($user) . "\r\n" : '')
1424
+        . ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1425
+        . (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1426 1426
 
1427 1427
 #	spip_log("Requete\n$req", 'distant');
1428
-	fwrite($f, $req);
1429
-	fwrite($f, $datas ?: "\r\n");
1428
+    fwrite($f, $req);
1429
+    fwrite($f, $datas ?: "\r\n");
1430 1430
 
1431
-	return $f;
1431
+    return $f;
1432 1432
 }
Please login to merge, or discard this patch.
Spacing   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28 28
 }
29 29
 if (!defined('_INC_DISTANT_USER_AGENT')) {
30
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
31 31
 }
32 32
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
33 33
 	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37 37
 }
38 38
 
39
-define('_REGEXP_COPIE_LOCALE', ',' 	.
39
+define('_REGEXP_COPIE_LOCALE', ','.
40 40
 	preg_replace(
41 41
 		'@^https?:@',
42 42
 		'https?:',
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 
74 74
 	// si c'est la protection de soi-meme, retourner le path
75 75
 	if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
-		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
76
+		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)).urldecode($match[1]);
77 77
 
78 78
 		return @file_exists($source) ? $source : false;
79 79
 	}
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		return false;
94 94
 	}
95 95
 
96
-	$localrac = _DIR_RACINE . $local;
96
+	$localrac = _DIR_RACINE.$local;
97 97
 	$t = ($mode === 'force') ? false : @file_exists($localrac);
98 98
 
99 99
 	// test d'existence du fichier
@@ -113,18 +113,18 @@  discard block
 block discarded – undo
113 113
 		if (!$taille_max) {
114 114
 			$taille_max = _COPIE_LOCALE_MAX_SIZE;
115 115
 		}
116
-		$localrac_tmp = $localrac . '.tmp';
116
+		$localrac_tmp = $localrac.'.tmp';
117 117
 		$res = recuperer_url(
118 118
 			$source,
119 119
 			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120 120
 		);
121 121
 
122 122
 		if (!$res || !$res['length'] && $res['status'] != 304) {
123
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
123
+			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : ".($res ? $res['status'] : '-'), 'distant'._LOG_INFO_IMPORTANTE);
124 124
 			@unlink($localrac_tmp);
125 125
 		}
126 126
 		else {
127
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
+			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille ".$res['length'].' status '.$res['status'], 'distant');
128 128
 		}
129 129
 		if (!$res || !$res['length']) {
130 130
 			// si $t c'est sans doute juste un not-modified-since
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 			&& is_callable($callback_valider_url)
138 138
 			&& !$callback_valider_url($res['url'])
139 139
 		) {
140
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
+			spip_log('copie_locale : url finale '.$res['url']." non valide, on refuse le fichier $localrac_tmp", 'distant'._LOG_INFO_IMPORTANTE);
141 141
 			@unlink($localrac_tmp);
142 142
 			return $t ? $local : false;
143 143
 		}
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 
228 228
 	if (!$is_known_host) {
229 229
 		$host = trim($parsed_url['host'], '.');
230
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
230
+		if (!$ip = filter_var($host, FILTER_VALIDATE_IP)) {
231 231
 			$ip = gethostbyname($host);
232 232
 			if ($ip === $host) {
233 233
 				// Error condition for gethostbyname()
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 				$ip = false;
248 248
 			}
249 249
 		}
250
-		if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250
+		if ($ip && !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
251 251
 			return false;
252 252
 		}
253 253
 	}
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 				}
329 329
 			}
330 330
 			if ($taille > 500) {
331
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
331
+				$boundary = substr(md5(random_int(0, mt_getrandmax()).'spip'), 0, 8);
332 332
 			}
333 333
 		}
334 334
 
@@ -361,10 +361,10 @@  discard block
 block discarded – undo
361 361
 				foreach ($donnees as $cle => $valeur) {
362 362
 					if (is_array($valeur)) {
363 363
 						foreach ($valeur as $val2) {
364
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
364
+							$chaine[] = rawurlencode($cle).'[]='.rawurlencode((string) $val2);
365 365
 						}
366 366
 					} else {
367
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
367
+						$chaine[] = rawurlencode($cle).'='.rawurlencode((string) $valeur);
368 368
 					}
369 369
 				}
370 370
 				$chaine = implode('&', $chaine);
@@ -465,13 +465,13 @@  discard block
 block discarded – undo
465 465
 		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
466 466
 	}
467 467
 
468
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
468
+	spip_log('recuperer_url '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
469 469
 
470 470
 	// Ajout des en-têtes spécifiques si besoin
471 471
 	$formatted_data = '';
472 472
 	if (!empty($options['headers'])) {
473 473
 		foreach ($options['headers'] as $champ => $valeur) {
474
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
474
+			$formatted_data .= $champ.': '.$valeur."\r\n";
475 475
 		}
476 476
 	}
477 477
 
@@ -479,9 +479,9 @@  discard block
 block discarded – undo
479 479
 		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
480 480
 		$head .= $formatted_data;
481 481
 		if (stripos($head, 'Content-Length:') === false) {
482
-			$head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
482
+			$head .= 'Content-Length: '.strlen((string) $postdata)."\r\n";
483 483
 		}
484
-		$formatted_data = $head . "\r\n" . $postdata;
484
+		$formatted_data = $head."\r\n".$postdata;
485 485
 		if (
486 486
 			strlen((string) $postdata) && !$methode_demandee
487 487
 		) {
@@ -494,9 +494,9 @@  discard block
 block discarded – undo
494 494
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
495 495
 	$url = preg_replace(',^feed://,i', 'http://', $url);
496 496
 	if (!tester_url_absolue($url)) {
497
-		$url = 'http://' . $url;
497
+		$url = 'http://'.$url;
498 498
 	} elseif (str_starts_with($url, '//')) {
499
-		$url = 'http:' . $url;
499
+		$url = 'http:'.$url;
500 500
 	}
501 501
 
502 502
 	$url = url_to_ascii($url);
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
 		$options['if_modified_since']
526 526
 	);
527 527
 	if (!$handle) {
528
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
528
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
529 529
 
530 530
 		return false;
531 531
 	}
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 					'status' => 200,
556 556
 				];
557 557
 			} else {
558
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
558
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
559 559
 				return false;
560 560
 			}
561 561
 		} elseif ($res['location'] && $options['follow_location']) {
@@ -572,11 +572,11 @@  discard block
 block discarded – undo
572 572
 				$options['methode'] = 'GET';
573 573
 				$options['datas'] = '';
574 574
 			}
575
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
575
+			spip_log('recuperer_url recommence '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
576 576
 
577 577
 			return recuperer_url($url, $options);
578 578
 		} elseif ($res['status'] !== 200) {
579
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
579
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
580 580
 		}
581 581
 		$result['status'] = $res['status'];
582 582
 		if (isset($res['headers'])) {
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
 
593 593
 	// on ne veut que les entetes
594 594
 	if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
595
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
595
+		spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($result, JSON_THROW_ON_ERROR), 'distant'._LOG_DEBUG);
596 596
 		return $result;
597 597
 	}
598 598
 
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
 
603 603
 	$gz = false;
604 604
 	if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
605
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
605
+		$gz = (_DIR_TMP.md5(uniqid(random_int(0, mt_getrandmax()))).'.tmp.gz');
606 606
 	}
607 607
 
608 608
 	// si on a pas deja recuperer le contenu par une methode detournee
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 
639 639
 	$trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
640 640
 	$trace['page'] = '...';
641
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
641
+	spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($trace, JSON_THROW_ON_ERROR), 'distant'._LOG_DEBUG);
642 642
 
643 643
 	return $result;
644 644
 }
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
 	$sig['url'] = $url;
693 693
 
694 694
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
695
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
695
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
696 696
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
697 697
 	$cache = "$sub$cache";
698 698
 
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
 	$fp = false;
747 747
 	if ($fichier) {
748 748
 		include_spip('inc/acces');
749
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
749
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
750 750
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
751 751
 		if (!$fp && file_exists($fichier)) {
752 752
 			return filesize($fichier);
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
 	}
806 806
 	$result['status'] = (int) $r[1];
807 807
 	while ($s = trim(fgets($handle, 16384))) {
808
-		$result['headers'][] = $s . "\n";
808
+		$result['headers'][] = $s."\n";
809 809
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
810 810
 		[, $d, $v] = $r;
811 811
 		if (strtolower(trim($d)) == 'location' && $result['status'] >= 300 && $result['status'] < 400) {
@@ -854,13 +854,13 @@  discard block
 block discarded – undo
854 854
 
855 855
 	// on se place tout le temps comme si on etait a la racine
856 856
 	if (_DIR_RACINE) {
857
-		$d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
857
+		$d = preg_replace(',^'.preg_quote((string) _DIR_RACINE, ',').',', '', (string) $d);
858 858
 	}
859 859
 
860 860
 	$m = md5($source);
861 861
 
862 862
 	return $d
863
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
863
+	. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
864 864
 	. substr($m, 0, 4)
865 865
 	. ".$extension";
866 866
 }
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
 	// Si c'est deja local pas de souci
885 885
 	if (!tester_url_absolue($source)) {
886 886
 		if (_DIR_RACINE) {
887
-			$source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
887
+			$source = preg_replace(',^'.preg_quote((string) _DIR_RACINE, ',').',', '', $source);
888 888
 		}
889 889
 
890 890
 		return $source;
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 		$ext
903 903
 		&& preg_match(',^\w+$,', $ext)
904 904
 		&& ($f = nom_fichier_copie_locale($source, $ext))
905
-		&& file_exists(_DIR_RACINE . $f)
905
+		&& file_exists(_DIR_RACINE.$f)
906 906
 	) {
907 907
 		return $f;
908 908
 	}
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
 
911 911
 	// Si c'est deja dans la table des documents,
912 912
 	// ramener le nom de sa copie potentielle
913
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
913
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
914 914
 
915 915
 	if ($ext) {
916 916
 		return nom_fichier_copie_locale($source, $ext);
@@ -921,9 +921,9 @@  discard block
 block discarded – undo
921 921
 
922 922
 	$ext = $path_parts ? $path_parts['extension'] : '';
923 923
 
924
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
924
+	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
925 925
 		$f = nom_fichier_copie_locale($source, $ext);
926
-		if (file_exists(_DIR_RACINE . $f)) {
926
+		if (file_exists(_DIR_RACINE.$f)) {
927 927
 			return $f;
928 928
 		}
929 929
 	}
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
 	// Ping  pour voir si son extension est connue et autorisee
932 932
 	// avec mise en cache du resultat du ping
933 933
 
934
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
934
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
935 935
 	if (
936 936
 		!@file_exists($cache)
937 937
 		|| !($path_parts = @unserialize(spip_file_get_contents($cache)))
@@ -941,11 +941,11 @@  discard block
 block discarded – undo
941 941
 		ecrire_fichier($cache, serialize($path_parts));
942 942
 	}
943 943
 	$ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
944
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
944
+	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
945 945
 		return nom_fichier_copie_locale($source, $ext);
946 946
 	}
947 947
 
948
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
948
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
949 949
 	return null;
950 950
 }
951 951
 
@@ -1044,7 +1044,7 @@  discard block
 block discarded – undo
1044 1044
 		} else {
1045 1045
 			if ($a['body']) {
1046 1046
 				$a['extension'] = $extension;
1047
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1047
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1048 1048
 				ecrire_fichier($a['fichier'], $a['body']);
1049 1049
 				$size_image = @spip_getimagesize($a['fichier']);
1050 1050
 				$a['largeur'] = (int) $size_image[0];
@@ -1107,20 +1107,20 @@  discard block
 block discarded – undo
1107 1107
 	$t = null;
1108 1108
 	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1109 1109
 		if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1110
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1110
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1111 1111
 		}
1112 1112
 		if (
1113 1113
 			!$t
1114 1114
 			&& preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1115 1115
 			&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1116 1116
 		) {
1117
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1117
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1118 1118
 		}
1119 1119
 	}
1120 1120
 
1121 1121
 	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1122 1122
 	if (!$t) {
1123
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1123
+		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1124 1124
 	}
1125 1125
 
1126 1126
 	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1131,11 +1131,11 @@  discard block
 block discarded – undo
1131 1131
 		&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1132 1132
 	) {
1133 1133
 		# eviter xxx.3 => 3gp (> SPIP 3)
1134
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1134
+		$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1135 1135
 	}
1136 1136
 
1137 1137
 	if ($t) {
1138
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1138
+		spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1139 1139
 		return $t['extension'];
1140 1140
 	} else {
1141 1141
 		# par defaut on retombe sur '.bin' si c'est autorise
@@ -1238,7 +1238,7 @@  discard block
 block discarded – undo
1238 1238
 		}
1239 1239
 	} else {
1240 1240
 		$scheme = $t['scheme'];
1241
-		$noproxy = $scheme . '://';
1241
+		$noproxy = $scheme.'://';
1242 1242
 	}
1243 1243
 	if (isset($t['user'])) {
1244 1244
 		$user = [$t['user'], $t['pass']];
@@ -1252,7 +1252,7 @@  discard block
 block discarded – undo
1252 1252
 	}
1253 1253
 
1254 1254
 	if (!empty($t['query'])) {
1255
-		$path .= '?' . $t['query'];
1255
+		$path .= '?'.$t['query'];
1256 1256
 	}
1257 1257
 
1258 1258
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1326,29 +1326,29 @@  discard block
 block discarded – undo
1326 1326
 	$proxy_user = '';
1327 1327
 	$http_proxy = need_proxy($host);
1328 1328
 	if ($user) {
1329
-		$user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1329
+		$user = urlencode((string) $user[0]).':'.urlencode((string) $user[1]);
1330 1330
 	}
1331 1331
 
1332 1332
 	$connect = '';
1333 1333
 	if ($http_proxy) {
1334
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1335
-			$path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1336
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1334
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls', 'ssl'])) {
1335
+			$path_host = ($user ? "$user@" : '').$host.(($port != 80) ? ":$port" : '');
1336
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1337 1337
 				. "Host: $path_host\r\n"
1338 1338
 				. "Proxy-Connection: Keep-Alive\r\n";
1339 1339
 		} else {
1340
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1340
+			$path = (in_array($scheme, ['tls', 'ssl']) ? 'https://' : "$scheme://")
1341 1341
 				. ($user ? "$user@" : '')
1342
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1342
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1343 1343
 		}
1344 1344
 		$t2 = @parse_url($http_proxy);
1345 1345
 		$first_host = $t2['host'];
1346 1346
 		$first_port = ($t2['port'] ?? null) ?: 80;
1347 1347
 		if ($t2['user'] ?? null) {
1348
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1348
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1349 1349
 		}
1350 1350
 	} else {
1351
-		$first_host = $noproxy . $host;
1351
+		$first_host = $noproxy.$host;
1352 1352
 		$first_port = $port;
1353 1353
 	}
1354 1354
 
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
 		);
1372 1372
 		spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1373 1373
 		if (!$f) {
1374
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1374
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1375 1375
 			return $errno;
1376 1376
 		}
1377 1377
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1384,7 +1384,7 @@  discard block
 block discarded – undo
1384 1384
 			|| ($res = explode(' ', $res)) === []
1385 1385
 			|| $res[1] !== '200'
1386 1386
 		) {
1387
-			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1387
+			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect'._LOG_INFO_IMPORTANTE);
1388 1388
 			fclose($f);
1389 1389
 
1390 1390
 			return false;
@@ -1401,7 +1401,7 @@  discard block
 block discarded – undo
1401 1401
 		} while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1402 1402
 		spip_log("Recuperer $path sur $first_host:$first_port par $f");
1403 1403
 		if (!$f) {
1404
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1404
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1405 1405
 
1406 1406
 			return $errno;
1407 1407
 		}
@@ -1411,16 +1411,16 @@  discard block
 block discarded – undo
1411 1411
 	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1412 1412
 
1413 1413
 	$host_port = $host;
1414
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1414
+	if ($port != (in_array($scheme, ['tls', 'ssl']) ? 443 : 80)) {
1415 1415
 		$host_port .= ":$port";
1416 1416
 	}
1417 1417
 	$req = "$method $path $vers\r\n"
1418 1418
 		. "Host: $host_port\r\n"
1419
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1420
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1419
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1420
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1421 1421
 		. ($site ? "Referer: $site/$referer\r\n" : '')
1422
-		. ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1423
-		. ($user ? 'Authorization: Basic ' . base64_encode($user) . "\r\n" : '')
1422
+		. ($date ? 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n") : '')
1423
+		. ($user ? 'Authorization: Basic '.base64_encode($user)."\r\n" : '')
1424 1424
 		. ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1425 1425
 		. (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1426 1426
 
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -122,8 +122,7 @@  discard block
 block discarded – undo
122 122
 		if (!$res || !$res['length'] && $res['status'] != 304) {
123 123
 			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124 124
 			@unlink($localrac_tmp);
125
-		}
126
-		else {
125
+		} else {
127 126
 			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
128 127
 		}
129 128
 		if (!$res || !$res['length']) {
@@ -242,8 +241,7 @@  discard block
 block discarded – undo
242 241
 						break;
243 242
 					}
244 243
 				}
245
-			}
246
-			else {
244
+			} else {
247 245
 				$ip = false;
248 246
 			}
249 247
 		}
Please login to merge, or discard this patch.
ecrire/inc/modeles.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
 use Spip\Texte\Collecteur\Modeles;
14 14
 
15 15
 if (!defined('_ECRIRE_INC_VERSION')) {
16
-	return;
16
+    return;
17 17
 }
18 18
 
19 19
 /**
@@ -26,16 +26,16 @@  discard block
 block discarded – undo
26 26
  */
27 27
 function traiter_modeles($texte, $doublons = false, $echap = '', string $connect = '', ?Liens $collecteurLiens = null, $env = []) {
28 28
 
29
-	include_spip('src/Texte/Collecteur/AbstractCollecteur');
30
-	include_spip('src/Texte/Collecteur/Modeles');
31
-	$collecteurModeles = new Modeles();
29
+    include_spip('src/Texte/Collecteur/AbstractCollecteur');
30
+    include_spip('src/Texte/Collecteur/Modeles');
31
+    $collecteurModeles = new Modeles();
32 32
 
33
-	$options = [
34
-		'doublons' => $doublons,
35
-		'echap' => $echap,
36
-		'connect' => $connect,
37
-		'collecteurLiens' => $collecteurLiens,
38
-		'env' => $env
39
-	];
40
-	return $collecteurModeles->traiter($texte ?? '', $options);
33
+    $options = [
34
+        'doublons' => $doublons,
35
+        'echap' => $echap,
36
+        'connect' => $connect,
37
+        'collecteurLiens' => $collecteurLiens,
38
+        'env' => $env
39
+    ];
40
+    return $collecteurModeles->traiter($texte ?? '', $options);
41 41
 }
Please login to merge, or discard this patch.
ecrire/inc/informer.php 2 patches
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -10,76 +10,76 @@
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 # Les information d'une rubrique selectionnee dans le mini navigateur
17 17
 
18 18
 function inc_informer_dist($id, $col, $exclus, $rac, $type, $do = 'aff') {
19
-	include_spip('inc/texte');
20
-	$titre = $descriptif = '';
21
-	if ($type === 'rubrique') {
22
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . (int) $id);
23
-		if ($row) {
24
-			$titre = typo($row['titre']);
25
-			$descriptif = propre($row['descriptif']);
26
-		} else {
27
-			$titre = _T('info_racine_site');
28
-		}
29
-	}
19
+    include_spip('inc/texte');
20
+    $titre = $descriptif = '';
21
+    if ($type === 'rubrique') {
22
+        $row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . (int) $id);
23
+        if ($row) {
24
+            $titre = typo($row['titre']);
25
+            $descriptif = propre($row['descriptif']);
26
+        } else {
27
+            $titre = _T('info_racine_site');
28
+        }
29
+    }
30 30
 
31
-	$res = '';
32
-	if (
33
-		$type === 'rubrique'
34
-		&& (int) ($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
35
-		&& isset($GLOBALS['meta']['image_process'])
36
-		&& $GLOBALS['meta']['image_process'] !== 'non'
37
-	) {
38
-		$chercher_logo = charger_fonction('chercher_logo', 'inc');
39
-		if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
40
-			[$fid, $dir, $nom, $format] = $res;
41
-			include_spip('inc/filtres_images_mini');
42
-			$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
43
-			if ($res) {
44
-				$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
45
-			}
46
-		}
47
-	}
31
+    $res = '';
32
+    if (
33
+        $type === 'rubrique'
34
+        && (int) ($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
35
+        && isset($GLOBALS['meta']['image_process'])
36
+        && $GLOBALS['meta']['image_process'] !== 'non'
37
+    ) {
38
+        $chercher_logo = charger_fonction('chercher_logo', 'inc');
39
+        if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
40
+            [$fid, $dir, $nom, $format] = $res;
41
+            include_spip('inc/filtres_images_mini');
42
+            $res = image_reduire("<img src='$fid' alt='' />", 100, 48);
43
+            if ($res) {
44
+                $res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
45
+            }
46
+        }
47
+    }
48 48
 
49
-	$rac = spip_htmlentities($rac, ENT_QUOTES);
50
-	$do = spip_htmlentities($do, ENT_QUOTES);
51
-	$id = (int) $id;
49
+    $rac = spip_htmlentities($rac, ENT_QUOTES);
50
+    $do = spip_htmlentities($do, ENT_QUOTES);
51
+    $id = (int) $id;
52 52
 
53 53
 # ce lien provoque la selection (directe) de la rubrique cliquee
54 54
 # et l'affichage de son titre dans le bandeau
55
-	$titre = strtr(
56
-		str_replace(
57
-			"'",
58
-			'&#8217;',
59
-			str_replace('"', '&#34;', (string) textebrut($titre))
60
-		),
61
-		"\n\r",
62
-		'  '
63
-	);
55
+    $titre = strtr(
56
+        str_replace(
57
+            "'",
58
+            '&#8217;',
59
+            str_replace('"', '&#34;', (string) textebrut($titre))
60
+        ),
61
+        "\n\r",
62
+        '  '
63
+    );
64 64
 
65
-	$js_func = $do . '_selection_titre';
65
+    $js_func = $do . '_selection_titre';
66 66
 
67
-	return "<div style='display: none;'>"
68
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
69
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
70
-	. entites_html($titre)
71
-	. '" />'
72
-	. '</div>'
73
-	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
74
-	. '<div class="informer__item">'
75
-	. ($res ?: '')
76
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
77
-	. ($descriptif ? "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>' : '')
78
-	. '</div>'
79
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
80
-	. "<input type='submit' class='fondo btn submit' value='"
81
-	. _T('bouton_choisir')
82
-	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
83
-	. '</div>'
84
-	. '</div>';
67
+    return "<div style='display: none;'>"
68
+    . "<input type='text' id='" . $rac . "_sel' value='$id' />"
69
+    . "<input type='text' id='" . $rac . "_sel2' value=\""
70
+    . entites_html($titre)
71
+    . '" />'
72
+    . '</div>'
73
+    . "<div class='informer' style='padding: 5px; border-top: 0px;'>"
74
+    . '<div class="informer__item">'
75
+    . ($res ?: '')
76
+    . "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
77
+    . ($descriptif ? "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>' : '')
78
+    . '</div>'
79
+    . "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
80
+    . "<input type='submit' class='fondo btn submit' value='"
81
+    . _T('bouton_choisir')
82
+    . "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
83
+    . '</div>'
84
+    . '</div>';
85 85
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 	include_spip('inc/texte');
20 20
 	$titre = $descriptif = '';
21 21
 	if ($type === 'rubrique') {
22
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . (int) $id);
22
+		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = '.(int) $id);
23 23
 		if ($row) {
24 24
 			$titre = typo($row['titre']);
25 25
 			$descriptif = propre($row['descriptif']);
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 			include_spip('inc/filtres_images_mini');
42 42
 			$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
43 43
 			if ($res) {
44
-				$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
44
+				$res = "<div class='informer__media' style='float: ".$GLOBALS['spip_lang_right'].'; margin-'.$GLOBALS['spip_lang_right'].": -5px; margin-top: -5px;'>$res</div>";
45 45
 			}
46 46
 		}
47 47
 	}
@@ -62,21 +62,21 @@  discard block
 block discarded – undo
62 62
 		'  '
63 63
 	);
64 64
 
65
-	$js_func = $do . '_selection_titre';
65
+	$js_func = $do.'_selection_titre';
66 66
 
67 67
 	return "<div style='display: none;'>"
68
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
69
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
68
+	. "<input type='text' id='".$rac."_sel' value='$id' />"
69
+	. "<input type='text' id='".$rac."_sel2' value=\""
70 70
 	. entites_html($titre)
71 71
 	. '" />'
72 72
 	. '</div>'
73 73
 	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
74 74
 	. '<div class="informer__item">'
75 75
 	. ($res ?: '')
76
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
77
-	. ($descriptif ? "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>' : '')
76
+	. "<p class='informer__titre'><b>".safehtml($titre).'</b></p>'
77
+	. ($descriptif ? "<div class='informer__descriptif'>".safehtml($descriptif).'</div>' : '')
78 78
 	. '</div>'
79
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
79
+	. "<div class='informer__action' style='clear:both; text-align: ".$GLOBALS['spip_lang_right'].";'>"
80 80
 	. "<input type='submit' class='fondo btn submit' value='"
81 81
 	. _T('bouton_choisir')
82 82
 	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
Please login to merge, or discard this patch.