Completed
Push — master ( 3898e1...ad50fe )
by cam
01:35
created
ecrire/exec/admin_plugin.php 1 patch
Indentation   +203 added lines, -203 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 include_spip('inc/config');
@@ -37,26 +37,26 @@  discard block
 block discarded – undo
37 37
  */
38 38
 function exec_admin_plugin_dist($retour = '') {
39 39
 
40
-	if (!autoriser('configurer', '_plugins')) {
41
-		include_spip('inc/minipres');
42
-		echo minipres();
43
-	} else {
44
-		// on fait la verif du path avant tout,
45
-		// et l'installation des qu'on est dans la colonne principale
46
-		// si jamais la liste des plugins actifs change, il faut faire un refresh du hit
47
-		// pour etre sur que les bons fichiers seront charges lors de l'install
48
-		$new = actualise_plugins_actifs();
49
-		if ($new and _request('actualise') < 2) {
50
-			include_spip('inc/headers');
51
-			if (isset($GLOBALS['fichier_php_compile_recent'])) {
52
-				// attendre eventuellement l'invalidation du cache opcode
53
-				spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
54
-			}
55
-			redirige_par_entete(parametre_url(self(), 'actualise', _request('actualise') + 1, '&'));
56
-		} else {
57
-			admin_plug_args(_request('voir'), _request('erreur'), _request('format'));
58
-		}
59
-	}
40
+    if (!autoriser('configurer', '_plugins')) {
41
+        include_spip('inc/minipres');
42
+        echo minipres();
43
+    } else {
44
+        // on fait la verif du path avant tout,
45
+        // et l'installation des qu'on est dans la colonne principale
46
+        // si jamais la liste des plugins actifs change, il faut faire un refresh du hit
47
+        // pour etre sur que les bons fichiers seront charges lors de l'install
48
+        $new = actualise_plugins_actifs();
49
+        if ($new and _request('actualise') < 2) {
50
+            include_spip('inc/headers');
51
+            if (isset($GLOBALS['fichier_php_compile_recent'])) {
52
+                // attendre eventuellement l'invalidation du cache opcode
53
+                spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
54
+            }
55
+            redirige_par_entete(parametre_url(self(), 'actualise', _request('actualise') + 1, '&'));
56
+        } else {
57
+            admin_plug_args(_request('voir'), _request('erreur'), _request('format'));
58
+        }
59
+    }
60 60
 }
61 61
 
62 62
 /**
@@ -81,132 +81,132 @@  discard block
 block discarded – undo
81 81
  *     Format d'affichage (liste ou arborescence)
82 82
  **/
83 83
 function admin_plug_args($quoi, $erreur, $format) {
84
-	$lpf = null;
85
-	$lcpas = null;
86
-	$lcpaffichesup = null;
87
-	if (!$quoi) {
88
-		$quoi = 'actifs';
89
-	}
90
-	// empecher l'affichage des erreurs dans le bandeau, on le donne ensuite
91
-	// format brut par plugin
92
-	$GLOBALS['erreurs_activation_raw'] = plugin_donne_erreurs(true, false);
93
-	// format resume mis en forme
94
-	$erreur_activation = plugin_donne_erreurs();
95
-	$commencer_page = charger_fonction('commencer_page', 'inc');
96
-	echo $commencer_page(_T('icone_admin_plugin'), 'configuration', 'plugin');
97
-
98
-	echo debut_gauche();
99
-	echo recuperer_fond('prive/squelettes/navigation/configurer', ['exec' => 'admin_plugin']);
100
-
101
-	echo pipeline(
102
-		'affiche_gauche',
103
-		[
104
-			'args' => ['exec' => 'admin_plugin'],
105
-			'data' => afficher_librairies()
106
-		]
107
-	);
108
-
109
-	echo debut_droite();
110
-	echo gros_titre(_T('icone_admin_plugin'), '');
111
-
112
-	// Barre d'onglets de premier niveau
113
-	echo barre_onglets('plugins', 'plugins_actifs');
114
-	// Barre d'onglets de second niveau
115
-	$onglet2 = $quoi == 'actifs' ? 'plugins_actifs' : 'admin_plugin';
116
-	echo debut_onglet('onglets_simple second');
117
-	echo onglet(_T('plugins_tous_liste'), generer_url_ecrire('admin_plugin', 'voir=tous'), 'admin_plugin', $onglet2);
118
-	echo onglet(_T('plugins_actifs_liste'), generer_url_ecrire('admin_plugin'), 'plugins_actifs', $onglet2);
119
-	echo fin_onglet();
120
-
121
-	// message d'erreur au retour d'une operation
122
-	if ($erreur) {
123
-		echo "<div class='error'>" . spip_htmlspecialchars($erreur) . '</div>';
124
-	}
125
-	if ($erreur_activation) {
126
-		echo "<div class='error'>$erreur_activation</div>";
127
-	}
128
-
129
-	// la mise a jour de cette meta a ete faite par ecrire_plugin_actifs
130
-	$actifs = (array) unserialize($GLOBALS['meta']['plugin']);
131
-	$lcpa = $actifs + (array) unserialize($GLOBALS['meta']['plugin_attente']);
132
-
133
-	// Les affichages se basent sur le repertoire, pas sur le nom
134
-	$actifs = liste_chemin_plugin($actifs, '');
135
-	if (defined('_DIR_PLUGINS_SUPPL')) {
136
-		$lcpas = liste_chemin_plugin($lcpa, _DIR_PLUGINS_SUPPL);
137
-	}
138
-	$lcpa = liste_chemin_plugin($lcpa);
139
-
140
-	// on installe les plugins maintenant,
141
-	// cela permet aux scripts d'install de faire des affichages (moches...)
142
-	plugin_installes_meta();
143
-
144
-	echo "<div class='liste-plugins formulaire_spip'>";
145
-	echo debut_cadre_trait_couleur('plugin-24.png', true, '', _T('plugins_liste'), 'plugins');
146
-
147
-	if ($quoi !== 'actifs') {
148
-		$lpf = liste_plugin_files();
149
-		if ($lpf) {
150
-			echo '<p>' . _T('texte_presente_plugin') . '</p>';
151
-		} else {
152
-			if (!@is_dir(_DIR_PLUGINS)) {
153
-				echo '<p>' . _T('plugin_info_automatique_ftp', ['rep' => joli_repertoire(_DIR_PLUGINS)])
154
-					. ' &mdash; ' . _T('plugin_info_automatique_creer') . '</p>';
155
-			}
156
-		}
157
-		$lcpaffiche = $lpf;
158
-		if (defined('_DIR_PLUGINS_SUPPL')) {
159
-			$lcpaffichesup = liste_plugin_files(_DIR_PLUGINS_SUPPL);
160
-		}
161
-	} else {
162
-		// la liste
163
-		// $quoi=='actifs'
164
-		$lcpaffiche = $lcpa;
165
-		if (defined('_DIR_PLUGINS_SUPPL')) {
166
-			$lcpaffichesup = $lcpas;
167
-		}
168
-	}
169
-
170
-	if ($quoi == 'actifs' or $lpf) {
171
-		$nb = is_countable($lcpa) ? count($lcpa) : 0;
172
-		if (defined('_DIR_PLUGINS_SUPPL')) {
173
-			$nb += is_countable($lcpas) ? count($lcpas) : 0;
174
-		}
175
-		echo '<h3>' . sinon(
176
-			singulier_ou_pluriel($nb, 'plugins_actif_un', 'plugins_actifs', 'count'),
177
-			_T('plugins_actif_aucun')
178
-		) . '</h3>';
179
-	}
180
-
181
-	if (empty($format)) {
182
-		$format = 'liste';
183
-	} elseif (!in_array($format, ['liste', 'repertoires'])) {
184
-		$format = 'repertoires';
185
-	}
186
-
187
-	$afficher = charger_fonction("afficher_$format", 'plugins');
188
-	$corps = $afficher(self(), $lcpaffiche, $lcpa, $actifs);
189
-	if (defined('_DIR_PLUGINS_SUPPL')) {
190
-		$corps .= $afficher(self(), $lcpaffichesup, $lcpas, $actifs, _DIR_PLUGINS_SUPPL);
191
-	}
192
-
193
-	if ($corps) {
194
-		$corps .= "\n<div class='boutons' style='display:none;'>"
195
-			. "<input type='submit' class='submit save' value='" . _T('bouton_enregistrer')
196
-			. "' />"
197
-			. '</div>';
198
-	}
199
-
200
-	echo redirige_action_post('activer_plugins', 'activer', 'admin_plugin', '', $corps);
201
-
202
-	echo fin_cadre_trait_couleur();
203
-
204
-	if ($quoi == 'actifs') {
205
-		echo affiche_les_plugins_verrouilles($actifs);
206
-	}
207
-	echo '</div>';
208
-
209
-	echo http_script("
84
+    $lpf = null;
85
+    $lcpas = null;
86
+    $lcpaffichesup = null;
87
+    if (!$quoi) {
88
+        $quoi = 'actifs';
89
+    }
90
+    // empecher l'affichage des erreurs dans le bandeau, on le donne ensuite
91
+    // format brut par plugin
92
+    $GLOBALS['erreurs_activation_raw'] = plugin_donne_erreurs(true, false);
93
+    // format resume mis en forme
94
+    $erreur_activation = plugin_donne_erreurs();
95
+    $commencer_page = charger_fonction('commencer_page', 'inc');
96
+    echo $commencer_page(_T('icone_admin_plugin'), 'configuration', 'plugin');
97
+
98
+    echo debut_gauche();
99
+    echo recuperer_fond('prive/squelettes/navigation/configurer', ['exec' => 'admin_plugin']);
100
+
101
+    echo pipeline(
102
+        'affiche_gauche',
103
+        [
104
+            'args' => ['exec' => 'admin_plugin'],
105
+            'data' => afficher_librairies()
106
+        ]
107
+    );
108
+
109
+    echo debut_droite();
110
+    echo gros_titre(_T('icone_admin_plugin'), '');
111
+
112
+    // Barre d'onglets de premier niveau
113
+    echo barre_onglets('plugins', 'plugins_actifs');
114
+    // Barre d'onglets de second niveau
115
+    $onglet2 = $quoi == 'actifs' ? 'plugins_actifs' : 'admin_plugin';
116
+    echo debut_onglet('onglets_simple second');
117
+    echo onglet(_T('plugins_tous_liste'), generer_url_ecrire('admin_plugin', 'voir=tous'), 'admin_plugin', $onglet2);
118
+    echo onglet(_T('plugins_actifs_liste'), generer_url_ecrire('admin_plugin'), 'plugins_actifs', $onglet2);
119
+    echo fin_onglet();
120
+
121
+    // message d'erreur au retour d'une operation
122
+    if ($erreur) {
123
+        echo "<div class='error'>" . spip_htmlspecialchars($erreur) . '</div>';
124
+    }
125
+    if ($erreur_activation) {
126
+        echo "<div class='error'>$erreur_activation</div>";
127
+    }
128
+
129
+    // la mise a jour de cette meta a ete faite par ecrire_plugin_actifs
130
+    $actifs = (array) unserialize($GLOBALS['meta']['plugin']);
131
+    $lcpa = $actifs + (array) unserialize($GLOBALS['meta']['plugin_attente']);
132
+
133
+    // Les affichages se basent sur le repertoire, pas sur le nom
134
+    $actifs = liste_chemin_plugin($actifs, '');
135
+    if (defined('_DIR_PLUGINS_SUPPL')) {
136
+        $lcpas = liste_chemin_plugin($lcpa, _DIR_PLUGINS_SUPPL);
137
+    }
138
+    $lcpa = liste_chemin_plugin($lcpa);
139
+
140
+    // on installe les plugins maintenant,
141
+    // cela permet aux scripts d'install de faire des affichages (moches...)
142
+    plugin_installes_meta();
143
+
144
+    echo "<div class='liste-plugins formulaire_spip'>";
145
+    echo debut_cadre_trait_couleur('plugin-24.png', true, '', _T('plugins_liste'), 'plugins');
146
+
147
+    if ($quoi !== 'actifs') {
148
+        $lpf = liste_plugin_files();
149
+        if ($lpf) {
150
+            echo '<p>' . _T('texte_presente_plugin') . '</p>';
151
+        } else {
152
+            if (!@is_dir(_DIR_PLUGINS)) {
153
+                echo '<p>' . _T('plugin_info_automatique_ftp', ['rep' => joli_repertoire(_DIR_PLUGINS)])
154
+                    . ' &mdash; ' . _T('plugin_info_automatique_creer') . '</p>';
155
+            }
156
+        }
157
+        $lcpaffiche = $lpf;
158
+        if (defined('_DIR_PLUGINS_SUPPL')) {
159
+            $lcpaffichesup = liste_plugin_files(_DIR_PLUGINS_SUPPL);
160
+        }
161
+    } else {
162
+        // la liste
163
+        // $quoi=='actifs'
164
+        $lcpaffiche = $lcpa;
165
+        if (defined('_DIR_PLUGINS_SUPPL')) {
166
+            $lcpaffichesup = $lcpas;
167
+        }
168
+    }
169
+
170
+    if ($quoi == 'actifs' or $lpf) {
171
+        $nb = is_countable($lcpa) ? count($lcpa) : 0;
172
+        if (defined('_DIR_PLUGINS_SUPPL')) {
173
+            $nb += is_countable($lcpas) ? count($lcpas) : 0;
174
+        }
175
+        echo '<h3>' . sinon(
176
+            singulier_ou_pluriel($nb, 'plugins_actif_un', 'plugins_actifs', 'count'),
177
+            _T('plugins_actif_aucun')
178
+        ) . '</h3>';
179
+    }
180
+
181
+    if (empty($format)) {
182
+        $format = 'liste';
183
+    } elseif (!in_array($format, ['liste', 'repertoires'])) {
184
+        $format = 'repertoires';
185
+    }
186
+
187
+    $afficher = charger_fonction("afficher_$format", 'plugins');
188
+    $corps = $afficher(self(), $lcpaffiche, $lcpa, $actifs);
189
+    if (defined('_DIR_PLUGINS_SUPPL')) {
190
+        $corps .= $afficher(self(), $lcpaffichesup, $lcpas, $actifs, _DIR_PLUGINS_SUPPL);
191
+    }
192
+
193
+    if ($corps) {
194
+        $corps .= "\n<div class='boutons' style='display:none;'>"
195
+            . "<input type='submit' class='submit save' value='" . _T('bouton_enregistrer')
196
+            . "' />"
197
+            . '</div>';
198
+    }
199
+
200
+    echo redirige_action_post('activer_plugins', 'activer', 'admin_plugin', '', $corps);
201
+
202
+    echo fin_cadre_trait_couleur();
203
+
204
+    if ($quoi == 'actifs') {
205
+        echo affiche_les_plugins_verrouilles($actifs);
206
+    }
207
+    echo '</div>';
208
+
209
+    echo http_script("
210 210
 	jQuery(function(){
211 211
 		jQuery('.plugins li.item a[rel=info]').click(function(){
212 212
 			var li = jQuery(this).parents('li').eq(0);
@@ -232,15 +232,15 @@  discard block
 block discarded – undo
232 232
 	});
233 233
 	");
234 234
 
235
-	echo pipeline(
236
-		'affiche_milieu',
237
-		[
238
-			'args' => ['exec' => 'admin_plugin'],
239
-			'data' => ''
240
-		]
241
-	);
235
+    echo pipeline(
236
+        'affiche_milieu',
237
+        [
238
+            'args' => ['exec' => 'admin_plugin'],
239
+            'data' => ''
240
+        ]
241
+    );
242 242
 
243
-	echo fin_gauche(), fin_page();
243
+    echo fin_gauche(), fin_page();
244 244
 }
245 245
 
246 246
 /**
@@ -254,23 +254,23 @@  discard block
 block discarded – undo
254 254
  *     Code HTML
255 255
  **/
256 256
 function affiche_les_plugins_verrouilles($actifs) {
257
-	if ((!$liste = liste_plugin_files(_DIR_PLUGINS_DIST))) {
258
-		return '';
259
-	}
260
-
261
-	$afficher = charger_fonction('afficher_liste', 'plugins');
262
-	$liste = $afficher(self(), $liste, [], $actifs, _DIR_PLUGINS_DIST);
263
-
264
-	return
265
-		"<div id='plugins_dist'>"
266
-		. debut_cadre_trait_couleur('', true, '', _T('plugins_liste_dist'), 'liste_plugins_dist')
267
-		. '<p>'
268
-		. _T('plugin_info_plugins_dist_1', ['plugins_dist' => joli_repertoire(_DIR_PLUGINS_DIST)])
269
-		. '<br />' . _T('plugin_info_plugins_dist_2')
270
-		. '</p>'
271
-		. $liste
272
-		. fin_cadre_trait_couleur()
273
-		. "</div>\n";
257
+    if ((!$liste = liste_plugin_files(_DIR_PLUGINS_DIST))) {
258
+        return '';
259
+    }
260
+
261
+    $afficher = charger_fonction('afficher_liste', 'plugins');
262
+    $liste = $afficher(self(), $liste, [], $actifs, _DIR_PLUGINS_DIST);
263
+
264
+    return
265
+        "<div id='plugins_dist'>"
266
+        . debut_cadre_trait_couleur('', true, '', _T('plugins_liste_dist'), 'liste_plugins_dist')
267
+        . '<p>'
268
+        . _T('plugin_info_plugins_dist_1', ['plugins_dist' => joli_repertoire(_DIR_PLUGINS_DIST)])
269
+        . '<br />' . _T('plugin_info_plugins_dist_2')
270
+        . '</p>'
271
+        . $liste
272
+        . fin_cadre_trait_couleur()
273
+        . "</div>\n";
274 274
 }
275 275
 
276 276
 /**
@@ -282,19 +282,19 @@  discard block
 block discarded – undo
282 282
  */
283 283
 function afficher_librairies() {
284 284
 
285
-	if (!$libs = liste_librairies()) {
286
-		return '';
287
-	}
288
-	ksort($libs);
289
-	$res = debut_cadre_enfonce('', true, '', _T('plugin_librairies_installees'));
290
-	$res .= '<dl>';
291
-	foreach ($libs as $lib => $rep) {
292
-		$res .= "<dt>$lib</dt><dd>" . joli_repertoire($rep) . "</dd>\n";
293
-	}
294
-	$res .= '</dl>';
295
-	$res .= fin_cadre_enfonce();
296
-
297
-	return $res;
285
+    if (!$libs = liste_librairies()) {
286
+        return '';
287
+    }
288
+    ksort($libs);
289
+    $res = debut_cadre_enfonce('', true, '', _T('plugin_librairies_installees'));
290
+    $res .= '<dl>';
291
+    foreach ($libs as $lib => $rep) {
292
+        $res .= "<dt>$lib</dt><dd>" . joli_repertoire($rep) . "</dd>\n";
293
+    }
294
+    $res .= '</dl>';
295
+    $res .= fin_cadre_enfonce();
296
+
297
+    return $res;
298 298
 }
299 299
 
300 300
 
@@ -305,22 +305,22 @@  discard block
 block discarded – undo
305 305
  *     Tableau (nom de la lib => repertoire , ...)
306 306
  */
307 307
 function liste_librairies() {
308
-	$libs = [];
309
-	foreach (array_reverse(creer_chemin()) as $d) {
310
-		if (
311
-			is_dir($dir = $d . 'lib/')
312
-			and $t = opendir($dir)
313
-		) {
314
-			while (($f = readdir($t)) !== false) {
315
-				if (
316
-					$f[0] != '.'
317
-					and is_dir("$dir/$f")
318
-				) {
319
-					$libs[$f] = $dir;
320
-				}
321
-			}
322
-		}
323
-	}
324
-
325
-	return $libs;
308
+    $libs = [];
309
+    foreach (array_reverse(creer_chemin()) as $d) {
310
+        if (
311
+            is_dir($dir = $d . 'lib/')
312
+            and $t = opendir($dir)
313
+        ) {
314
+            while (($f = readdir($t)) !== false) {
315
+                if (
316
+                    $f[0] != '.'
317
+                    and is_dir("$dir/$f")
318
+                ) {
319
+                    $libs[$f] = $dir;
320
+                }
321
+            }
322
+        }
323
+    }
324
+
325
+    return $libs;
326 326
 }
Please login to merge, or discard this patch.
ecrire/inc/log.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -11,109 +11,109 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 function inc_log_dist($message, $logname = null, $logdir = null, $logsuf = null) {
18
-	static $test_repertoire = [];
19
-	static $compteur = [];
20
-	static $debugverb = ''; // pour ne pas le recalculer au reappel
21
-
22
-	if (is_null($logname) or !is_string($logname)) {
23
-		$logname = defined('_FILE_LOG') ? _FILE_LOG : 'spip';
24
-	}
25
-	if (!isset($compteur[$logname])) {
26
-		$compteur[$logname] = 0;
27
-	}
28
-	if (
29
-		$logname != 'maj'
30
-		and defined('_MAX_LOG')
31
-		and (
32
-			$compteur[$logname]++ > _MAX_LOG
33
-			or !$GLOBALS['nombre_de_logs']
34
-			or !$GLOBALS['taille_des_logs']
35
-		)
36
-	) {
37
-		return;
38
-	}
39
-
40
-	// si spip_log() est appelé dans mes_options, toutes les constantes n'ont pas été définies
41
-	$logfile =
42
-		($logdir ?? (defined('_DIR_LOG') ? _DIR_LOG : _DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES))
43
-		. $logname
44
-		. ($logsuf ?? (defined('_FILE_LOG_SUFFIX') ? _FILE_LOG_SUFFIX : '.log'));
45
-
46
-	if (!isset($test_repertoire[$d = dirname($logfile)])) {
47
-		$test_repertoire[$d] = false; // eviter une recursivite en cas d'erreur de sous_repertoire
48
-		$test_repertoire[$d] = (@is_dir($d) ? true : (function_exists('sous_repertoire') ? sous_repertoire(
49
-			$d,
50
-			'',
51
-			false,
52
-			true
53
-		) : false));
54
-	}
55
-
56
-	// Si le repertoire défini n'existe pas, poser dans tmp/
57
-	if (!$test_repertoire[$d]) {
58
-		$logfile = _DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES . $logname . '.log';
59
-	}
60
-
61
-	$rotate = 0;
62
-	$pid = '(pid ' . @getmypid() . ')';
63
-
64
-	// accepter spip_log( Array )
65
-	if (!is_string($message)) {
66
-		$message = var_export($message, true);
67
-	}
68
-
69
-	if (!$debugverb and defined('_LOG_FILELINE') and _LOG_FILELINE) {
70
-		$debug = debug_backtrace();
71
-		$l = $debug[1]['line'];
72
-		$fi = $debug[1]['file'];
73
-		if (strncmp($fi, _ROOT_RACINE, strlen(_ROOT_RACINE)) == 0) {
74
-			$fi = substr($fi, strlen(_ROOT_RACINE));
75
-		}
76
-		$fu = $debug[2]['function'] ?? '';
77
-		$debugverb = "$fi:L$l:$fu" . '():';
78
-	}
79
-
80
-	$m = date('Y-m-d H:i:s') . ' ' . ($GLOBALS['ip'] ?? '') . ' ' . $pid . ' '
81
-		//distinguer les logs prives et publics dans les grep
82
-		. $debugverb
83
-		. (test_espace_prive() ? ':Pri:' : ':Pub:')
84
-		. preg_replace("/\n*$/", "\n", $message);
85
-
86
-
87
-	if (
88
-		@is_readable($logfile)
89
-		and (!$s = @filesize($logfile) or $s > $GLOBALS['taille_des_logs'] * 1024)
90
-	) {
91
-		$rotate = $GLOBALS['nombre_de_logs'];
92
-		$m .= "[-- rotate --]\n";
93
-	}
94
-
95
-	$f = @fopen($logfile, 'ab');
96
-	if ($f) {
97
-		fputs($f, (defined('_LOG_BRUT') and _LOG_BRUT) ? $m : str_replace('<', '&lt;', $m));
98
-		fclose($f);
99
-	}
100
-
101
-	if (
102
-		$rotate-- > 0
103
-		and function_exists('spip_unlink')
104
-	) {
105
-		spip_unlink($logfile . '.' . $rotate);
106
-		while ($rotate--) {
107
-			@rename($logfile . ($rotate ? '.' . $rotate : ''), $logfile . '.' . ($rotate + 1));
108
-		}
109
-	}
110
-
111
-	// Dupliquer les erreurs specifiques dans le log general
112
-	if (
113
-		defined('_FILE_LOG')
114
-		and ($logname !== _FILE_LOG)
115
-	) {
116
-		inc_log_dist($logname == 'maj' ? 'cf maj.log' : $message);
117
-	}
118
-	$debugverb = '';
18
+    static $test_repertoire = [];
19
+    static $compteur = [];
20
+    static $debugverb = ''; // pour ne pas le recalculer au reappel
21
+
22
+    if (is_null($logname) or !is_string($logname)) {
23
+        $logname = defined('_FILE_LOG') ? _FILE_LOG : 'spip';
24
+    }
25
+    if (!isset($compteur[$logname])) {
26
+        $compteur[$logname] = 0;
27
+    }
28
+    if (
29
+        $logname != 'maj'
30
+        and defined('_MAX_LOG')
31
+        and (
32
+            $compteur[$logname]++ > _MAX_LOG
33
+            or !$GLOBALS['nombre_de_logs']
34
+            or !$GLOBALS['taille_des_logs']
35
+        )
36
+    ) {
37
+        return;
38
+    }
39
+
40
+    // si spip_log() est appelé dans mes_options, toutes les constantes n'ont pas été définies
41
+    $logfile =
42
+        ($logdir ?? (defined('_DIR_LOG') ? _DIR_LOG : _DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES))
43
+        . $logname
44
+        . ($logsuf ?? (defined('_FILE_LOG_SUFFIX') ? _FILE_LOG_SUFFIX : '.log'));
45
+
46
+    if (!isset($test_repertoire[$d = dirname($logfile)])) {
47
+        $test_repertoire[$d] = false; // eviter une recursivite en cas d'erreur de sous_repertoire
48
+        $test_repertoire[$d] = (@is_dir($d) ? true : (function_exists('sous_repertoire') ? sous_repertoire(
49
+            $d,
50
+            '',
51
+            false,
52
+            true
53
+        ) : false));
54
+    }
55
+
56
+    // Si le repertoire défini n'existe pas, poser dans tmp/
57
+    if (!$test_repertoire[$d]) {
58
+        $logfile = _DIR_RACINE . _NOM_TEMPORAIRES_INACCESSIBLES . $logname . '.log';
59
+    }
60
+
61
+    $rotate = 0;
62
+    $pid = '(pid ' . @getmypid() . ')';
63
+
64
+    // accepter spip_log( Array )
65
+    if (!is_string($message)) {
66
+        $message = var_export($message, true);
67
+    }
68
+
69
+    if (!$debugverb and defined('_LOG_FILELINE') and _LOG_FILELINE) {
70
+        $debug = debug_backtrace();
71
+        $l = $debug[1]['line'];
72
+        $fi = $debug[1]['file'];
73
+        if (strncmp($fi, _ROOT_RACINE, strlen(_ROOT_RACINE)) == 0) {
74
+            $fi = substr($fi, strlen(_ROOT_RACINE));
75
+        }
76
+        $fu = $debug[2]['function'] ?? '';
77
+        $debugverb = "$fi:L$l:$fu" . '():';
78
+    }
79
+
80
+    $m = date('Y-m-d H:i:s') . ' ' . ($GLOBALS['ip'] ?? '') . ' ' . $pid . ' '
81
+        //distinguer les logs prives et publics dans les grep
82
+        . $debugverb
83
+        . (test_espace_prive() ? ':Pri:' : ':Pub:')
84
+        . preg_replace("/\n*$/", "\n", $message);
85
+
86
+
87
+    if (
88
+        @is_readable($logfile)
89
+        and (!$s = @filesize($logfile) or $s > $GLOBALS['taille_des_logs'] * 1024)
90
+    ) {
91
+        $rotate = $GLOBALS['nombre_de_logs'];
92
+        $m .= "[-- rotate --]\n";
93
+    }
94
+
95
+    $f = @fopen($logfile, 'ab');
96
+    if ($f) {
97
+        fputs($f, (defined('_LOG_BRUT') and _LOG_BRUT) ? $m : str_replace('<', '&lt;', $m));
98
+        fclose($f);
99
+    }
100
+
101
+    if (
102
+        $rotate-- > 0
103
+        and function_exists('spip_unlink')
104
+    ) {
105
+        spip_unlink($logfile . '.' . $rotate);
106
+        while ($rotate--) {
107
+            @rename($logfile . ($rotate ? '.' . $rotate : ''), $logfile . '.' . ($rotate + 1));
108
+        }
109
+    }
110
+
111
+    // Dupliquer les erreurs specifiques dans le log general
112
+    if (
113
+        defined('_FILE_LOG')
114
+        and ($logname !== _FILE_LOG)
115
+    ) {
116
+        inc_log_dist($logname == 'maj' ? 'cf maj.log' : $message);
117
+    }
118
+    $debugverb = '';
119 119
 }
Please login to merge, or discard this patch.
ecrire/inc/config.php 1 patch
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
  * @return void
29 29
  */
30 30
 function inc_config_dist() {
31
-	actualise_metas(liste_metas());
31
+    actualise_metas(liste_metas());
32 32
 }
33 33
 
34 34
 /**
@@ -45,34 +45,34 @@  discard block
 block discarded – undo
45 45
  *     Liste (table, casier, sous_casier)
46 46
  */
47 47
 function expliquer_config($cfg) {
48
-	// par defaut, sur la table des meta
49
-	$table = 'meta';
50
-	$casier = null;
51
-	$sous_casier = [];
52
-	$cfg = explode('/', $cfg);
53
-
54
-	// si le premier argument est vide, c'est une syntaxe /table/ ou un appel vide ''
55
-	if (!reset($cfg) and count($cfg) > 1) {
56
-		array_shift($cfg);
57
-		$table = array_shift($cfg);
58
-		if (!isset($GLOBALS[$table])) {
59
-			lire_metas($table);
60
-		}
61
-	}
62
-
63
-	// si on a demande #CONFIG{/meta,'',0}
64
-	if (count($cfg)) {
65
-		// pas sur un appel vide ''
66
-		if ('' !== ($c = array_shift($cfg))) {
67
-			$casier = $c;
68
-		}
69
-	}
70
-
71
-	if (count($cfg)) {
72
-		$sous_casier = $cfg;
73
-	}
74
-
75
-	return [$table, $casier, $sous_casier];
48
+    // par defaut, sur la table des meta
49
+    $table = 'meta';
50
+    $casier = null;
51
+    $sous_casier = [];
52
+    $cfg = explode('/', $cfg);
53
+
54
+    // si le premier argument est vide, c'est une syntaxe /table/ ou un appel vide ''
55
+    if (!reset($cfg) and count($cfg) > 1) {
56
+        array_shift($cfg);
57
+        $table = array_shift($cfg);
58
+        if (!isset($GLOBALS[$table])) {
59
+            lire_metas($table);
60
+        }
61
+    }
62
+
63
+    // si on a demande #CONFIG{/meta,'',0}
64
+    if (count($cfg)) {
65
+        // pas sur un appel vide ''
66
+        if ('' !== ($c = array_shift($cfg))) {
67
+            $casier = $c;
68
+        }
69
+    }
70
+
71
+    if (count($cfg)) {
72
+        $sous_casier = $cfg;
73
+    }
74
+
75
+    return [$table, $casier, $sous_casier];
76 76
 }
77 77
 
78 78
 /**
@@ -100,65 +100,65 @@  discard block
 block discarded – undo
100 100
  *    Contenu de la configuration obtenue
101 101
  */
102 102
 function lire_config($cfg = '', $def = null, $unserialize = true) {
103
-	// lire le stockage sous la forme /table/valeur
104
-	// ou valeur qui est en fait implicitement /meta/valeur
105
-	// ou casier/valeur qui est en fait implicitement /meta/casier/valeur
106
-
107
-	// traiter en priorite le cas simple et frequent
108
-	// de lecture direct $GLOBALS['meta']['truc'], si $cfg ne contient ni / ni :
109
-	if ($cfg and strpbrk($cfg, '/:') === false) {
110
-		$r = isset($GLOBALS['meta'][$cfg]) ?
111
-			((!$unserialize
112
-				// ne pas essayer de deserialiser autre chose qu'une chaine
113
-				or !is_string($GLOBALS['meta'][$cfg])
114
-				// ne pas essayer de deserialiser si ce n'est visiblement pas une chaine serializee
115
-				or strpos($GLOBALS['meta'][$cfg], ':') === false
116
-				or ($t = @unserialize($GLOBALS['meta'][$cfg])) === false) ? $GLOBALS['meta'][$cfg] : $t)
117
-			: $def;
118
-
119
-		return $r;
120
-	}
121
-
122
-	// Brancher sur methodes externes si besoin
123
-	if ($cfg and $p = strpos($cfg, '::')) {
124
-		$methode = substr($cfg, 0, $p);
125
-		$lire_config = charger_fonction($methode, 'lire_config');
126
-
127
-		return $lire_config(substr($cfg, $p + 2), $def, $unserialize);
128
-	}
129
-
130
-	[$table, $casier, $sous_casier] = expliquer_config($cfg);
131
-
132
-	if (!isset($GLOBALS[$table])) {
133
-		return $def;
134
-	}
135
-
136
-	$r = $GLOBALS[$table];
137
-
138
-	// si on a demande #CONFIG{/meta,'',0}
139
-	if (!$casier) {
140
-		return $unserialize ? $r : serialize($r);
141
-	}
142
-
143
-	// casier principal :
144
-	// le deserializer si demande
145
-	// ou si on a besoin
146
-	// d'un sous casier
147
-	$r = $r[$casier] ?? null;
148
-	if (($unserialize or is_countable($sous_casier) ? count($sous_casier) : 0) and $r and is_string($r)) {
149
-		$r = (($t = @unserialize($r)) === false ? $r : $t);
150
-	}
151
-
152
-	// aller chercher le sous_casier
153
-	while (!is_null($r) and $casier = array_shift($sous_casier)) {
154
-		$r = $r[$casier] ?? null;
155
-	}
156
-
157
-	if (is_null($r)) {
158
-		return $def;
159
-	}
160
-
161
-	return $r;
103
+    // lire le stockage sous la forme /table/valeur
104
+    // ou valeur qui est en fait implicitement /meta/valeur
105
+    // ou casier/valeur qui est en fait implicitement /meta/casier/valeur
106
+
107
+    // traiter en priorite le cas simple et frequent
108
+    // de lecture direct $GLOBALS['meta']['truc'], si $cfg ne contient ni / ni :
109
+    if ($cfg and strpbrk($cfg, '/:') === false) {
110
+        $r = isset($GLOBALS['meta'][$cfg]) ?
111
+            ((!$unserialize
112
+                // ne pas essayer de deserialiser autre chose qu'une chaine
113
+                or !is_string($GLOBALS['meta'][$cfg])
114
+                // ne pas essayer de deserialiser si ce n'est visiblement pas une chaine serializee
115
+                or strpos($GLOBALS['meta'][$cfg], ':') === false
116
+                or ($t = @unserialize($GLOBALS['meta'][$cfg])) === false) ? $GLOBALS['meta'][$cfg] : $t)
117
+            : $def;
118
+
119
+        return $r;
120
+    }
121
+
122
+    // Brancher sur methodes externes si besoin
123
+    if ($cfg and $p = strpos($cfg, '::')) {
124
+        $methode = substr($cfg, 0, $p);
125
+        $lire_config = charger_fonction($methode, 'lire_config');
126
+
127
+        return $lire_config(substr($cfg, $p + 2), $def, $unserialize);
128
+    }
129
+
130
+    [$table, $casier, $sous_casier] = expliquer_config($cfg);
131
+
132
+    if (!isset($GLOBALS[$table])) {
133
+        return $def;
134
+    }
135
+
136
+    $r = $GLOBALS[$table];
137
+
138
+    // si on a demande #CONFIG{/meta,'',0}
139
+    if (!$casier) {
140
+        return $unserialize ? $r : serialize($r);
141
+    }
142
+
143
+    // casier principal :
144
+    // le deserializer si demande
145
+    // ou si on a besoin
146
+    // d'un sous casier
147
+    $r = $r[$casier] ?? null;
148
+    if (($unserialize or is_countable($sous_casier) ? count($sous_casier) : 0) and $r and is_string($r)) {
149
+        $r = (($t = @unserialize($r)) === false ? $r : $t);
150
+    }
151
+
152
+    // aller chercher le sous_casier
153
+    while (!is_null($r) and $casier = array_shift($sous_casier)) {
154
+        $r = $r[$casier] ?? null;
155
+    }
156
+
157
+    if (is_null($r)) {
158
+        return $def;
159
+    }
160
+
161
+    return $r;
162 162
 }
163 163
 
164 164
 /**
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
  * @return mixed
173 173
  */
174 174
 function lire_config_metapack_dist($cfg = '', $def = null, $unserialize = true) {
175
-	return lire_config($cfg, $def, $unserialize);
175
+    return lire_config($cfg, $def, $unserialize);
176 176
 }
177 177
 
178 178
 
@@ -184,144 +184,144 @@  discard block
 block discarded – undo
184 184
  * @return bool
185 185
  */
186 186
 function ecrire_config($cfg, $store) {
187
-	// Brancher sur methodes externes si besoin
188
-	if ($cfg and $p = strpos($cfg, '::')) {
189
-		$methode = substr($cfg, 0, $p);
190
-		$ecrire_config = charger_fonction($methode, 'ecrire_config');
191
-
192
-		return $ecrire_config(substr($cfg, $p + 2), $store);
193
-	}
194
-
195
-	[$table, $casier, $sous_casier] = expliquer_config($cfg);
196
-	// il faut au moins un casier pour ecrire
197
-	if (!$casier) {
198
-		return false;
199
-	}
200
-
201
-	// trouvons ou creons le pointeur sur le casier
202
-	$st = $GLOBALS[$table][$casier] ?? null;
203
-	if (!is_array($st) and ($sous_casier or is_array($store))) {
204
-		if ($st === null) {
205
-			// ne rien creer si c'est une demande d'effacement
206
-			if ($store === null) {
207
-				return false;
208
-			}
209
-			$st = [];
210
-		} else {
211
-			$st = unserialize($st);
212
-			if ($st === false) {
213
-				// ne rien creer si c'est une demande d'effacement
214
-				if ($store === null) {
215
-					return false;
216
-				}
217
-				$st = [];
218
-			}
219
-		}
220
-	}
221
-
222
-	$has_planes = false;
223
-	// si on a affaire a un sous caiser
224
-	// il faut ecrire au bon endroit sans perdre les autres sous casier freres
225
-	if ($c = $sous_casier) {
226
-		$sc = &$st;
227
-		$pointeurs = [];
228
-		while (is_countable($c) ? count($c) : 0 and $cc = array_shift($c)) {
229
-			// creer l'entree si elle n'existe pas
230
-			if (!isset($sc[$cc])) {
231
-				// si on essaye d'effacer une config qui n'existe pas
232
-				// ne rien creer mais sortir
233
-				if (is_null($store)) {
234
-					return false;
235
-				}
236
-				$sc[$cc] = [];
237
-			}
238
-			$pointeurs[$cc] = &$sc;
239
-			$sc = &$sc[$cc];
240
-		}
241
-
242
-		// si c'est une demande d'effacement
243
-		if (is_null($store)) {
244
-			$c = $sous_casier;
245
-			$sous = array_pop($c);
246
-			// effacer, et remonter pour effacer les parents vides
247
-			do {
248
-				unset($pointeurs[$sous][$sous]);
249
-			} while ($sous = array_pop($c) and !(is_countable($pointeurs[$sous][$sous]) ? count($pointeurs[$sous][$sous]) : 0));
250
-
251
-			// si on a vide tous les sous casiers,
252
-			// et que le casier est vide
253
-			// vider aussi la meta
254
-			if (!$sous and !(is_countable($st) ? count($st) : 0)) {
255
-				$st = null;
256
-			}
257
-		} // dans tous les autres cas, on ecrase
258
-		else {
259
-			if (
260
-					defined('_MYSQL_NOPLANES')
261
-				and _MYSQL_NOPLANES
262
-				and !empty($GLOBALS['meta']['charset_sql_connexion'])
263
-				and $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
264
-			) {
265
-				// detecter si la valeur qu'on veut ecrire a des planes
266
-				// @see utf8_noplanes
267
-				$serialized_store = (is_string($store) ? $store : serialize($store));
268
-				// un preg_match rapide pour voir si ca vaut le coup de lancer utf8_noplanes
269
-				if (preg_match(',[\xF0-\xF4],ms', $serialized_store)) {
270
-					if (!function_exists('utf8_noplanes')) {
271
-						include_spip('inc/charsets');
272
-					}
273
-					if ($serialized_store !== utf8_noplanes($serialized_store)) {
274
-						$has_planes = true;
275
-					}
276
-				}
277
-			}
278
-
279
-			$sc = $store;
280
-		}
281
-
282
-		// Maintenant que $st est modifiee
283
-		// reprenons la comme valeur a stocker dans le casier principal
284
-		$store = $st;
285
-	}
286
-
287
-	if (is_null($store)) {
288
-		if (is_null($st) and !$sous_casier) {
289
-			return false;
290
-		} // la config n'existait deja pas !
291
-		effacer_meta($casier, $table);
292
-		supprimer_table_meta($table); // supprimons la table (si elle est bien vide)
293
-	} // les meta ne peuvent etre que des chaines : il faut serializer le reste
294
-	else {
295
-		if (!isset($GLOBALS[$table])) {
296
-			installer_table_meta($table);
297
-		}
298
-		// si ce n'est pas une chaine
299
-		// il faut serializer
300
-		if (!is_string($store)) {
301
-			$serialized_store = serialize($store);
302
-			ecrire_meta($casier, $serialized_store, null, $table);
303
-			// et dans ce cas il faut verifier que l'ecriture en base a bien eu lieu a l'identique si il y a des planes dans la chaine
304
-			// car sinon ca casse le serialize PHP - par exemple si on est en mysql utf8 (non mb4)
305
-			if ($has_planes) {
306
-				$check_store = sql_getfetsel('valeur', 'spip_' . $table, 'nom=' . sql_quote($casier));
307
-				if ($check_store !== $serialized_store) {
308
-					array_walk_recursive($store, function (&$value, $key) {
309
-						if (is_string($value)) {
310
-							$value = utf8_noplanes($value);
311
-						}
312
-					});
313
-					$serialized_store = serialize($store);
314
-					ecrire_meta($casier, $serialized_store, null, $table);
315
-				}
316
-			}
317
-		}
318
-		else {
319
-			ecrire_meta($casier, $store, null, $table);
320
-		}
321
-	}
322
-
323
-	// verifier que lire_config($cfg)==$store ?
324
-	return true;
187
+    // Brancher sur methodes externes si besoin
188
+    if ($cfg and $p = strpos($cfg, '::')) {
189
+        $methode = substr($cfg, 0, $p);
190
+        $ecrire_config = charger_fonction($methode, 'ecrire_config');
191
+
192
+        return $ecrire_config(substr($cfg, $p + 2), $store);
193
+    }
194
+
195
+    [$table, $casier, $sous_casier] = expliquer_config($cfg);
196
+    // il faut au moins un casier pour ecrire
197
+    if (!$casier) {
198
+        return false;
199
+    }
200
+
201
+    // trouvons ou creons le pointeur sur le casier
202
+    $st = $GLOBALS[$table][$casier] ?? null;
203
+    if (!is_array($st) and ($sous_casier or is_array($store))) {
204
+        if ($st === null) {
205
+            // ne rien creer si c'est une demande d'effacement
206
+            if ($store === null) {
207
+                return false;
208
+            }
209
+            $st = [];
210
+        } else {
211
+            $st = unserialize($st);
212
+            if ($st === false) {
213
+                // ne rien creer si c'est une demande d'effacement
214
+                if ($store === null) {
215
+                    return false;
216
+                }
217
+                $st = [];
218
+            }
219
+        }
220
+    }
221
+
222
+    $has_planes = false;
223
+    // si on a affaire a un sous caiser
224
+    // il faut ecrire au bon endroit sans perdre les autres sous casier freres
225
+    if ($c = $sous_casier) {
226
+        $sc = &$st;
227
+        $pointeurs = [];
228
+        while (is_countable($c) ? count($c) : 0 and $cc = array_shift($c)) {
229
+            // creer l'entree si elle n'existe pas
230
+            if (!isset($sc[$cc])) {
231
+                // si on essaye d'effacer une config qui n'existe pas
232
+                // ne rien creer mais sortir
233
+                if (is_null($store)) {
234
+                    return false;
235
+                }
236
+                $sc[$cc] = [];
237
+            }
238
+            $pointeurs[$cc] = &$sc;
239
+            $sc = &$sc[$cc];
240
+        }
241
+
242
+        // si c'est une demande d'effacement
243
+        if (is_null($store)) {
244
+            $c = $sous_casier;
245
+            $sous = array_pop($c);
246
+            // effacer, et remonter pour effacer les parents vides
247
+            do {
248
+                unset($pointeurs[$sous][$sous]);
249
+            } while ($sous = array_pop($c) and !(is_countable($pointeurs[$sous][$sous]) ? count($pointeurs[$sous][$sous]) : 0));
250
+
251
+            // si on a vide tous les sous casiers,
252
+            // et que le casier est vide
253
+            // vider aussi la meta
254
+            if (!$sous and !(is_countable($st) ? count($st) : 0)) {
255
+                $st = null;
256
+            }
257
+        } // dans tous les autres cas, on ecrase
258
+        else {
259
+            if (
260
+                    defined('_MYSQL_NOPLANES')
261
+                and _MYSQL_NOPLANES
262
+                and !empty($GLOBALS['meta']['charset_sql_connexion'])
263
+                and $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
264
+            ) {
265
+                // detecter si la valeur qu'on veut ecrire a des planes
266
+                // @see utf8_noplanes
267
+                $serialized_store = (is_string($store) ? $store : serialize($store));
268
+                // un preg_match rapide pour voir si ca vaut le coup de lancer utf8_noplanes
269
+                if (preg_match(',[\xF0-\xF4],ms', $serialized_store)) {
270
+                    if (!function_exists('utf8_noplanes')) {
271
+                        include_spip('inc/charsets');
272
+                    }
273
+                    if ($serialized_store !== utf8_noplanes($serialized_store)) {
274
+                        $has_planes = true;
275
+                    }
276
+                }
277
+            }
278
+
279
+            $sc = $store;
280
+        }
281
+
282
+        // Maintenant que $st est modifiee
283
+        // reprenons la comme valeur a stocker dans le casier principal
284
+        $store = $st;
285
+    }
286
+
287
+    if (is_null($store)) {
288
+        if (is_null($st) and !$sous_casier) {
289
+            return false;
290
+        } // la config n'existait deja pas !
291
+        effacer_meta($casier, $table);
292
+        supprimer_table_meta($table); // supprimons la table (si elle est bien vide)
293
+    } // les meta ne peuvent etre que des chaines : il faut serializer le reste
294
+    else {
295
+        if (!isset($GLOBALS[$table])) {
296
+            installer_table_meta($table);
297
+        }
298
+        // si ce n'est pas une chaine
299
+        // il faut serializer
300
+        if (!is_string($store)) {
301
+            $serialized_store = serialize($store);
302
+            ecrire_meta($casier, $serialized_store, null, $table);
303
+            // et dans ce cas il faut verifier que l'ecriture en base a bien eu lieu a l'identique si il y a des planes dans la chaine
304
+            // car sinon ca casse le serialize PHP - par exemple si on est en mysql utf8 (non mb4)
305
+            if ($has_planes) {
306
+                $check_store = sql_getfetsel('valeur', 'spip_' . $table, 'nom=' . sql_quote($casier));
307
+                if ($check_store !== $serialized_store) {
308
+                    array_walk_recursive($store, function (&$value, $key) {
309
+                        if (is_string($value)) {
310
+                            $value = utf8_noplanes($value);
311
+                        }
312
+                    });
313
+                    $serialized_store = serialize($store);
314
+                    ecrire_meta($casier, $serialized_store, null, $table);
315
+                }
316
+            }
317
+        }
318
+        else {
319
+            ecrire_meta($casier, $store, null, $table);
320
+        }
321
+    }
322
+
323
+    // verifier que lire_config($cfg)==$store ?
324
+    return true;
325 325
 }
326 326
 
327 327
 
@@ -335,14 +335,14 @@  discard block
 block discarded – undo
335 335
  * @return bool
336 336
  */
337 337
 function ecrire_config_metapack_dist($cfg, $store) {
338
-	// cas particulier en metapack::
339
-	// si on ecrit une chaine deja serializee, il faut la reserializer pour la rendre
340
-	// intacte en sortie ...
341
-	if (is_string($store) and strpos($store, ':') and unserialize($store)) {
342
-		$store = serialize($store);
343
-	}
344
-
345
-	return ecrire_config($cfg, $store);
338
+    // cas particulier en metapack::
339
+    // si on ecrit une chaine deja serializee, il faut la reserializer pour la rendre
340
+    // intacte en sortie ...
341
+    if (is_string($store) and strpos($store, ':') and unserialize($store)) {
342
+        $store = serialize($store);
343
+    }
344
+
345
+    return ecrire_config($cfg, $store);
346 346
 }
347 347
 
348 348
 /**
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
  * @return bool
353 353
  */
354 354
 function effacer_config($cfg) {
355
-	ecrire_config($cfg, null);
355
+    ecrire_config($cfg, null);
356 356
 
357
-	return true;
357
+    return true;
358 358
 }
359 359
 
360 360
 /**
@@ -371,58 +371,58 @@  discard block
 block discarded – undo
371 371
  *    Couples nom de la `meta` => valeur par défaut
372 372
  */
373 373
 function liste_metas() {
374
-	return pipeline('configurer_liste_metas', [
375
-		'nom_site' => _T('info_mon_site_spip'),
376
-		'slogan_site' => '',
377
-		'adresse_site' => preg_replace(',/$,', '', url_de_base()),
378
-		'descriptif_site' => '',
379
-		'activer_logos' => 'oui',
380
-		'activer_logos_survol' => 'non',
381
-		'articles_surtitre' => 'non',
382
-		'articles_soustitre' => 'non',
383
-		'articles_descriptif' => 'non',
384
-		'articles_chapeau' => 'non',
385
-		'articles_texte' => 'oui',
386
-		'articles_ps' => 'non',
387
-		'articles_redac' => 'non',
388
-		'post_dates' => 'non',
389
-		'articles_urlref' => 'non',
390
-		'articles_redirection' => 'non',
391
-		'creer_preview' => 'non',
392
-		'taille_preview' => 150,
393
-		'articles_modif' => 'non',
394
-
395
-		'rubriques_descriptif' => 'non',
396
-		'rubriques_texte' => 'oui',
397
-
398
-		'accepter_inscriptions' => 'non',
399
-		'accepter_visiteurs' => 'non',
400
-		'prevenir_auteurs' => 'non',
401
-		'suivi_edito' => 'non',
402
-		'adresse_suivi' => '',
403
-		'adresse_suivi_inscription' => '',
404
-		'adresse_neuf' => '',
405
-		'jours_neuf' => '',
406
-		'quoi_de_neuf' => 'non',
407
-		'preview' => ',0minirezo,1comite,',
408
-
409
-		'syndication_integrale' => 'oui',
410
-		'charset' => _DEFAULT_CHARSET,
411
-		'dir_img' => substr(_DIR_IMG, strlen(_DIR_RACINE)),
412
-
413
-		'multi_rubriques' => 'non',
414
-		'multi_secteurs' => 'non',
415
-		'gerer_trad' => 'non',
416
-		'langues_multilingue' => '',
417
-
418
-		'version_html_max' => 'html4',
419
-
420
-		'type_urls' => 'page',
421
-
422
-		'email_envoi' => '',
423
-		'email_webmaster' => '',
424
-		'auto_compress_http' => 'non',
425
-	]);
374
+    return pipeline('configurer_liste_metas', [
375
+        'nom_site' => _T('info_mon_site_spip'),
376
+        'slogan_site' => '',
377
+        'adresse_site' => preg_replace(',/$,', '', url_de_base()),
378
+        'descriptif_site' => '',
379
+        'activer_logos' => 'oui',
380
+        'activer_logos_survol' => 'non',
381
+        'articles_surtitre' => 'non',
382
+        'articles_soustitre' => 'non',
383
+        'articles_descriptif' => 'non',
384
+        'articles_chapeau' => 'non',
385
+        'articles_texte' => 'oui',
386
+        'articles_ps' => 'non',
387
+        'articles_redac' => 'non',
388
+        'post_dates' => 'non',
389
+        'articles_urlref' => 'non',
390
+        'articles_redirection' => 'non',
391
+        'creer_preview' => 'non',
392
+        'taille_preview' => 150,
393
+        'articles_modif' => 'non',
394
+
395
+        'rubriques_descriptif' => 'non',
396
+        'rubriques_texte' => 'oui',
397
+
398
+        'accepter_inscriptions' => 'non',
399
+        'accepter_visiteurs' => 'non',
400
+        'prevenir_auteurs' => 'non',
401
+        'suivi_edito' => 'non',
402
+        'adresse_suivi' => '',
403
+        'adresse_suivi_inscription' => '',
404
+        'adresse_neuf' => '',
405
+        'jours_neuf' => '',
406
+        'quoi_de_neuf' => 'non',
407
+        'preview' => ',0minirezo,1comite,',
408
+
409
+        'syndication_integrale' => 'oui',
410
+        'charset' => _DEFAULT_CHARSET,
411
+        'dir_img' => substr(_DIR_IMG, strlen(_DIR_RACINE)),
412
+
413
+        'multi_rubriques' => 'non',
414
+        'multi_secteurs' => 'non',
415
+        'gerer_trad' => 'non',
416
+        'langues_multilingue' => '',
417
+
418
+        'version_html_max' => 'html4',
419
+
420
+        'type_urls' => 'page',
421
+
422
+        'email_envoi' => '',
423
+        'email_webmaster' => '',
424
+        'auto_compress_http' => 'non',
425
+    ]);
426 426
 }
427 427
 
428 428
 /**
@@ -433,43 +433,43 @@  discard block
 block discarded – undo
433 433
  * @return void
434 434
  */
435 435
 function actualise_metas($liste_meta) {
436
-	$meta_serveur =
437
-		[
438
-			'version_installee',
439
-			'adresse_site',
440
-			'alea_ephemere_ancien',
441
-			'alea_ephemere',
442
-			'alea_ephemere_date',
443
-			'langue_site',
444
-			'langues_proposees',
445
-			'date_calcul_rubriques',
446
-			'derniere_modif',
447
-			'optimiser_table',
448
-			'drapeau_edition',
449
-			'creer_preview',
450
-			'taille_preview',
451
-			'creer_htpasswd',
452
-			'creer_htaccess',
453
-			'gd_formats_read',
454
-			'gd_formats',
455
-			'netpbm_formats',
456
-			'formats_graphiques',
457
-			'image_process',
458
-			'plugin_header',
459
-			'plugin'
460
-		];
461
-	// verifier le impt=non
462
-	sql_updateq('spip_meta', ['impt' => 'non'], sql_in('nom', $meta_serveur));
463
-
464
-	foreach ($liste_meta as $nom => $valeur) {
465
-		if (empty($GLOBALS['meta'][$nom])) {
466
-			ecrire_meta($nom, $valeur);
467
-		}
468
-	}
469
-
470
-	include_spip('inc/rubriques');
471
-	$langues = calculer_langues_utilisees();
472
-	ecrire_meta('langues_utilisees', $langues);
436
+    $meta_serveur =
437
+        [
438
+            'version_installee',
439
+            'adresse_site',
440
+            'alea_ephemere_ancien',
441
+            'alea_ephemere',
442
+            'alea_ephemere_date',
443
+            'langue_site',
444
+            'langues_proposees',
445
+            'date_calcul_rubriques',
446
+            'derniere_modif',
447
+            'optimiser_table',
448
+            'drapeau_edition',
449
+            'creer_preview',
450
+            'taille_preview',
451
+            'creer_htpasswd',
452
+            'creer_htaccess',
453
+            'gd_formats_read',
454
+            'gd_formats',
455
+            'netpbm_formats',
456
+            'formats_graphiques',
457
+            'image_process',
458
+            'plugin_header',
459
+            'plugin'
460
+        ];
461
+    // verifier le impt=non
462
+    sql_updateq('spip_meta', ['impt' => 'non'], sql_in('nom', $meta_serveur));
463
+
464
+    foreach ($liste_meta as $nom => $valeur) {
465
+        if (empty($GLOBALS['meta'][$nom])) {
466
+            ecrire_meta($nom, $valeur);
467
+        }
468
+    }
469
+
470
+    include_spip('inc/rubriques');
471
+    $langues = calculer_langues_utilisees();
472
+    ecrire_meta('langues_utilisees', $langues);
473 473
 }
474 474
 
475 475
 
@@ -491,18 +491,18 @@  discard block
 block discarded – undo
491 491
  */
492 492
 function appliquer_modifs_config($purger_skel = false) {
493 493
 
494
-	foreach (liste_metas() as $i => $v) {
495
-		if (($x = _request($i)) !== null) {
496
-			ecrire_meta($i, $x);
497
-		} elseif (!isset($GLOBALS['meta'][$i])) {
498
-			ecrire_meta($i, $v);
499
-		}
500
-	}
501
-
502
-	if ($purger_skel) {
503
-		include_spip('inc/invalideur');
504
-		purger_repertoire(_DIR_SKELS);
505
-	}
494
+    foreach (liste_metas() as $i => $v) {
495
+        if (($x = _request($i)) !== null) {
496
+            ecrire_meta($i, $x);
497
+        } elseif (!isset($GLOBALS['meta'][$i])) {
498
+            ecrire_meta($i, $v);
499
+        }
500
+    }
501
+
502
+    if ($purger_skel) {
503
+        include_spip('inc/invalideur');
504
+        purger_repertoire(_DIR_SKELS);
505
+    }
506 506
 }
507 507
 
508 508
 /**
@@ -513,21 +513,21 @@  discard block
 block discarded – undo
513 513
  * @return string
514 514
  */
515 515
 function appliquer_adresse_site($adresse_site) {
516
-	if ($adresse_site !== null) {
517
-		if (!strlen($adresse_site)) {
518
-			$GLOBALS['profondeur_url'] = _DIR_RESTREINT ? 0 : 1;
519
-			$adresse_site = url_de_base();
520
-		}
521
-		$adresse_site = preg_replace(',/?\s*$,', '', $adresse_site);
516
+    if ($adresse_site !== null) {
517
+        if (!strlen($adresse_site)) {
518
+            $GLOBALS['profondeur_url'] = _DIR_RESTREINT ? 0 : 1;
519
+            $adresse_site = url_de_base();
520
+        }
521
+        $adresse_site = preg_replace(',/?\s*$,', '', $adresse_site);
522 522
 
523
-		if (!tester_url_absolue($adresse_site)) {
524
-			$adresse_site = "http://$adresse_site";
525
-		}
523
+        if (!tester_url_absolue($adresse_site)) {
524
+            $adresse_site = "http://$adresse_site";
525
+        }
526 526
 
527
-		$adresse_site = entites_html($adresse_site);
527
+        $adresse_site = entites_html($adresse_site);
528 528
 
529
-		ecrire_meta('adresse_site', $adresse_site);
530
-	}
529
+        ecrire_meta('adresse_site', $adresse_site);
530
+    }
531 531
 
532
-	return $adresse_site;
532
+    return $adresse_site;
533 533
 }
Please login to merge, or discard this patch.
ecrire/inc/distant.php 1 patch
Indentation   +1085 added lines, -1085 removed lines patch added patch discarded remove patch
@@ -16,32 +16,32 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Distant
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
23
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
23
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24 24
 }
25 25
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
26
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
26
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
32
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
33 33
 }
34 34
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
35
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
35
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38 38
 define('_REGEXP_COPIE_LOCALE', ',' 	.
39
-	preg_replace(
40
-		'@^https?:@',
41
-		'https?:',
42
-		($GLOBALS['meta']['adresse_site'] ?? '')
43
-	)
44
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
39
+    preg_replace(
40
+        '@^https?:@',
41
+        'https?:',
42
+        ($GLOBALS['meta']['adresse_site'] ?? '')
43
+    )
44
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
45 45
 
46 46
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
47 47
 
@@ -70,107 +70,107 @@  discard block
 block discarded – undo
70 70
  */
71 71
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
72 72
 
73
-	// si c'est la protection de soi-meme, retourner le path
74
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
75
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
76
-
77
-		return @file_exists($source) ? $source : false;
78
-	}
79
-
80
-	if (is_null($local)) {
81
-		$local = fichier_copie_locale($source);
82
-	} else {
83
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
84
-			$local = substr($local, strlen(_DIR_RACINE));
85
-		}
86
-	}
87
-
88
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
89
-	// par exemple un fichier qui ne figure pas dans nos documents ;
90
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
91
-	if (!$local) {
92
-		return false;
93
-	}
94
-
95
-	$localrac = _DIR_RACINE . $local;
96
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
97
-
98
-	// test d'existence du fichier
99
-	if ($mode === 'test') {
100
-		return $t ? $local : '';
101
-	}
102
-
103
-	// sinon voir si on doit/peut le telecharger
104
-	if ($local === $source or !tester_url_absolue($source)) {
105
-		return $t ? $local : '';
106
-	}
107
-
108
-	if ($mode === 'modif' or !$t) {
109
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
110
-		// et des eventuelles recuperations concurantes
111
-		include_spip('inc/acces');
112
-		if (!$taille_max) {
113
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
114
-		}
115
-		$localrac_tmp = $localrac . '.tmp';
116
-		$res = recuperer_url(
117
-			$source,
118
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
119
-		);
120
-
121
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
122
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
123
-			@unlink($localrac_tmp);
124
-		}
125
-		else {
126
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
-		}
128
-		if (!$res or !$res['length']) {
129
-			// si $t c'est sans doute juste un not-modified-since
130
-			return $t ? $local : false;
131
-		}
132
-
133
-		// si option valider url, verifions que l'URL finale est acceptable
134
-		if (
135
-			$callback_valider_url
136
-			and is_callable($callback_valider_url)
137
-			and !$callback_valider_url($res['url'])
138
-		) {
139
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
-			@unlink($localrac_tmp);
141
-			return $t ? $local : false;
142
-		}
143
-
144
-		// on peut renommer le fichier tmp
145
-		@rename($localrac_tmp, $localrac);
146
-
147
-		// si on retrouve l'extension
148
-		if (
149
-			!empty($res['headers'])
150
-			and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
151
-		) {
152
-			if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
153
-				$sanitizer($localrac);
154
-			}
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;
73
+    // si c'est la protection de soi-meme, retourner le path
74
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
75
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
76
+
77
+        return @file_exists($source) ? $source : false;
78
+    }
79
+
80
+    if (is_null($local)) {
81
+        $local = fichier_copie_locale($source);
82
+    } else {
83
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
84
+            $local = substr($local, strlen(_DIR_RACINE));
85
+        }
86
+    }
87
+
88
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
89
+    // par exemple un fichier qui ne figure pas dans nos documents ;
90
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
91
+    if (!$local) {
92
+        return false;
93
+    }
94
+
95
+    $localrac = _DIR_RACINE . $local;
96
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
97
+
98
+    // test d'existence du fichier
99
+    if ($mode === 'test') {
100
+        return $t ? $local : '';
101
+    }
102
+
103
+    // sinon voir si on doit/peut le telecharger
104
+    if ($local === $source or !tester_url_absolue($source)) {
105
+        return $t ? $local : '';
106
+    }
107
+
108
+    if ($mode === 'modif' or !$t) {
109
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
110
+        // et des eventuelles recuperations concurantes
111
+        include_spip('inc/acces');
112
+        if (!$taille_max) {
113
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
114
+        }
115
+        $localrac_tmp = $localrac . '.tmp';
116
+        $res = recuperer_url(
117
+            $source,
118
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
119
+        );
120
+
121
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
122
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
123
+            @unlink($localrac_tmp);
124
+        }
125
+        else {
126
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
+        }
128
+        if (!$res or !$res['length']) {
129
+            // si $t c'est sans doute juste un not-modified-since
130
+            return $t ? $local : false;
131
+        }
132
+
133
+        // si option valider url, verifions que l'URL finale est acceptable
134
+        if (
135
+            $callback_valider_url
136
+            and is_callable($callback_valider_url)
137
+            and !$callback_valider_url($res['url'])
138
+        ) {
139
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
+            @unlink($localrac_tmp);
141
+            return $t ? $local : false;
142
+        }
143
+
144
+        // on peut renommer le fichier tmp
145
+        @rename($localrac_tmp, $localrac);
146
+
147
+        // si on retrouve l'extension
148
+        if (
149
+            !empty($res['headers'])
150
+            and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
151
+        ) {
152
+            if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
153
+                $sanitizer($localrac);
154
+            }
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,99 +185,99 @@  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 or empty($parsed_url['host'])) {
198
-		return false;
199
-	}
200
-
201
-	if (isset($parsed_url['user']) or 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($known_host);
219
-		if (
220
-			$parse_known
221
-			and 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) {
251
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
252
-				return false;
253
-			}
254
-		}
255
-	}
256
-
257
-	if (empty($parsed_url['port'])) {
258
-		return $url;
259
-	}
260
-
261
-	$port = $parsed_url['port'];
262
-	if ($port === 80  or $port === 443  or $port === 8080) {
263
-		return $url;
264
-	}
265
-
266
-	if ($is_known_host) {
267
-		foreach ($known_hosts as $known_host) {
268
-			$parse_known = parse_url($known_host);
269
-			if (
270
-				$parse_known
271
-				and !empty($parse_known['port'])
272
-				and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
273
-				and $parse_known['port'] == $port
274
-			) {
275
-				return $url;
276
-			}
277
-		}
278
-	}
279
-
280
-	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 or empty($parsed_url['host'])) {
198
+        return false;
199
+    }
200
+
201
+    if (isset($parsed_url['user']) or 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($known_host);
219
+        if (
220
+            $parse_known
221
+            and 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) {
251
+            if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
252
+                return false;
253
+            }
254
+        }
255
+    }
256
+
257
+    if (empty($parsed_url['port'])) {
258
+        return $url;
259
+    }
260
+
261
+    $port = $parsed_url['port'];
262
+    if ($port === 80  or $port === 443  or $port === 8080) {
263
+        return $url;
264
+    }
265
+
266
+    if ($is_known_host) {
267
+        foreach ($known_hosts as $known_host) {
268
+            $parse_known = parse_url($known_host);
269
+            if (
270
+                $parse_known
271
+                and !empty($parse_known['port'])
272
+                and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
273
+                and $parse_known['port'] == $port
274
+            ) {
275
+                return $url;
276
+            }
277
+        }
278
+    }
279
+
280
+    return false;
281 281
 }
282 282
 
283 283
 /**
@@ -297,86 +297,86 @@  discard block
 block discarded – undo
297 297
  */
298 298
 function prepare_donnees_post($donnees, $boundary = '') {
299 299
 
300
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
301
-	// pour un appel soap par exemple
302
-	// l'entete est separe des donnees par un double retour a la ligne
303
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
304
-	if (is_string($donnees) && strlen($donnees)) {
305
-		$entete = '';
306
-		// on repasse tous les \r\n et \r en simples \n
307
-		$donnees = str_replace("\r\n", "\n", $donnees);
308
-		$donnees = str_replace("\r", "\n", $donnees);
309
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
310
-		$p = strpos($donnees, "\n\n");
311
-		if ($p !== false) {
312
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
313
-			$donnees = substr($donnees, $p + 2);
314
-		}
315
-		$chaine = str_replace("\n", "\r\n", $donnees);
316
-	} else {
317
-		/* boundary automatique */
318
-		// Si on a plus de 500 octects de donnees, on "boundarise"
319
-		if ($boundary === '') {
320
-			$taille = 0;
321
-			foreach ($donnees as $cle => $valeur) {
322
-				if (is_array($valeur)) {
323
-					foreach ($valeur as $val2) {
324
-						$taille += strlen($val2);
325
-					}
326
-				} else {
327
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
328
-					$taille += strlen($valeur);
329
-				}
330
-			}
331
-			if ($taille > 500) {
332
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
333
-			}
334
-		}
335
-
336
-		if (is_string($boundary) and strlen($boundary)) {
337
-			// fabrique une chaine HTTP pour un POST avec boundary
338
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
339
-			$chaine = '';
340
-			if (is_array($donnees)) {
341
-				foreach ($donnees as $cle => $valeur) {
342
-					if (is_array($valeur)) {
343
-						foreach ($valeur as $val2) {
344
-							$chaine .= "\r\n--$boundary\r\n";
345
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
346
-							$chaine .= "\r\n";
347
-							$chaine .= $val2;
348
-						}
349
-					} else {
350
-						$chaine .= "\r\n--$boundary\r\n";
351
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
352
-						$chaine .= "\r\n";
353
-						$chaine .= $valeur;
354
-					}
355
-				}
356
-				$chaine .= "\r\n--$boundary\r\n";
357
-			}
358
-		} else {
359
-			// fabrique une chaine HTTP simple pour un POST
360
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
361
-			$chaine = [];
362
-			if (is_array($donnees)) {
363
-				foreach ($donnees as $cle => $valeur) {
364
-					if (is_array($valeur)) {
365
-						foreach ($valeur as $val2) {
366
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
367
-						}
368
-					} else {
369
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
370
-					}
371
-				}
372
-				$chaine = implode('&', $chaine);
373
-			} else {
374
-				$chaine = $donnees;
375
-			}
376
-		}
377
-	}
378
-
379
-	return [$entete, $chaine];
300
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
301
+    // pour un appel soap par exemple
302
+    // l'entete est separe des donnees par un double retour a la ligne
303
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
304
+    if (is_string($donnees) && strlen($donnees)) {
305
+        $entete = '';
306
+        // on repasse tous les \r\n et \r en simples \n
307
+        $donnees = str_replace("\r\n", "\n", $donnees);
308
+        $donnees = str_replace("\r", "\n", $donnees);
309
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
310
+        $p = strpos($donnees, "\n\n");
311
+        if ($p !== false) {
312
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
313
+            $donnees = substr($donnees, $p + 2);
314
+        }
315
+        $chaine = str_replace("\n", "\r\n", $donnees);
316
+    } else {
317
+        /* boundary automatique */
318
+        // Si on a plus de 500 octects de donnees, on "boundarise"
319
+        if ($boundary === '') {
320
+            $taille = 0;
321
+            foreach ($donnees as $cle => $valeur) {
322
+                if (is_array($valeur)) {
323
+                    foreach ($valeur as $val2) {
324
+                        $taille += strlen($val2);
325
+                    }
326
+                } else {
327
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
328
+                    $taille += strlen($valeur);
329
+                }
330
+            }
331
+            if ($taille > 500) {
332
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
333
+            }
334
+        }
335
+
336
+        if (is_string($boundary) and strlen($boundary)) {
337
+            // fabrique une chaine HTTP pour un POST avec boundary
338
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
339
+            $chaine = '';
340
+            if (is_array($donnees)) {
341
+                foreach ($donnees as $cle => $valeur) {
342
+                    if (is_array($valeur)) {
343
+                        foreach ($valeur as $val2) {
344
+                            $chaine .= "\r\n--$boundary\r\n";
345
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
346
+                            $chaine .= "\r\n";
347
+                            $chaine .= $val2;
348
+                        }
349
+                    } else {
350
+                        $chaine .= "\r\n--$boundary\r\n";
351
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
352
+                        $chaine .= "\r\n";
353
+                        $chaine .= $valeur;
354
+                    }
355
+                }
356
+                $chaine .= "\r\n--$boundary\r\n";
357
+            }
358
+        } else {
359
+            // fabrique une chaine HTTP simple pour un POST
360
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
361
+            $chaine = [];
362
+            if (is_array($donnees)) {
363
+                foreach ($donnees as $cle => $valeur) {
364
+                    if (is_array($valeur)) {
365
+                        foreach ($valeur as $val2) {
366
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
367
+                        }
368
+                    } else {
369
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
370
+                    }
371
+                }
372
+                $chaine = implode('&', $chaine);
373
+            } else {
374
+                $chaine = $donnees;
375
+            }
376
+        }
377
+    }
378
+
379
+    return [$entete, $chaine];
380 380
 }
381 381
 
382 382
 /**
@@ -390,20 +390,20 @@  discard block
 block discarded – undo
390 390
  */
391 391
 function url_to_ascii($url_idn) {
392 392
 
393
-	if ($parts = parse_url($url_idn)) {
394
-		$host = $parts['host'];
395
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
396
-			include_spip('inc/idna_convert.class');
397
-			$IDN = new idna_convert();
398
-			$host_ascii = $IDN->encode($host);
399
-			$url_idn = explode($host, $url_idn, 2);
400
-			$url_idn = implode($host_ascii, $url_idn);
401
-		}
402
-		// et on urlencode les char utf si besoin dans le path
403
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
404
-	}
405
-
406
-	return $url_idn;
393
+    if ($parts = parse_url($url_idn)) {
394
+        $host = $parts['host'];
395
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
396
+            include_spip('inc/idna_convert.class');
397
+            $IDN = new idna_convert();
398
+            $host_ascii = $IDN->encode($host);
399
+            $url_idn = explode($host, $url_idn, 2);
400
+            $url_idn = implode($host_ascii, $url_idn);
401
+        }
402
+        // et on urlencode les char utf si besoin dans le path
403
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
404
+    }
405
+
406
+    return $url_idn;
407 407
 }
408 408
 
409 409
 /**
@@ -444,209 +444,209 @@  discard block
 block discarded – undo
444 444
  *     string file : nom du fichier si enregistre dans un fichier
445 445
  */
446 446
 function recuperer_url($url, $options = []) {
447
-	// Conserve la mémoire de la méthode fournit éventuellement
448
-	$methode_demandee = $options['methode'] ?? '';
449
-	$default = [
450
-		'transcoder' => false,
451
-		'methode' => 'GET',
452
-		'taille_max' => null,
453
-		'headers' => [],
454
-		'datas' => '',
455
-		'boundary' => '',
456
-		'refuser_gz' => false,
457
-		'if_modified_since' => '',
458
-		'uri_referer' => '',
459
-		'file' => '',
460
-		'follow_location' => 10,
461
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
462
-	];
463
-	$options = array_merge($default, $options);
464
-	// copier directement dans un fichier ?
465
-	$copy = $options['file'];
466
-
467
-	if ($options['methode'] == 'HEAD') {
468
-		$options['taille_max'] = 0;
469
-	}
470
-	if (is_null($options['taille_max'])) {
471
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
472
-	}
473
-
474
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
475
-
476
-	// Ajout des en-têtes spécifiques si besoin
477
-	$formatted_data = '';
478
-	if (!empty($options['headers'])) {
479
-		foreach ($options['headers'] as $champ => $valeur) {
480
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
481
-		}
482
-	}
483
-
484
-	if (!empty($options['datas'])) {
485
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
486
-		$head .= $formatted_data;
487
-		if (stripos($head, 'Content-Length:') === false) {
488
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
489
-		}
490
-		$formatted_data = $head . "\r\n" . $postdata;
491
-		if (
492
-			strlen($postdata)
493
-			and !$methode_demandee
494
-		) {
495
-			$options['methode'] = 'POST';
496
-		}
497
-	} elseif ($formatted_data) {
498
-		$formatted_data .= "\r\n";
499
-	}
500
-
501
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
502
-	$url = preg_replace(',^feed://,i', 'http://', $url);
503
-	if (!tester_url_absolue($url)) {
504
-		$url = 'http://' . $url;
505
-	} elseif (strncmp($url, '//', 2) == 0) {
506
-		$url = 'http:' . $url;
507
-	}
508
-
509
-	$url = url_to_ascii($url);
510
-
511
-	$result = [
512
-		'status' => 0,
513
-		'headers' => '',
514
-		'page' => '',
515
-		'length' => 0,
516
-		'last_modified' => '',
517
-		'location' => '',
518
-		'url' => $url
519
-	];
520
-
521
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
522
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
523
-
524
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
525
-	[$handle, $fopen] = init_http(
526
-		$options['methode'],
527
-		$url,
528
-		$refuser_gz,
529
-		$options['uri_referer'],
530
-		$formatted_data,
531
-		$options['version_http'],
532
-		$options['if_modified_since']
533
-	);
534
-	if (!$handle) {
535
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
536
-
537
-		return false;
538
-	}
539
-
540
-	// Sauf en fopen, envoyer le flux d'entree
541
-	// et recuperer les en-tetes de reponses
542
-	if (!$fopen) {
543
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
544
-		if (!$res) {
545
-			fclose($handle);
546
-			$t = @parse_url($url);
547
-			$host = $t['host'];
548
-			// Chinoisierie inexplicable pour contrer
549
-			// les actions liberticides de l'empire du milieu
550
-			if (
551
-				!need_proxy($host)
552
-				and $res = @file_get_contents($url)
553
-			) {
554
-				$result['length'] = strlen($res);
555
-				if ($copy) {
556
-					ecrire_fichier($copy, $res);
557
-					$result['file'] = $copy;
558
-				} else {
559
-					$result['page'] = $res;
560
-				}
561
-				$res = [
562
-					'status' => 200,
563
-				];
564
-			} else {
565
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
566
-				return false;
567
-			}
568
-		} elseif ($res['location'] and $options['follow_location']) {
569
-			$options['follow_location']--;
570
-			fclose($handle);
571
-			include_spip('inc/filtres');
572
-			$url = suivre_lien($url, $res['location']);
573
-
574
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
575
-			if ($options['methode'] !== 'GET') {
576
-				if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
577
-					$options['methode'] = 'GET';
578
-					$options['datas'] = '';
579
-				}
580
-			}
581
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
582
-
583
-			return recuperer_url($url, $options);
584
-		} elseif ($res['status'] !== 200) {
585
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
586
-		}
587
-		$result['status'] = $res['status'];
588
-		if (isset($res['headers'])) {
589
-			$result['headers'] = $res['headers'];
590
-		}
591
-		if (isset($res['last_modified'])) {
592
-			$result['last_modified'] = $res['last_modified'];
593
-		}
594
-		if (isset($res['location'])) {
595
-			$result['location'] = $res['location'];
596
-		}
597
-	}
598
-
599
-	// on ne veut que les entetes
600
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
601
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
602
-		return $result;
603
-	}
604
-
605
-
606
-	// s'il faut deballer, le faire via un fichier temporaire
607
-	// sinon la memoire explose pour les gros flux
608
-
609
-	$gz = false;
610
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
611
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
612
-	}
613
-
614
-	// si on a pas deja recuperer le contenu par une methode detournee
615
-	if (!$result['length']) {
616
-		$res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
617
-		fclose($handle);
618
-		if ($copy) {
619
-			$result['length'] = $res;
620
-			$result['file'] = $copy;
621
-		} elseif ($res) {
622
-			$result['page'] = &$res;
623
-			$result['length'] = strlen($result['page']);
624
-		}
625
-		if (!$result['status']) {
626
-			$result['status'] = 200; // on a reussi, donc !
627
-		}
628
-	}
629
-	if (!$result['page']) {
630
-		return $result;
631
-	}
632
-
633
-	// Decompresser au besoin
634
-	if ($gz) {
635
-		$result['page'] = implode('', gzfile($gz));
636
-		supprimer_fichier($gz);
637
-	}
638
-
639
-	// Faut-il l'importer dans notre charset local ?
640
-	if ($options['transcoder']) {
641
-		include_spip('inc/charsets');
642
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
643
-	}
644
-
645
-	$trace = json_decode(json_encode($result), true);
646
-	$trace['page'] = '...';
647
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
648
-
649
-	return $result;
447
+    // Conserve la mémoire de la méthode fournit éventuellement
448
+    $methode_demandee = $options['methode'] ?? '';
449
+    $default = [
450
+        'transcoder' => false,
451
+        'methode' => 'GET',
452
+        'taille_max' => null,
453
+        'headers' => [],
454
+        'datas' => '',
455
+        'boundary' => '',
456
+        'refuser_gz' => false,
457
+        'if_modified_since' => '',
458
+        'uri_referer' => '',
459
+        'file' => '',
460
+        'follow_location' => 10,
461
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
462
+    ];
463
+    $options = array_merge($default, $options);
464
+    // copier directement dans un fichier ?
465
+    $copy = $options['file'];
466
+
467
+    if ($options['methode'] == 'HEAD') {
468
+        $options['taille_max'] = 0;
469
+    }
470
+    if (is_null($options['taille_max'])) {
471
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
472
+    }
473
+
474
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
475
+
476
+    // Ajout des en-têtes spécifiques si besoin
477
+    $formatted_data = '';
478
+    if (!empty($options['headers'])) {
479
+        foreach ($options['headers'] as $champ => $valeur) {
480
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
481
+        }
482
+    }
483
+
484
+    if (!empty($options['datas'])) {
485
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
486
+        $head .= $formatted_data;
487
+        if (stripos($head, 'Content-Length:') === false) {
488
+            $head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
489
+        }
490
+        $formatted_data = $head . "\r\n" . $postdata;
491
+        if (
492
+            strlen($postdata)
493
+            and !$methode_demandee
494
+        ) {
495
+            $options['methode'] = 'POST';
496
+        }
497
+    } elseif ($formatted_data) {
498
+        $formatted_data .= "\r\n";
499
+    }
500
+
501
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
502
+    $url = preg_replace(',^feed://,i', 'http://', $url);
503
+    if (!tester_url_absolue($url)) {
504
+        $url = 'http://' . $url;
505
+    } elseif (strncmp($url, '//', 2) == 0) {
506
+        $url = 'http:' . $url;
507
+    }
508
+
509
+    $url = url_to_ascii($url);
510
+
511
+    $result = [
512
+        'status' => 0,
513
+        'headers' => '',
514
+        'page' => '',
515
+        'length' => 0,
516
+        'last_modified' => '',
517
+        'location' => '',
518
+        'url' => $url
519
+    ];
520
+
521
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
522
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
523
+
524
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
525
+    [$handle, $fopen] = init_http(
526
+        $options['methode'],
527
+        $url,
528
+        $refuser_gz,
529
+        $options['uri_referer'],
530
+        $formatted_data,
531
+        $options['version_http'],
532
+        $options['if_modified_since']
533
+    );
534
+    if (!$handle) {
535
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
536
+
537
+        return false;
538
+    }
539
+
540
+    // Sauf en fopen, envoyer le flux d'entree
541
+    // et recuperer les en-tetes de reponses
542
+    if (!$fopen) {
543
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
544
+        if (!$res) {
545
+            fclose($handle);
546
+            $t = @parse_url($url);
547
+            $host = $t['host'];
548
+            // Chinoisierie inexplicable pour contrer
549
+            // les actions liberticides de l'empire du milieu
550
+            if (
551
+                !need_proxy($host)
552
+                and $res = @file_get_contents($url)
553
+            ) {
554
+                $result['length'] = strlen($res);
555
+                if ($copy) {
556
+                    ecrire_fichier($copy, $res);
557
+                    $result['file'] = $copy;
558
+                } else {
559
+                    $result['page'] = $res;
560
+                }
561
+                $res = [
562
+                    'status' => 200,
563
+                ];
564
+            } else {
565
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
566
+                return false;
567
+            }
568
+        } elseif ($res['location'] and $options['follow_location']) {
569
+            $options['follow_location']--;
570
+            fclose($handle);
571
+            include_spip('inc/filtres');
572
+            $url = suivre_lien($url, $res['location']);
573
+
574
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
575
+            if ($options['methode'] !== 'GET') {
576
+                if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
577
+                    $options['methode'] = 'GET';
578
+                    $options['datas'] = '';
579
+                }
580
+            }
581
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
582
+
583
+            return recuperer_url($url, $options);
584
+        } elseif ($res['status'] !== 200) {
585
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
586
+        }
587
+        $result['status'] = $res['status'];
588
+        if (isset($res['headers'])) {
589
+            $result['headers'] = $res['headers'];
590
+        }
591
+        if (isset($res['last_modified'])) {
592
+            $result['last_modified'] = $res['last_modified'];
593
+        }
594
+        if (isset($res['location'])) {
595
+            $result['location'] = $res['location'];
596
+        }
597
+    }
598
+
599
+    // on ne veut que les entetes
600
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
601
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
602
+        return $result;
603
+    }
604
+
605
+
606
+    // s'il faut deballer, le faire via un fichier temporaire
607
+    // sinon la memoire explose pour les gros flux
608
+
609
+    $gz = false;
610
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
611
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
612
+    }
613
+
614
+    // si on a pas deja recuperer le contenu par une methode detournee
615
+    if (!$result['length']) {
616
+        $res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
617
+        fclose($handle);
618
+        if ($copy) {
619
+            $result['length'] = $res;
620
+            $result['file'] = $copy;
621
+        } elseif ($res) {
622
+            $result['page'] = &$res;
623
+            $result['length'] = strlen($result['page']);
624
+        }
625
+        if (!$result['status']) {
626
+            $result['status'] = 200; // on a reussi, donc !
627
+        }
628
+    }
629
+    if (!$result['page']) {
630
+        return $result;
631
+    }
632
+
633
+    // Decompresser au besoin
634
+    if ($gz) {
635
+        $result['page'] = implode('', gzfile($gz));
636
+        supprimer_fichier($gz);
637
+    }
638
+
639
+    // Faut-il l'importer dans notre charset local ?
640
+    if ($options['transcoder']) {
641
+        include_spip('inc/charsets');
642
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
643
+    }
644
+
645
+    $trace = json_decode(json_encode($result), true);
646
+    $trace['page'] = '...';
647
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
648
+
649
+    return $result;
650 650
 }
651 651
 
652 652
 /**
@@ -662,73 +662,73 @@  discard block
 block discarded – undo
662 662
  * @return array|bool|mixed
663 663
  */
664 664
 function recuperer_url_cache($url, $options = []) {
665
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
666
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
667
-	}
668
-	$default = [
669
-		'transcoder' => false,
670
-		'methode' => 'GET',
671
-		'taille_max' => null,
672
-		'datas' => '',
673
-		'boundary' => '',
674
-		'refuser_gz' => false,
675
-		'if_modified_since' => '',
676
-		'uri_referer' => '',
677
-		'file' => '',
678
-		'follow_location' => 10,
679
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
680
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
681
-	];
682
-	$options = array_merge($default, $options);
683
-
684
-	// cas ou il n'est pas possible de cacher
685
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
686
-		return recuperer_url($url, $options);
687
-	}
688
-
689
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
690
-	static $errors = [];
691
-	if (isset($errors[$url])) {
692
-		return $errors[$url];
693
-	}
694
-
695
-	$sig = $options;
696
-	unset($sig['if_modified_since']);
697
-	unset($sig['delai_cache']);
698
-	$sig['url'] = $url;
699
-
700
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
701
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
702
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
703
-	$cache = "$sub$cache";
704
-
705
-	$res = false;
706
-	$is_cached = file_exists($cache);
707
-	if (
708
-		$is_cached
709
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
710
-	) {
711
-		lire_fichier($cache, $res);
712
-		if ($res = unserialize($res)) {
713
-			// mettre le last_modified et le status=304 ?
714
-		}
715
-	}
716
-	if (!$res) {
717
-		$res = recuperer_url($url, $options);
718
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
719
-		if (!$res) {
720
-			if ($is_cached) {
721
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
722
-				lire_fichier($cache, $res);
723
-				$res = unserialize($res);
724
-			}
725
-
726
-			return $errors[$url] = $res;
727
-		}
728
-		ecrire_fichier($cache, serialize($res));
729
-	}
730
-
731
-	return $res;
665
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
666
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
667
+    }
668
+    $default = [
669
+        'transcoder' => false,
670
+        'methode' => 'GET',
671
+        'taille_max' => null,
672
+        'datas' => '',
673
+        'boundary' => '',
674
+        'refuser_gz' => false,
675
+        'if_modified_since' => '',
676
+        'uri_referer' => '',
677
+        'file' => '',
678
+        'follow_location' => 10,
679
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
680
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
681
+    ];
682
+    $options = array_merge($default, $options);
683
+
684
+    // cas ou il n'est pas possible de cacher
685
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
686
+        return recuperer_url($url, $options);
687
+    }
688
+
689
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
690
+    static $errors = [];
691
+    if (isset($errors[$url])) {
692
+        return $errors[$url];
693
+    }
694
+
695
+    $sig = $options;
696
+    unset($sig['if_modified_since']);
697
+    unset($sig['delai_cache']);
698
+    $sig['url'] = $url;
699
+
700
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
701
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
702
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
703
+    $cache = "$sub$cache";
704
+
705
+    $res = false;
706
+    $is_cached = file_exists($cache);
707
+    if (
708
+        $is_cached
709
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
710
+    ) {
711
+        lire_fichier($cache, $res);
712
+        if ($res = unserialize($res)) {
713
+            // mettre le last_modified et le status=304 ?
714
+        }
715
+    }
716
+    if (!$res) {
717
+        $res = recuperer_url($url, $options);
718
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
719
+        if (!$res) {
720
+            if ($is_cached) {
721
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
722
+                lire_fichier($cache, $res);
723
+                $res = unserialize($res);
724
+            }
725
+
726
+            return $errors[$url] = $res;
727
+        }
728
+        ecrire_fichier($cache, serialize($res));
729
+    }
730
+
731
+    return $res;
732 732
 }
733 733
 
734 734
 /**
@@ -746,42 +746,42 @@  discard block
 block discarded – undo
746 746
  *   string contenu de la resource
747 747
  */
748 748
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
749
-	$tmpfile = null;
750
-	$taille = 0;
751
-	$result = '';
752
-	$fp = false;
753
-	if ($fichier) {
754
-		include_spip('inc/acces');
755
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
756
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
757
-		if (!$fp and file_exists($fichier)) {
758
-			return filesize($fichier);
759
-		}
760
-		if (!$fp) {
761
-			return false;
762
-		}
763
-		$result = 0; // on renvoie la taille du fichier
764
-	}
765
-	while (!feof($handle) and $taille < $taille_max) {
766
-		$res = fread($handle, 16384);
767
-		$taille += strlen($res);
768
-		if ($fp) {
769
-			fwrite($fp, $res);
770
-			$result = $taille;
771
-		} else {
772
-			$result .= $res;
773
-		}
774
-	}
775
-	if ($fp) {
776
-		spip_fclose_unlock($fp);
777
-		spip_unlink($fichier);
778
-		@rename($tmpfile, $fichier);
779
-		if (!file_exists($fichier)) {
780
-			return false;
781
-		}
782
-	}
783
-
784
-	return $result;
749
+    $tmpfile = null;
750
+    $taille = 0;
751
+    $result = '';
752
+    $fp = false;
753
+    if ($fichier) {
754
+        include_spip('inc/acces');
755
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
756
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
757
+        if (!$fp and file_exists($fichier)) {
758
+            return filesize($fichier);
759
+        }
760
+        if (!$fp) {
761
+            return false;
762
+        }
763
+        $result = 0; // on renvoie la taille du fichier
764
+    }
765
+    while (!feof($handle) and $taille < $taille_max) {
766
+        $res = fread($handle, 16384);
767
+        $taille += strlen($res);
768
+        if ($fp) {
769
+            fwrite($fp, $res);
770
+            $result = $taille;
771
+        } else {
772
+            $result .= $res;
773
+        }
774
+    }
775
+    if ($fp) {
776
+        spip_fclose_unlock($fp);
777
+        spip_unlink($fichier);
778
+        @rename($tmpfile, $fichier);
779
+        if (!file_exists($fichier)) {
780
+            return false;
781
+        }
782
+    }
783
+
784
+    return $result;
785 785
 }
786 786
 
787 787
 /**
@@ -803,35 +803,35 @@  discard block
 block discarded – undo
803 803
  *   string location
804 804
  */
805 805
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
806
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
807
-
808
-	$s = @trim(fgets($handle, 16384));
809
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
810
-		return false;
811
-	}
812
-	$result['status'] = intval($r[1]);
813
-	while ($s = trim(fgets($handle, 16384))) {
814
-		$result['headers'][] = $s . "\n";
815
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
816
-		[, $d, $v] = $r;
817
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
818
-			$result['location'] = $v;
819
-		} elseif ($d == 'Last-Modified') {
820
-			$result['last_modified'] = strtotime($v);
821
-		}
822
-	}
823
-	if (
824
-		$if_modified_since
825
-		and $result['last_modified']
826
-		and $if_modified_since > $result['last_modified']
827
-		and $result['status'] == 200
828
-	) {
829
-		$result['status'] = 304;
830
-	}
831
-
832
-	$result['headers'] = implode('', $result['headers']);
833
-
834
-	return $result;
806
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
807
+
808
+    $s = @trim(fgets($handle, 16384));
809
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
810
+        return false;
811
+    }
812
+    $result['status'] = intval($r[1]);
813
+    while ($s = trim(fgets($handle, 16384))) {
814
+        $result['headers'][] = $s . "\n";
815
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
816
+        [, $d, $v] = $r;
817
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
818
+            $result['location'] = $v;
819
+        } elseif ($d == 'Last-Modified') {
820
+            $result['last_modified'] = strtotime($v);
821
+        }
822
+    }
823
+    if (
824
+        $if_modified_since
825
+        and $result['last_modified']
826
+        and $if_modified_since > $result['last_modified']
827
+        and $result['status'] == 200
828
+    ) {
829
+        $result['status'] = 304;
830
+    }
831
+
832
+    $result['headers'] = implode('', $result['headers']);
833
+
834
+    return $result;
835 835
 }
836 836
 
837 837
 /**
@@ -853,22 +853,22 @@  discard block
 block discarded – undo
853 853
  *     Nom du fichier pour copie locale
854 854
  **/
855 855
 function nom_fichier_copie_locale($source, $extension) {
856
-	include_spip('inc/documents');
856
+    include_spip('inc/documents');
857 857
 
858
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
859
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
858
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
859
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
860 860
 
861
-	// on se place tout le temps comme si on etait a la racine
862
-	if (_DIR_RACINE) {
863
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
864
-	}
861
+    // on se place tout le temps comme si on etait a la racine
862
+    if (_DIR_RACINE) {
863
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
864
+    }
865 865
 
866
-	$m = md5($source);
866
+    $m = md5($source);
867 867
 
868
-	return $d
869
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
870
-	. substr($m, 0, 4)
871
-	. ".$extension";
868
+    return $d
869
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
870
+    . substr($m, 0, 4)
871
+    . ".$extension";
872 872
 }
873 873
 
874 874
 /**
@@ -886,70 +886,70 @@  discard block
 block discarded – undo
886 886
  *      Nom du fichier calculé
887 887
  **/
888 888
 function fichier_copie_locale($source) {
889
-	// Si c'est deja local pas de souci
890
-	if (!tester_url_absolue($source)) {
891
-		if (_DIR_RACINE) {
892
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
893
-		}
894
-
895
-		return $source;
896
-	}
897
-
898
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
899
-	// a deja ete copie en local avec cette extension
900
-	// dans ce cas elle est fiable, pas la peine de requeter en base
901
-	$path_parts = pathinfo($source);
902
-	if (!isset($path_parts['extension'])) {
903
-		$path_parts['extension'] = '';
904
-	}
905
-	$ext = $path_parts ? $path_parts['extension'] : '';
906
-	if (
907
-		$ext
908
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
909
-		and $f = nom_fichier_copie_locale($source, $ext)
910
-		and file_exists(_DIR_RACINE . $f)
911
-	) {
912
-		return $f;
913
-	}
914
-
915
-
916
-	// Si c'est deja dans la table des documents,
917
-	// ramener le nom de sa copie potentielle
918
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
919
-
920
-	if ($ext) {
921
-		return nom_fichier_copie_locale($source, $ext);
922
-	}
923
-
924
-	// voir si l'extension indiquee dans le nom du fichier est ok
925
-	// et si il n'aurait pas deja ete rapatrie
926
-
927
-	$ext = $path_parts ? $path_parts['extension'] : '';
928
-
929
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
930
-		$f = nom_fichier_copie_locale($source, $ext);
931
-		if (file_exists(_DIR_RACINE . $f)) {
932
-			return $f;
933
-		}
934
-	}
935
-
936
-	// Ping  pour voir si son extension est connue et autorisee
937
-	// avec mise en cache du resultat du ping
938
-
939
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
940
-	if (
941
-		!@file_exists($cache)
942
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
943
-		or _request('var_mode') === 'recalcul'
944
-	) {
945
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
946
-		ecrire_fichier($cache, serialize($path_parts));
947
-	}
948
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
949
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
950
-		return nom_fichier_copie_locale($source, $ext);
951
-	}
952
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
889
+    // Si c'est deja local pas de souci
890
+    if (!tester_url_absolue($source)) {
891
+        if (_DIR_RACINE) {
892
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
893
+        }
894
+
895
+        return $source;
896
+    }
897
+
898
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
899
+    // a deja ete copie en local avec cette extension
900
+    // dans ce cas elle est fiable, pas la peine de requeter en base
901
+    $path_parts = pathinfo($source);
902
+    if (!isset($path_parts['extension'])) {
903
+        $path_parts['extension'] = '';
904
+    }
905
+    $ext = $path_parts ? $path_parts['extension'] : '';
906
+    if (
907
+        $ext
908
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
909
+        and $f = nom_fichier_copie_locale($source, $ext)
910
+        and file_exists(_DIR_RACINE . $f)
911
+    ) {
912
+        return $f;
913
+    }
914
+
915
+
916
+    // Si c'est deja dans la table des documents,
917
+    // ramener le nom de sa copie potentielle
918
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
919
+
920
+    if ($ext) {
921
+        return nom_fichier_copie_locale($source, $ext);
922
+    }
923
+
924
+    // voir si l'extension indiquee dans le nom du fichier est ok
925
+    // et si il n'aurait pas deja ete rapatrie
926
+
927
+    $ext = $path_parts ? $path_parts['extension'] : '';
928
+
929
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
930
+        $f = nom_fichier_copie_locale($source, $ext);
931
+        if (file_exists(_DIR_RACINE . $f)) {
932
+            return $f;
933
+        }
934
+    }
935
+
936
+    // Ping  pour voir si son extension est connue et autorisee
937
+    // avec mise en cache du resultat du ping
938
+
939
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
940
+    if (
941
+        !@file_exists($cache)
942
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
943
+        or _request('var_mode') === 'recalcul'
944
+    ) {
945
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
946
+        ecrire_fichier($cache, serialize($path_parts));
947
+    }
948
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
949
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
950
+        return nom_fichier_copie_locale($source, $ext);
951
+    }
952
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
953 953
 }
954 954
 
955 955
 
@@ -978,110 +978,110 @@  discard block
 block discarded – undo
978 978
  **/
979 979
 function recuperer_infos_distantes($source, $options = []) {
980 980
 
981
-	// pas la peine de perdre son temps
982
-	if (!tester_url_absolue($source)) {
983
-		return false;
984
-	}
985
-
986
-	$taille_max = $options['taille_max'] ?? 0;
987
-	$charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
988
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
989
-
990
-	# charger les alias des types mime
991
-	include_spip('base/typedoc');
992
-
993
-	$a = [];
994
-	$mime_type = '';
995
-	// On va directement charger le debut des images et des fichiers html,
996
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
997
-	// ca echoue l'utilisateur devra les entrer...
998
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
999
-	if (
1000
-		$callback_valider_url
1001
-		and is_callable($callback_valider_url)
1002
-		and !$callback_valider_url($reponse['url'])
1003
-	) {
1004
-		return false;
1005
-	}
1006
-	$headers = $reponse['headers'] ?? '';
1007
-	$a['body'] = $reponse['page'] ?? '';
1008
-	if ($headers) {
1009
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1010
-			return false;
1011
-		}
1012
-
1013
-		$a['extension'] = $extension;
1014
-
1015
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1016
-			$a['taille'] = intval($regs[1]);
1017
-		}
1018
-	}
1019
-
1020
-	// Echec avec HEAD, on tente avec GET
1021
-	if (!$a and !$taille_max) {
1022
-		spip_log("tenter GET $source", 'distant');
1023
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1024
-		$a = recuperer_infos_distantes($source, $options);
1025
-	}
1026
-
1027
-	// si on a rien trouve pas la peine d'insister
1028
-	if (!$a) {
1029
-		return false;
1030
-	}
1031
-
1032
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1033
-	// recharger le document en GET et recuperer des donnees supplementaires...
1034
-	include_spip('inc/filtres_images_lib_mini');
1035
-	if (
1036
-		strpos($mime_type, 'image/') === 0
1037
-		and $extension = _image_trouver_extension_depuis_mime($mime_type)
1038
-	) {
1039
-		if (
1040
-			$taille_max == 0
1041
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1042
-			and in_array($extension, formats_image_acceptables())
1043
-			and $charger_si_petite_image
1044
-		) {
1045
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1046
-			$a = recuperer_infos_distantes($source, $options);
1047
-		} else {
1048
-			if ($a['body']) {
1049
-				$a['extension'] = $extension;
1050
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1051
-				ecrire_fichier($a['fichier'], $a['body']);
1052
-				$size_image = @spip_getimagesize($a['fichier']);
1053
-				$a['largeur'] = intval($size_image[0]);
1054
-				$a['hauteur'] = intval($size_image[1]);
1055
-				$a['type_image'] = true;
1056
-			}
1057
-		}
1058
-	}
1059
-
1060
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1061
-	// ce sera mieux que 0x0
1062
-	// Flash is dead!
1063
-	if (
1064
-		$a and isset($a['extension']) and $a['extension'] == 'swf'
1065
-		and empty($a['largeur'])
1066
-	) {
1067
-		$a['largeur'] = 425;
1068
-		$a['hauteur'] = 350;
1069
-	}
1070
-
1071
-	if ($mime_type == 'text/html') {
1072
-		include_spip('inc/filtres');
1073
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1074
-		$page = $page['page'] ?? '';
1075
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1076
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1077
-		}
1078
-		if (!isset($a['taille']) or !$a['taille']) {
1079
-			$a['taille'] = strlen($page); # a peu pres
1080
-		}
1081
-	}
1082
-	$a['mime_type'] = $mime_type;
1083
-
1084
-	return $a;
981
+    // pas la peine de perdre son temps
982
+    if (!tester_url_absolue($source)) {
983
+        return false;
984
+    }
985
+
986
+    $taille_max = $options['taille_max'] ?? 0;
987
+    $charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
988
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
989
+
990
+    # charger les alias des types mime
991
+    include_spip('base/typedoc');
992
+
993
+    $a = [];
994
+    $mime_type = '';
995
+    // On va directement charger le debut des images et des fichiers html,
996
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
997
+    // ca echoue l'utilisateur devra les entrer...
998
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
999
+    if (
1000
+        $callback_valider_url
1001
+        and is_callable($callback_valider_url)
1002
+        and !$callback_valider_url($reponse['url'])
1003
+    ) {
1004
+        return false;
1005
+    }
1006
+    $headers = $reponse['headers'] ?? '';
1007
+    $a['body'] = $reponse['page'] ?? '';
1008
+    if ($headers) {
1009
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1010
+            return false;
1011
+        }
1012
+
1013
+        $a['extension'] = $extension;
1014
+
1015
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1016
+            $a['taille'] = intval($regs[1]);
1017
+        }
1018
+    }
1019
+
1020
+    // Echec avec HEAD, on tente avec GET
1021
+    if (!$a and !$taille_max) {
1022
+        spip_log("tenter GET $source", 'distant');
1023
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1024
+        $a = recuperer_infos_distantes($source, $options);
1025
+    }
1026
+
1027
+    // si on a rien trouve pas la peine d'insister
1028
+    if (!$a) {
1029
+        return false;
1030
+    }
1031
+
1032
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1033
+    // recharger le document en GET et recuperer des donnees supplementaires...
1034
+    include_spip('inc/filtres_images_lib_mini');
1035
+    if (
1036
+        strpos($mime_type, 'image/') === 0
1037
+        and $extension = _image_trouver_extension_depuis_mime($mime_type)
1038
+    ) {
1039
+        if (
1040
+            $taille_max == 0
1041
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1042
+            and in_array($extension, formats_image_acceptables())
1043
+            and $charger_si_petite_image
1044
+        ) {
1045
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1046
+            $a = recuperer_infos_distantes($source, $options);
1047
+        } else {
1048
+            if ($a['body']) {
1049
+                $a['extension'] = $extension;
1050
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1051
+                ecrire_fichier($a['fichier'], $a['body']);
1052
+                $size_image = @spip_getimagesize($a['fichier']);
1053
+                $a['largeur'] = intval($size_image[0]);
1054
+                $a['hauteur'] = intval($size_image[1]);
1055
+                $a['type_image'] = true;
1056
+            }
1057
+        }
1058
+    }
1059
+
1060
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1061
+    // ce sera mieux que 0x0
1062
+    // Flash is dead!
1063
+    if (
1064
+        $a and isset($a['extension']) and $a['extension'] == 'swf'
1065
+        and empty($a['largeur'])
1066
+    ) {
1067
+        $a['largeur'] = 425;
1068
+        $a['hauteur'] = 350;
1069
+    }
1070
+
1071
+    if ($mime_type == 'text/html') {
1072
+        include_spip('inc/filtres');
1073
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1074
+        $page = $page['page'] ?? '';
1075
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1076
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1077
+        }
1078
+        if (!isset($a['taille']) or !$a['taille']) {
1079
+            $a['taille'] = strlen($page); # a peu pres
1080
+        }
1081
+    }
1082
+    $a['mime_type'] = $mime_type;
1083
+
1084
+    return $a;
1085 1085
 }
1086 1086
 
1087 1087
 /**
@@ -1090,70 +1090,70 @@  discard block
 block discarded – undo
1090 1090
  * @return false|mixed
1091 1091
  */
1092 1092
 function distant_trouver_extension_selon_headers($source, $headers) {
1093
-	if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1094
-		$mime_type = (trim($regs[1]));
1095
-	} else {
1096
-		$mime_type = '';
1097
-	} // inconnu
1098
-
1099
-	// Appliquer les alias
1100
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1101
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1102
-	}
1103
-
1104
-	// pour corriger_extension()
1105
-	include_spip('inc/documents');
1106
-
1107
-	// Si on a un mime-type insignifiant
1108
-	// text/plain,application/octet-stream ou vide
1109
-	// c'est peut-etre que le serveur ne sait pas
1110
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1111
-	// ou le Content-Disposition: attachment; filename=...
1112
-	$t = null;
1113
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1114
-		if (
1115
-			!$t
1116
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1117
-		) {
1118
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1119
-		}
1120
-		if (
1121
-			!$t
1122
-			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1123
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1124
-		) {
1125
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1126
-		}
1127
-	}
1128
-
1129
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1130
-	if (!$t) {
1131
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1132
-	}
1133
-
1134
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1135
-	// On essaie de nouveau avec l'extension
1136
-	if (
1137
-		!$t
1138
-		and $mime_type != 'text/plain'
1139
-		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1140
-	) {
1141
-		# eviter xxx.3 => 3gp (> SPIP 3)
1142
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1143
-	}
1144
-
1145
-	if ($t) {
1146
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1147
-		return $t['extension'];
1148
-	} else {
1149
-		# par defaut on retombe sur '.bin' si c'est autorise
1150
-		spip_log("mime-type $mime_type inconnu", 'distant');
1151
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1152
-		if (!$t) {
1153
-			return false;
1154
-		}
1155
-		return $t['extension'];
1156
-	}
1093
+    if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1094
+        $mime_type = (trim($regs[1]));
1095
+    } else {
1096
+        $mime_type = '';
1097
+    } // inconnu
1098
+
1099
+    // Appliquer les alias
1100
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1101
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1102
+    }
1103
+
1104
+    // pour corriger_extension()
1105
+    include_spip('inc/documents');
1106
+
1107
+    // Si on a un mime-type insignifiant
1108
+    // text/plain,application/octet-stream ou vide
1109
+    // c'est peut-etre que le serveur ne sait pas
1110
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1111
+    // ou le Content-Disposition: attachment; filename=...
1112
+    $t = null;
1113
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1114
+        if (
1115
+            !$t
1116
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1117
+        ) {
1118
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1119
+        }
1120
+        if (
1121
+            !$t
1122
+            and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1123
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1124
+        ) {
1125
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1126
+        }
1127
+    }
1128
+
1129
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1130
+    if (!$t) {
1131
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1132
+    }
1133
+
1134
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1135
+    // On essaie de nouveau avec l'extension
1136
+    if (
1137
+        !$t
1138
+        and $mime_type != 'text/plain'
1139
+        and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1140
+    ) {
1141
+        # eviter xxx.3 => 3gp (> SPIP 3)
1142
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1143
+    }
1144
+
1145
+    if ($t) {
1146
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1147
+        return $t['extension'];
1148
+    } else {
1149
+        # par defaut on retombe sur '.bin' si c'est autorise
1150
+        spip_log("mime-type $mime_type inconnu", 'distant');
1151
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1152
+        if (!$t) {
1153
+            return false;
1154
+        }
1155
+        return $t['extension'];
1156
+    }
1157 1157
 }
1158 1158
 
1159 1159
 /**
@@ -1169,45 +1169,45 @@  discard block
 block discarded – undo
1169 1169
  */
1170 1170
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1171 1171
 
1172
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1173
-
1174
-	// rien a faire si pas de proxy :)
1175
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1176
-		return '';
1177
-	}
1178
-
1179
-	if (is_null($http_noproxy)) {
1180
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1181
-	}
1182
-	// si pas d'exception, on retourne le proxy
1183
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1184
-		return $http_proxy;
1185
-	}
1186
-
1187
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1188
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1189
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1190
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1191
-	$http_noproxy = " $http_noproxy ";
1192
-	$domain = $host;
1193
-	// si le domaine exact www.example.org est dans les exceptions
1194
-	if (strpos($http_noproxy, (string) " $domain ") !== false) {
1195
-		return '';
1196
-	}
1197
-
1198
-	while (strpos($domain, '.') !== false) {
1199
-		$domain = explode('.', $domain);
1200
-		array_shift($domain);
1201
-		$domain = implode('.', $domain);
1202
-
1203
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1204
-		if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1205
-			return '';
1206
-		}
1207
-	}
1208
-
1209
-	// ok c'est pas une exception
1210
-	return $http_proxy;
1172
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1173
+
1174
+    // rien a faire si pas de proxy :)
1175
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1176
+        return '';
1177
+    }
1178
+
1179
+    if (is_null($http_noproxy)) {
1180
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1181
+    }
1182
+    // si pas d'exception, on retourne le proxy
1183
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1184
+        return $http_proxy;
1185
+    }
1186
+
1187
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1188
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1189
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1190
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1191
+    $http_noproxy = " $http_noproxy ";
1192
+    $domain = $host;
1193
+    // si le domaine exact www.example.org est dans les exceptions
1194
+    if (strpos($http_noproxy, (string) " $domain ") !== false) {
1195
+        return '';
1196
+    }
1197
+
1198
+    while (strpos($domain, '.') !== false) {
1199
+        $domain = explode('.', $domain);
1200
+        array_shift($domain);
1201
+        $domain = implode('.', $domain);
1202
+
1203
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1204
+        if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1205
+            return '';
1206
+        }
1207
+    }
1208
+
1209
+    // ok c'est pas une exception
1210
+    return $http_proxy;
1211 1211
 }
1212 1212
 
1213 1213
 
@@ -1230,59 +1230,59 @@  discard block
 block discarded – undo
1230 1230
  * @return array
1231 1231
  */
1232 1232
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1233
-	$user = $via_proxy = $proxy_user = '';
1234
-	$fopen = false;
1235
-
1236
-	$t = @parse_url($url);
1237
-	$host = $t['host'];
1238
-	if ($t['scheme'] == 'http') {
1239
-		$scheme = 'http';
1240
-		$noproxy = '';
1241
-	} elseif ($t['scheme'] == 'https') {
1242
-		$scheme = 'ssl';
1243
-		$noproxy = 'ssl://';
1244
-		if (!isset($t['port']) || !($port = $t['port'])) {
1245
-			$t['port'] = 443;
1246
-		}
1247
-	} else {
1248
-		$scheme = $t['scheme'];
1249
-		$noproxy = $scheme . '://';
1250
-	}
1251
-	if (isset($t['user'])) {
1252
-		$user = [$t['user'], $t['pass']];
1253
-	}
1254
-
1255
-	if (!isset($t['port']) || !($port = $t['port'])) {
1256
-		$port = 80;
1257
-	}
1258
-	if (!isset($t['path']) || !($path = $t['path'])) {
1259
-		$path = '/';
1260
-	}
1261
-
1262
-	if (!empty($t['query'])) {
1263
-		$path .= '?' . $t['query'];
1264
-	}
1265
-
1266
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1267
-	if (!$f or !is_resource($f)) {
1268
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1269
-		// ce qui correspond a $f===110
1270
-		if (
1271
-			$f !== 110
1272
-			and !need_proxy($host)
1273
-			and !_request('tester_proxy')
1274
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1275
-		) {
1276
-			$f = @fopen($url, 'rb');
1277
-			spip_log("connexion vers $url par simple fopen", 'distant');
1278
-			$fopen = true;
1279
-		} else {
1280
-			// echec total
1281
-			$f = false;
1282
-		}
1283
-	}
1284
-
1285
-	return [$f, $fopen];
1233
+    $user = $via_proxy = $proxy_user = '';
1234
+    $fopen = false;
1235
+
1236
+    $t = @parse_url($url);
1237
+    $host = $t['host'];
1238
+    if ($t['scheme'] == 'http') {
1239
+        $scheme = 'http';
1240
+        $noproxy = '';
1241
+    } elseif ($t['scheme'] == 'https') {
1242
+        $scheme = 'ssl';
1243
+        $noproxy = 'ssl://';
1244
+        if (!isset($t['port']) || !($port = $t['port'])) {
1245
+            $t['port'] = 443;
1246
+        }
1247
+    } else {
1248
+        $scheme = $t['scheme'];
1249
+        $noproxy = $scheme . '://';
1250
+    }
1251
+    if (isset($t['user'])) {
1252
+        $user = [$t['user'], $t['pass']];
1253
+    }
1254
+
1255
+    if (!isset($t['port']) || !($port = $t['port'])) {
1256
+        $port = 80;
1257
+    }
1258
+    if (!isset($t['path']) || !($path = $t['path'])) {
1259
+        $path = '/';
1260
+    }
1261
+
1262
+    if (!empty($t['query'])) {
1263
+        $path .= '?' . $t['query'];
1264
+    }
1265
+
1266
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1267
+    if (!$f or !is_resource($f)) {
1268
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1269
+        // ce qui correspond a $f===110
1270
+        if (
1271
+            $f !== 110
1272
+            and !need_proxy($host)
1273
+            and !_request('tester_proxy')
1274
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1275
+        ) {
1276
+            $f = @fopen($url, 'rb');
1277
+            spip_log("connexion vers $url par simple fopen", 'distant');
1278
+            $fopen = true;
1279
+        } else {
1280
+            // echec total
1281
+            $f = false;
1282
+        }
1283
+    }
1284
+
1285
+    return [$f, $fopen];
1286 1286
 }
1287 1287
 
1288 1288
 /**
@@ -1317,123 +1317,123 @@  discard block
 block discarded – undo
1317 1317
  *   resource socket vers l'url demandee
1318 1318
  */
1319 1319
 function lance_requete(
1320
-	$method,
1321
-	$scheme,
1322
-	$user,
1323
-	$host,
1324
-	$path,
1325
-	$port,
1326
-	$noproxy,
1327
-	$refuse_gz = false,
1328
-	$referer = '',
1329
-	$datas = '',
1330
-	$vers = 'HTTP/1.0',
1331
-	$date = ''
1320
+    $method,
1321
+    $scheme,
1322
+    $user,
1323
+    $host,
1324
+    $path,
1325
+    $port,
1326
+    $noproxy,
1327
+    $refuse_gz = false,
1328
+    $referer = '',
1329
+    $datas = '',
1330
+    $vers = 'HTTP/1.0',
1331
+    $date = ''
1332 1332
 ) {
1333 1333
 
1334
-	$proxy_user = '';
1335
-	$http_proxy = need_proxy($host);
1336
-	if ($user) {
1337
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1338
-	}
1339
-
1340
-	$connect = '';
1341
-	if ($http_proxy) {
1342
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1343
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1344
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1345
-				. "Host: $path_host\r\n"
1346
-				. "Proxy-Connection: Keep-Alive\r\n";
1347
-		} else {
1348
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1349
-				. (!$user ? '' : "$user@")
1350
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1351
-		}
1352
-		$t2 = @parse_url($http_proxy);
1353
-		$first_host = $t2['host'];
1354
-		$port = ($t2['port'] ?? null) ?: 80;
1355
-		if ($t2['user'] ?? null) {
1356
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1357
-		}
1358
-	} else {
1359
-		$first_host = $noproxy . $host;
1360
-	}
1361
-
1362
-	if ($connect) {
1363
-		$streamContext = stream_context_create([
1364
-			'ssl' => [
1365
-				'verify_peer' => false,
1366
-				'allow_self_signed' => true,
1367
-				'SNI_enabled' => true,
1368
-				'peer_name' => $host,
1369
-			]
1370
-		]);
1371
-		$f = @stream_socket_client(
1372
-			"tcp://$first_host:$port",
1373
-			$errno,
1374
-			$errstr,
1375
-			_INC_DISTANT_CONNECT_TIMEOUT,
1376
-			STREAM_CLIENT_CONNECT,
1377
-			$streamContext
1378
-		);
1379
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1380
-		if (!$f) {
1381
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1382
-			return $errno;
1383
-		}
1384
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1385
-
1386
-		fputs($f, $connect);
1387
-		fputs($f, "\r\n");
1388
-		$res = fread($f, 1024);
1389
-		if (
1390
-			!$res
1391
-			or !count($res = explode(' ', $res))
1392
-			or $res[1] !== '200'
1393
-		) {
1394
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1395
-			fclose($f);
1396
-
1397
-			return false;
1398
-		}
1399
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1400
-		stream_set_blocking($f, true);
1401
-		// envoyer le handshake
1402
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1403
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1404
-	} else {
1405
-		$ntry = 3;
1406
-		do {
1407
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1408
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1409
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1410
-		if (!$f) {
1411
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1412
-
1413
-			return $errno;
1414
-		}
1415
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1416
-	}
1417
-
1418
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1419
-
1420
-	$host_port = $host;
1421
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1422
-		$host_port .= ":$port";
1423
-	}
1424
-	$req = "$method $path $vers\r\n"
1425
-		. "Host: $host_port\r\n"
1426
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1427
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1428
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1429
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1430
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1431
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1432
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1334
+    $proxy_user = '';
1335
+    $http_proxy = need_proxy($host);
1336
+    if ($user) {
1337
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1338
+    }
1339
+
1340
+    $connect = '';
1341
+    if ($http_proxy) {
1342
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1343
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1344
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1345
+                . "Host: $path_host\r\n"
1346
+                . "Proxy-Connection: Keep-Alive\r\n";
1347
+        } else {
1348
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1349
+                . (!$user ? '' : "$user@")
1350
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1351
+        }
1352
+        $t2 = @parse_url($http_proxy);
1353
+        $first_host = $t2['host'];
1354
+        $port = ($t2['port'] ?? null) ?: 80;
1355
+        if ($t2['user'] ?? null) {
1356
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1357
+        }
1358
+    } else {
1359
+        $first_host = $noproxy . $host;
1360
+    }
1361
+
1362
+    if ($connect) {
1363
+        $streamContext = stream_context_create([
1364
+            'ssl' => [
1365
+                'verify_peer' => false,
1366
+                'allow_self_signed' => true,
1367
+                'SNI_enabled' => true,
1368
+                'peer_name' => $host,
1369
+            ]
1370
+        ]);
1371
+        $f = @stream_socket_client(
1372
+            "tcp://$first_host:$port",
1373
+            $errno,
1374
+            $errstr,
1375
+            _INC_DISTANT_CONNECT_TIMEOUT,
1376
+            STREAM_CLIENT_CONNECT,
1377
+            $streamContext
1378
+        );
1379
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1380
+        if (!$f) {
1381
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1382
+            return $errno;
1383
+        }
1384
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1385
+
1386
+        fputs($f, $connect);
1387
+        fputs($f, "\r\n");
1388
+        $res = fread($f, 1024);
1389
+        if (
1390
+            !$res
1391
+            or !count($res = explode(' ', $res))
1392
+            or $res[1] !== '200'
1393
+        ) {
1394
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1395
+            fclose($f);
1396
+
1397
+            return false;
1398
+        }
1399
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1400
+        stream_set_blocking($f, true);
1401
+        // envoyer le handshake
1402
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1403
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1404
+    } else {
1405
+        $ntry = 3;
1406
+        do {
1407
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1408
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1409
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1410
+        if (!$f) {
1411
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1412
+
1413
+            return $errno;
1414
+        }
1415
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1416
+    }
1417
+
1418
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1419
+
1420
+    $host_port = $host;
1421
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1422
+        $host_port .= ":$port";
1423
+    }
1424
+    $req = "$method $path $vers\r\n"
1425
+        . "Host: $host_port\r\n"
1426
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1427
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1428
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1429
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1430
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1431
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1432
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1433 1433
 
1434 1434
 #	spip_log("Requete\n$req", 'distant');
1435
-	fputs($f, $req);
1436
-	fputs($f, $datas ?: "\r\n");
1435
+    fputs($f, $req);
1436
+    fputs($f, $datas ?: "\r\n");
1437 1437
 
1438
-	return $f;
1438
+    return $f;
1439 1439
 }
Please login to merge, or discard this patch.
ecrire/install/etape_ldap2.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -11,89 +11,89 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 function install_etape_ldap2_dist() {
18
-	echo install_debut_html('AUTO', ' onload="document.getElementById(\'suivant\').focus();return false;"');
19
-
20
-	$adresse_ldap = _request('adresse_ldap');
21
-
22
-	$port_ldap = _request('port_ldap');
23
-
24
-	$tls_ldap = _request('tls_ldap');
25
-
26
-	$protocole_ldap = _request('protocole_ldap');
27
-
28
-	$login_ldap = _request('login_ldap');
29
-
30
-	$pass_ldap = _request('pass_ldap');
31
-
32
-	$port_ldap = intval($port_ldap);
33
-
34
-	$tls = false;
35
-
36
-	if ($tls_ldap == 'oui') {
37
-		if ($port_ldap == 636) {
38
-			$adresse_ldap = "ldaps://$adresse_ldap";
39
-		} else {
40
-			$tls = true;
41
-		}
42
-	}
43
-	else {
44
-		$tls_ldap == 'non';
45
-	}
46
-
47
-	// Verifions que l'adresse demandee est valide
48
-	$adresse_ldap = filter_var($adresse_ldap, FILTER_SANITIZE_URL) ?: '';
49
-
50
-	$ldap_link = ldap_connect($adresse_ldap, $port_ldap);
51
-	$erreur = 'ldap_connect(' . spip_htmlspecialchars($adresse_ldap) . ', ' . spip_htmlspecialchars($port_ldap) . ')';
52
-
53
-	if ($ldap_link) {
54
-		if (!ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap)) {
55
-			$protocole_ldap = 2;
56
-			ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap);
57
-		}
58
-		if ($tls === true) {
59
-			if (!ldap_start_tls($ldap_link)) {
60
-				$erreur = 'ldap_start_tls(' . spip_htmlspecialchars($ldap_link)
61
-					. ' ' . spip_htmlspecialchars($adresse_ldap)
62
-					. ', ' . spip_htmlspecialchars($port_ldap) . ')';
63
-				$ldap_link = false;
64
-			}
65
-		}
66
-		if ($ldap_link) {
67
-			$ldap_link = ldap_bind($ldap_link, $login_ldap, $pass_ldap);
68
-			$erreur = "ldap_bind('" . spip_htmlspecialchars($ldap_link)
69
-				. "', '" . spip_htmlspecialchars($login_ldap)
70
-				. "', '" . spip_htmlspecialchars($pass_ldap)
71
-				. "'): " . spip_htmlspecialchars($adresse_ldap)
72
-				. ', ' . spip_htmlspecialchars($port_ldap);
73
-		}
74
-	}
75
-
76
-	if ($ldap_link) {
77
-		echo info_etape(
78
-			_T('titre_connexion_ldap'),
79
-			info_progression_etape(2, 'etape_ldap', 'install/')
80
-		),  _T('info_connexion_ldap_ok');
81
-		echo generer_form_ecrire('install', (
82
-			"\n<input type='hidden' name='etape' value='ldap3' />"
83
-			. "\n<input type='hidden' name='adresse_ldap' value=\"" . spip_htmlspecialchars($adresse_ldap) . '" />'
84
-			. "\n<input type='hidden' name='port_ldap' value=\"" . spip_htmlspecialchars($port_ldap) . '" />'
85
-			. "\n<input type='hidden' name='login_ldap' value=\"" . spip_htmlspecialchars($login_ldap) . '" />'
86
-			. "\n<input type='hidden' name='pass_ldap' value=\"" . spip_htmlspecialchars($pass_ldap) . '" />'
87
-			. "\n<input type='hidden' name='protocole_ldap' value=\"" . spip_htmlspecialchars($protocole_ldap) . '" />'
88
-			. "\n<input type='hidden' name='tls_ldap' value=\"" . spip_htmlspecialchars($tls_ldap) . '" />'
89
-			. bouton_suivant()));
90
-	} else {
91
-		echo info_etape(_T('titre_connexion_ldap')), info_progression_etape(1, 'etape_ldap', 'install/', true),
92
-			"<div class='error'><p>" . _T('avis_connexion_ldap_echec_1') . '</p>',
93
-			'<p>' . _T('avis_connexion_ldap_echec_2') .
94
-			"<br />\n" . _T('avis_connexion_ldap_echec_3') .
95
-			'<br /><br />' . $erreur . '<b> ?</b></p></div>';
96
-	}
97
-
98
-	echo install_fin_html();
18
+    echo install_debut_html('AUTO', ' onload="document.getElementById(\'suivant\').focus();return false;"');
19
+
20
+    $adresse_ldap = _request('adresse_ldap');
21
+
22
+    $port_ldap = _request('port_ldap');
23
+
24
+    $tls_ldap = _request('tls_ldap');
25
+
26
+    $protocole_ldap = _request('protocole_ldap');
27
+
28
+    $login_ldap = _request('login_ldap');
29
+
30
+    $pass_ldap = _request('pass_ldap');
31
+
32
+    $port_ldap = intval($port_ldap);
33
+
34
+    $tls = false;
35
+
36
+    if ($tls_ldap == 'oui') {
37
+        if ($port_ldap == 636) {
38
+            $adresse_ldap = "ldaps://$adresse_ldap";
39
+        } else {
40
+            $tls = true;
41
+        }
42
+    }
43
+    else {
44
+        $tls_ldap == 'non';
45
+    }
46
+
47
+    // Verifions que l'adresse demandee est valide
48
+    $adresse_ldap = filter_var($adresse_ldap, FILTER_SANITIZE_URL) ?: '';
49
+
50
+    $ldap_link = ldap_connect($adresse_ldap, $port_ldap);
51
+    $erreur = 'ldap_connect(' . spip_htmlspecialchars($adresse_ldap) . ', ' . spip_htmlspecialchars($port_ldap) . ')';
52
+
53
+    if ($ldap_link) {
54
+        if (!ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap)) {
55
+            $protocole_ldap = 2;
56
+            ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap);
57
+        }
58
+        if ($tls === true) {
59
+            if (!ldap_start_tls($ldap_link)) {
60
+                $erreur = 'ldap_start_tls(' . spip_htmlspecialchars($ldap_link)
61
+                    . ' ' . spip_htmlspecialchars($adresse_ldap)
62
+                    . ', ' . spip_htmlspecialchars($port_ldap) . ')';
63
+                $ldap_link = false;
64
+            }
65
+        }
66
+        if ($ldap_link) {
67
+            $ldap_link = ldap_bind($ldap_link, $login_ldap, $pass_ldap);
68
+            $erreur = "ldap_bind('" . spip_htmlspecialchars($ldap_link)
69
+                . "', '" . spip_htmlspecialchars($login_ldap)
70
+                . "', '" . spip_htmlspecialchars($pass_ldap)
71
+                . "'): " . spip_htmlspecialchars($adresse_ldap)
72
+                . ', ' . spip_htmlspecialchars($port_ldap);
73
+        }
74
+    }
75
+
76
+    if ($ldap_link) {
77
+        echo info_etape(
78
+            _T('titre_connexion_ldap'),
79
+            info_progression_etape(2, 'etape_ldap', 'install/')
80
+        ),  _T('info_connexion_ldap_ok');
81
+        echo generer_form_ecrire('install', (
82
+            "\n<input type='hidden' name='etape' value='ldap3' />"
83
+            . "\n<input type='hidden' name='adresse_ldap' value=\"" . spip_htmlspecialchars($adresse_ldap) . '" />'
84
+            . "\n<input type='hidden' name='port_ldap' value=\"" . spip_htmlspecialchars($port_ldap) . '" />'
85
+            . "\n<input type='hidden' name='login_ldap' value=\"" . spip_htmlspecialchars($login_ldap) . '" />'
86
+            . "\n<input type='hidden' name='pass_ldap' value=\"" . spip_htmlspecialchars($pass_ldap) . '" />'
87
+            . "\n<input type='hidden' name='protocole_ldap' value=\"" . spip_htmlspecialchars($protocole_ldap) . '" />'
88
+            . "\n<input type='hidden' name='tls_ldap' value=\"" . spip_htmlspecialchars($tls_ldap) . '" />'
89
+            . bouton_suivant()));
90
+    } else {
91
+        echo info_etape(_T('titre_connexion_ldap')), info_progression_etape(1, 'etape_ldap', 'install/', true),
92
+            "<div class='error'><p>" . _T('avis_connexion_ldap_echec_1') . '</p>',
93
+            '<p>' . _T('avis_connexion_ldap_echec_2') .
94
+            "<br />\n" . _T('avis_connexion_ldap_echec_3') .
95
+            '<br /><br />' . $erreur . '<b> ?</b></p></div>';
96
+    }
97
+
98
+    echo install_fin_html();
99 99
 }
Please login to merge, or discard this patch.
ecrire/install/etape_3.php 1 patch
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('inc/headers');
@@ -19,199 +19,199 @@  discard block
 block discarded – undo
19 19
 
20 20
 function install_bases($adresse_db, $login_db, $pass_db, $server_db, $choix_db, $sel_db, $chmod_db) {
21 21
 
22
-	// Prefix des tables :
23
-	// S'il n'est pas defini par mes_options/inc/mutualiser, on va le creer
24
-	// a partir de ce qui est envoye a l'installation
25
-	if (!defined('_INSTALL_TABLE_PREFIX')) {
26
-		$table_prefix = ($GLOBALS['table_prefix'] != 'spip')
27
-			? $GLOBALS['table_prefix']
28
-			: preparer_prefixe_tables(_request('tprefix'));
29
-		// S'il est vide on remet spip
30
-		if (!$table_prefix) {
31
-			$table_prefix = 'spip';
32
-		}
33
-	} else {
34
-		$table_prefix = _INSTALL_TABLE_PREFIX;
35
-	}
36
-
37
-	if (preg_match(',(.*):(.*),', $adresse_db, $r)) {
38
-		[, $adresse_db, $port] = $r;
39
-	} else {
40
-		$port = '';
41
-	}
42
-
43
-	$GLOBALS['connexions'][$server_db]
44
-		= spip_connect_db($adresse_db, $port, $login_db, $pass_db, '', $server_db);
45
-
46
-	$GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
47
-		= $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
48
-
49
-	$fquery = sql_serveur('query', $server_db);
50
-	if ($choix_db == 'new_spip') {
51
-		$re = ',^[a-z_][a-z_0-9-]*$,i';
52
-		if (preg_match($re, $sel_db)) {
53
-			$ok = sql_create_base($sel_db, $server_db);
54
-			if (!$ok) {
55
-				$re = "Impossible de creer la base $re";
56
-				spip_log($re);
57
-				return '<p>' . _T('avis_connexion_erreur_creer_base') . "</p><!--\n$re\n-->";
58
-			}
59
-		} else {
60
-			$re = "Le nom de la base doit correspondre a $re";
61
-			spip_log($re);
62
-
63
-			return '<p>' . _T('avis_connexion_erreur_nom_base') . "</p><!--\n$re\n-->";
64
-		}
65
-	}
66
-
67
-	// on rejoue la connexion apres avoir teste si il faut lui indiquer
68
-	// un sql_mode
69
-	install_mode_appel($server_db, false);
70
-	$GLOBALS['connexions'][$server_db]
71
-		= spip_connect_db($adresse_db, $port, $login_db, $pass_db, $sel_db, $server_db);
72
-
73
-	$GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
74
-		= $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
75
-
76
-	// Completer le tableau decrivant la connexion
77
-
78
-	$GLOBALS['connexions'][$server_db]['prefixe'] = $table_prefix;
79
-	$GLOBALS['connexions'][$server_db]['db'] = $sel_db;
80
-
81
-	$old = sql_showbase($table_prefix . '_meta', $server_db);
82
-	if ($old) {
83
-		$old = sql_fetch($old, $server_db);
84
-	}
85
-	if (!$old) {
86
-		// Si possible, demander au serveur d'envoyer les textes
87
-		// dans le codage std de SPIP,
88
-		$charset = sql_get_charset(_DEFAULT_CHARSET, $server_db);
89
-
90
-		if ($charset) {
91
-			sql_set_charset($charset['charset'], $server_db);
92
-			$GLOBALS['meta']['charset_sql_base'] =
93
-				$charset['charset'];
94
-			$GLOBALS['meta']['charset_collation_sql_base'] =
95
-				$charset['collation'];
96
-			$GLOBALS['meta']['charset_sql_connexion'] =
97
-				$charset['charset'];
98
-			$charsetbase = $charset['charset'];
99
-		} else {
100
-			spip_log(_DEFAULT_CHARSET . ' inconnu du serveur SQL');
101
-			$charsetbase = 'standard';
102
-		}
103
-		spip_log("Creation des tables. Codage $charsetbase");
104
-		creer_base($server_db); // AT LAST
105
-		// memoriser avec quel charset on l'a creee
106
-
107
-		if ($charset) {
108
-			$t = [
109
-				'nom' => 'charset_sql_base',
110
-				'valeur' => $charset['charset'],
111
-				'impt' => 'non'
112
-			];
113
-			@sql_insertq('spip_meta', $t, [], $server_db);
114
-			$t['nom'] = 'charset_collation_sql_base';
115
-			$t['valeur'] = $charset['collation'];
116
-			@sql_insertq('spip_meta', $t, [], $server_db);
117
-			$t['nom'] = 'charset_sql_connexion';
118
-			$t['valeur'] = $charset['charset'];
119
-			@sql_insertq('spip_meta', $t, [], $server_db);
120
-		}
121
-		$t = [
122
-			'nom' => 'version_installee',
123
-			'valeur' => $GLOBALS['spip_version_base'],
124
-			'impt' => 'non'
125
-		];
126
-		@sql_insertq('spip_meta', $t, [], $server_db);
127
-		$t['nom'] = 'nouvelle_install';
128
-		$t['valeur'] = 1;
129
-		@sql_insertq('spip_meta', $t, [], $server_db);
130
-		// positionner la langue par defaut du site si un cookie de lang a ete mis
131
-		if (isset($_COOKIE['spip_lang_ecrire'])) {
132
-			@sql_insertq(
133
-				'spip_meta',
134
-				['nom' => 'langue_site', 'valeur' => $_COOKIE['spip_lang_ecrire']],
135
-				[],
136
-				$server_db
137
-			);
138
-		}
139
-	} else {
140
-		// pour recreer les tables disparues au besoin
141
-		spip_log('Table des Meta deja la. Verification des autres.');
142
-		creer_base($server_db);
143
-		$fupdateq = sql_serveur('updateq', $server_db);
144
-
145
-		$r = $fquery("SELECT valeur FROM spip_meta WHERE nom='version_installee'", $server_db);
146
-
147
-		if ($r) {
148
-			$r = sql_fetch($r, $server_db);
149
-		}
150
-		$version_installee = !$r ? 0 : (double)$r['valeur'];
151
-		if (!$version_installee or ($GLOBALS['spip_version_base'] < $version_installee)) {
152
-			$fupdateq(
153
-				'spip_meta',
154
-				['valeur' => $GLOBALS['spip_version_base'], 'impt' => 'non'],
155
-				"nom='version_installee'",
156
-				'',
157
-				$server_db
158
-			);
159
-			spip_log('nouvelle version installee: ' . $GLOBALS['spip_version_base']);
160
-		}
161
-		// eliminer la derniere operation d'admin mal terminee
162
-		// notamment la mise a jour
163
-		@$fquery("DELETE FROM spip_meta WHERE nom='import_all' OR  nom='admin'", $server_db);
164
-	}
165
-
166
-	// recuperer le charset de la connexion dans les meta
167
-	$charset = '';
168
-	$r = $fquery("SELECT valeur FROM spip_meta WHERE nom='charset_sql_connexion'", $server_db);
169
-	if ($r) {
170
-		$r = sql_fetch($r, $server_db);
171
-	}
172
-	if ($r) {
173
-		$charset = $r['valeur'];
174
-	}
175
-
176
-	$ligne_rappel = install_mode_appel($server_db);
177
-
178
-	$result_ok = @$fquery('SELECT COUNT(*) FROM spip_meta', $server_db);
179
-	if (!$result_ok) {
180
-		return "<!--\nvielle = $old rappel= $ligne_rappel\n-->";
181
-	}
182
-
183
-	if ($chmod_db) {
184
-		install_fichier_connexion(
185
-			_FILE_CHMOD_TMP,
186
-			"if (!defined('_SPIP_CHMOD')) define('_SPIP_CHMOD', " . sprintf('0%3o', $chmod_db) . ");\n"
187
-		);
188
-	}
189
-
190
-	// si ce fichier existe a cette etape c'est qu'il provient
191
-	// d'une installation qui ne l'a pas cree correctement.
192
-	// Le supprimer pour que _FILE_CONNECT_TMP prime.
193
-
194
-	if (_FILE_CONNECT and file_exists(_FILE_CONNECT)) {
195
-		spip_unlink(_FILE_CONNECT);
196
-	}
197
-
198
-	install_fichier_connexion(
199
-		_FILE_CONNECT_TMP,
200
-		$ligne_rappel
201
-		. install_connexion(
202
-			$adresse_db,
203
-			$port,
204
-			$login_db,
205
-			$pass_db,
206
-			$sel_db,
207
-			$server_db,
208
-			$table_prefix,
209
-			'',
210
-			$charset
211
-		)
212
-	);
213
-
214
-	return '';
22
+    // Prefix des tables :
23
+    // S'il n'est pas defini par mes_options/inc/mutualiser, on va le creer
24
+    // a partir de ce qui est envoye a l'installation
25
+    if (!defined('_INSTALL_TABLE_PREFIX')) {
26
+        $table_prefix = ($GLOBALS['table_prefix'] != 'spip')
27
+            ? $GLOBALS['table_prefix']
28
+            : preparer_prefixe_tables(_request('tprefix'));
29
+        // S'il est vide on remet spip
30
+        if (!$table_prefix) {
31
+            $table_prefix = 'spip';
32
+        }
33
+    } else {
34
+        $table_prefix = _INSTALL_TABLE_PREFIX;
35
+    }
36
+
37
+    if (preg_match(',(.*):(.*),', $adresse_db, $r)) {
38
+        [, $adresse_db, $port] = $r;
39
+    } else {
40
+        $port = '';
41
+    }
42
+
43
+    $GLOBALS['connexions'][$server_db]
44
+        = spip_connect_db($adresse_db, $port, $login_db, $pass_db, '', $server_db);
45
+
46
+    $GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
47
+        = $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
48
+
49
+    $fquery = sql_serveur('query', $server_db);
50
+    if ($choix_db == 'new_spip') {
51
+        $re = ',^[a-z_][a-z_0-9-]*$,i';
52
+        if (preg_match($re, $sel_db)) {
53
+            $ok = sql_create_base($sel_db, $server_db);
54
+            if (!$ok) {
55
+                $re = "Impossible de creer la base $re";
56
+                spip_log($re);
57
+                return '<p>' . _T('avis_connexion_erreur_creer_base') . "</p><!--\n$re\n-->";
58
+            }
59
+        } else {
60
+            $re = "Le nom de la base doit correspondre a $re";
61
+            spip_log($re);
62
+
63
+            return '<p>' . _T('avis_connexion_erreur_nom_base') . "</p><!--\n$re\n-->";
64
+        }
65
+    }
66
+
67
+    // on rejoue la connexion apres avoir teste si il faut lui indiquer
68
+    // un sql_mode
69
+    install_mode_appel($server_db, false);
70
+    $GLOBALS['connexions'][$server_db]
71
+        = spip_connect_db($adresse_db, $port, $login_db, $pass_db, $sel_db, $server_db);
72
+
73
+    $GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']]
74
+        = $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']];
75
+
76
+    // Completer le tableau decrivant la connexion
77
+
78
+    $GLOBALS['connexions'][$server_db]['prefixe'] = $table_prefix;
79
+    $GLOBALS['connexions'][$server_db]['db'] = $sel_db;
80
+
81
+    $old = sql_showbase($table_prefix . '_meta', $server_db);
82
+    if ($old) {
83
+        $old = sql_fetch($old, $server_db);
84
+    }
85
+    if (!$old) {
86
+        // Si possible, demander au serveur d'envoyer les textes
87
+        // dans le codage std de SPIP,
88
+        $charset = sql_get_charset(_DEFAULT_CHARSET, $server_db);
89
+
90
+        if ($charset) {
91
+            sql_set_charset($charset['charset'], $server_db);
92
+            $GLOBALS['meta']['charset_sql_base'] =
93
+                $charset['charset'];
94
+            $GLOBALS['meta']['charset_collation_sql_base'] =
95
+                $charset['collation'];
96
+            $GLOBALS['meta']['charset_sql_connexion'] =
97
+                $charset['charset'];
98
+            $charsetbase = $charset['charset'];
99
+        } else {
100
+            spip_log(_DEFAULT_CHARSET . ' inconnu du serveur SQL');
101
+            $charsetbase = 'standard';
102
+        }
103
+        spip_log("Creation des tables. Codage $charsetbase");
104
+        creer_base($server_db); // AT LAST
105
+        // memoriser avec quel charset on l'a creee
106
+
107
+        if ($charset) {
108
+            $t = [
109
+                'nom' => 'charset_sql_base',
110
+                'valeur' => $charset['charset'],
111
+                'impt' => 'non'
112
+            ];
113
+            @sql_insertq('spip_meta', $t, [], $server_db);
114
+            $t['nom'] = 'charset_collation_sql_base';
115
+            $t['valeur'] = $charset['collation'];
116
+            @sql_insertq('spip_meta', $t, [], $server_db);
117
+            $t['nom'] = 'charset_sql_connexion';
118
+            $t['valeur'] = $charset['charset'];
119
+            @sql_insertq('spip_meta', $t, [], $server_db);
120
+        }
121
+        $t = [
122
+            'nom' => 'version_installee',
123
+            'valeur' => $GLOBALS['spip_version_base'],
124
+            'impt' => 'non'
125
+        ];
126
+        @sql_insertq('spip_meta', $t, [], $server_db);
127
+        $t['nom'] = 'nouvelle_install';
128
+        $t['valeur'] = 1;
129
+        @sql_insertq('spip_meta', $t, [], $server_db);
130
+        // positionner la langue par defaut du site si un cookie de lang a ete mis
131
+        if (isset($_COOKIE['spip_lang_ecrire'])) {
132
+            @sql_insertq(
133
+                'spip_meta',
134
+                ['nom' => 'langue_site', 'valeur' => $_COOKIE['spip_lang_ecrire']],
135
+                [],
136
+                $server_db
137
+            );
138
+        }
139
+    } else {
140
+        // pour recreer les tables disparues au besoin
141
+        spip_log('Table des Meta deja la. Verification des autres.');
142
+        creer_base($server_db);
143
+        $fupdateq = sql_serveur('updateq', $server_db);
144
+
145
+        $r = $fquery("SELECT valeur FROM spip_meta WHERE nom='version_installee'", $server_db);
146
+
147
+        if ($r) {
148
+            $r = sql_fetch($r, $server_db);
149
+        }
150
+        $version_installee = !$r ? 0 : (double)$r['valeur'];
151
+        if (!$version_installee or ($GLOBALS['spip_version_base'] < $version_installee)) {
152
+            $fupdateq(
153
+                'spip_meta',
154
+                ['valeur' => $GLOBALS['spip_version_base'], 'impt' => 'non'],
155
+                "nom='version_installee'",
156
+                '',
157
+                $server_db
158
+            );
159
+            spip_log('nouvelle version installee: ' . $GLOBALS['spip_version_base']);
160
+        }
161
+        // eliminer la derniere operation d'admin mal terminee
162
+        // notamment la mise a jour
163
+        @$fquery("DELETE FROM spip_meta WHERE nom='import_all' OR  nom='admin'", $server_db);
164
+    }
165
+
166
+    // recuperer le charset de la connexion dans les meta
167
+    $charset = '';
168
+    $r = $fquery("SELECT valeur FROM spip_meta WHERE nom='charset_sql_connexion'", $server_db);
169
+    if ($r) {
170
+        $r = sql_fetch($r, $server_db);
171
+    }
172
+    if ($r) {
173
+        $charset = $r['valeur'];
174
+    }
175
+
176
+    $ligne_rappel = install_mode_appel($server_db);
177
+
178
+    $result_ok = @$fquery('SELECT COUNT(*) FROM spip_meta', $server_db);
179
+    if (!$result_ok) {
180
+        return "<!--\nvielle = $old rappel= $ligne_rappel\n-->";
181
+    }
182
+
183
+    if ($chmod_db) {
184
+        install_fichier_connexion(
185
+            _FILE_CHMOD_TMP,
186
+            "if (!defined('_SPIP_CHMOD')) define('_SPIP_CHMOD', " . sprintf('0%3o', $chmod_db) . ");\n"
187
+        );
188
+    }
189
+
190
+    // si ce fichier existe a cette etape c'est qu'il provient
191
+    // d'une installation qui ne l'a pas cree correctement.
192
+    // Le supprimer pour que _FILE_CONNECT_TMP prime.
193
+
194
+    if (_FILE_CONNECT and file_exists(_FILE_CONNECT)) {
195
+        spip_unlink(_FILE_CONNECT);
196
+    }
197
+
198
+    install_fichier_connexion(
199
+        _FILE_CONNECT_TMP,
200
+        $ligne_rappel
201
+        . install_connexion(
202
+            $adresse_db,
203
+            $port,
204
+            $login_db,
205
+            $pass_db,
206
+            $sel_db,
207
+            $server_db,
208
+            $table_prefix,
209
+            '',
210
+            $charset
211
+        )
212
+    );
213
+
214
+    return '';
215 215
 }
216 216
 
217 217
 /**
@@ -226,166 +226,166 @@  discard block
 block discarded – undo
226 226
  * @return string Le préfixe corrigé
227 227
  */
228 228
 function preparer_prefixe_tables($prefixe) {
229
-	return trim(preg_replace(',^[0-9]+,', '', preg_replace(',[^a-z0-9],', '', strtolower($prefixe))));
229
+    return trim(preg_replace(',^[0-9]+,', '', preg_replace(',[^a-z0-9],', '', strtolower($prefixe))));
230 230
 }
231 231
 
232 232
 function install_propose_ldap() {
233
-	return generer_form_ecrire('install', (
234
-	fieldset(
235
-		_T('info_authentification_externe'),
236
-		[
237
-			'etape' => [
238
-				'label' => _T('texte_annuaire_ldap_1'),
239
-				'valeur' => 'ldap1',
240
-				'hidden' => true
241
-			]
242
-		],
243
-		bouton_suivant(_T('bouton_acces_ldap'))
244
-	)));
233
+    return generer_form_ecrire('install', (
234
+    fieldset(
235
+        _T('info_authentification_externe'),
236
+        [
237
+            'etape' => [
238
+                'label' => _T('texte_annuaire_ldap_1'),
239
+                'valeur' => 'ldap1',
240
+                'hidden' => true
241
+            ]
242
+        ],
243
+        bouton_suivant(_T('bouton_acces_ldap'))
244
+    )));
245 245
 }
246 246
 
247 247
 
248 248
 function install_premier_auteur($email, $login, $nom, $pass, $hidden, $auteur_obligatoire) {
249
-	return info_progression_etape(3, 'etape_', 'install/') .
250
-	info_etape(
251
-		_T('info_informations_personnelles'),
252
-		'<b>' . _T('texte_informations_personnelles_1') . '</b>' .
253
-		aider('install5', true) .
254
-		'<p>' .
255
-		($auteur_obligatoire ?
256
-			''
257
-			:
258
-			_T('texte_informations_personnelles_2') . ' ' . _T('info_laisser_champs_vides')
259
-		)
260
-	)
261
-	. generer_form_ecrire('install', (
262
-		"\n<input type='hidden' name='etape' value='3b' />"
263
-		. $hidden
264
-		. fieldset(
265
-			_T('info_identification_publique'),
266
-			[
267
-				'nom' => [
268
-					'label' => '<b>' . _T('entree_signature') . "</b><br />\n" . _T('entree_nom_pseudo_1') . "\n",
269
-					'valeur' => $nom,
270
-					'required' => $auteur_obligatoire,
271
-				],
272
-				'email' => [
273
-					'label' => '<b>' . _T('entree_adresse_email') . "</b>\n",
274
-					'valeur' => $email,
275
-				]
276
-			]
277
-		)
278
-
279
-		. fieldset(
280
-			_T('entree_identifiants_connexion'),
281
-			[
282
-				'login' => [
283
-					'label' => '<b>' . _T('entree_login') . "</b><br />\n" . _T(
284
-						'info_login_trop_court_car_pluriel',
285
-						['nb' => _LOGIN_TROP_COURT]
286
-					) . "\n",
287
-					'valeur' => $login,
288
-					'required' => $auteur_obligatoire,
289
-				],
290
-				'pass' => [
291
-					'label' => '<b>' . _T('entree_mot_passe') . "</b><br />\n" . _T(
292
-						'info_passe_trop_court_car_pluriel',
293
-						['nb' => _PASS_LONGUEUR_MINI]
294
-					) . "\n",
295
-					'valeur' => $pass,
296
-					'required' => $auteur_obligatoire,
297
-				],
298
-				'pass_verif' => [
299
-					'label' => '<b>' . _T('info_confirmer_passe') . "</b><br />\n",
300
-					'valeur' => $pass,
301
-					'required' => $auteur_obligatoire,
302
-				]
303
-			]
304
-		)
305
-		. bouton_suivant()));
249
+    return info_progression_etape(3, 'etape_', 'install/') .
250
+    info_etape(
251
+        _T('info_informations_personnelles'),
252
+        '<b>' . _T('texte_informations_personnelles_1') . '</b>' .
253
+        aider('install5', true) .
254
+        '<p>' .
255
+        ($auteur_obligatoire ?
256
+            ''
257
+            :
258
+            _T('texte_informations_personnelles_2') . ' ' . _T('info_laisser_champs_vides')
259
+        )
260
+    )
261
+    . generer_form_ecrire('install', (
262
+        "\n<input type='hidden' name='etape' value='3b' />"
263
+        . $hidden
264
+        . fieldset(
265
+            _T('info_identification_publique'),
266
+            [
267
+                'nom' => [
268
+                    'label' => '<b>' . _T('entree_signature') . "</b><br />\n" . _T('entree_nom_pseudo_1') . "\n",
269
+                    'valeur' => $nom,
270
+                    'required' => $auteur_obligatoire,
271
+                ],
272
+                'email' => [
273
+                    'label' => '<b>' . _T('entree_adresse_email') . "</b>\n",
274
+                    'valeur' => $email,
275
+                ]
276
+            ]
277
+        )
278
+
279
+        . fieldset(
280
+            _T('entree_identifiants_connexion'),
281
+            [
282
+                'login' => [
283
+                    'label' => '<b>' . _T('entree_login') . "</b><br />\n" . _T(
284
+                        'info_login_trop_court_car_pluriel',
285
+                        ['nb' => _LOGIN_TROP_COURT]
286
+                    ) . "\n",
287
+                    'valeur' => $login,
288
+                    'required' => $auteur_obligatoire,
289
+                ],
290
+                'pass' => [
291
+                    'label' => '<b>' . _T('entree_mot_passe') . "</b><br />\n" . _T(
292
+                        'info_passe_trop_court_car_pluriel',
293
+                        ['nb' => _PASS_LONGUEUR_MINI]
294
+                    ) . "\n",
295
+                    'valeur' => $pass,
296
+                    'required' => $auteur_obligatoire,
297
+                ],
298
+                'pass_verif' => [
299
+                    'label' => '<b>' . _T('info_confirmer_passe') . "</b><br />\n",
300
+                    'valeur' => $pass,
301
+                    'required' => $auteur_obligatoire,
302
+                ]
303
+            ]
304
+        )
305
+        . bouton_suivant()));
306 306
 }
307 307
 
308 308
 function install_etape_3_dist() {
309
-	$ldap_present = _request('ldap_present');
310
-
311
-	if (!$ldap_present) {
312
-		$adresse_db = defined('_INSTALL_HOST_DB')
313
-			? _INSTALL_HOST_DB
314
-			: _request('adresse_db');
315
-
316
-		$login_db = defined('_INSTALL_USER_DB')
317
-			? _INSTALL_USER_DB
318
-			: _request('login_db');
319
-
320
-		$pass_db = defined('_INSTALL_PASS_DB')
321
-			? _INSTALL_PASS_DB
322
-			: _request('pass_db');
323
-
324
-		$server_db = defined('_INSTALL_SERVER_DB')
325
-			? _INSTALL_SERVER_DB
326
-			: _request('server_db');
327
-
328
-		$chmod_db = defined('_SPIP_CHMOD')
329
-			? _SPIP_CHMOD
330
-			: _request('chmod');
331
-
332
-		$choix_db = defined('_INSTALL_NAME_DB')
333
-			? _INSTALL_NAME_DB
334
-			: _request('choix_db');
335
-
336
-		$sel_db = ($choix_db == 'new_spip')
337
-			? _request('table_new') : $choix_db;
338
-
339
-		$res = install_bases($adresse_db, $login_db, $pass_db, $server_db, $choix_db, $sel_db, $chmod_db);
340
-
341
-		if ($res) {
342
-			$res = info_progression_etape(2, 'etape_', 'install/', true)
343
-				. "<div class='error'><h3>" . _T('avis_operation_echec') . '</h3>'
344
-				. $res
345
-				. '<p>' . _T('texte_operation_echec') . '</p>'
346
-				. '</div>';
347
-		}
348
-	} else {
349
-		$res = '';
350
-		[$adresse_db, $login_db, $pass_db, $sel_db, $server_db] = analyse_fichier_connection(_FILE_CONNECT_TMP);
351
-		$GLOBALS['connexions'][$server_db] = spip_connect_db($adresse_db, $sel_db, $login_db, $pass_db, $sel_db, $server_db);
352
-	}
353
-
354
-	if (!$res) {
355
-		if (file_exists(_FILE_CONNECT_TMP)) {
356
-			include(_FILE_CONNECT_TMP);
357
-		} else {
358
-			redirige_url_ecrire('install');
359
-		}
360
-
361
-		if (file_exists(_FILE_CHMOD_TMP)) {
362
-			include(_FILE_CHMOD_TMP);
363
-		} else {
364
-			redirige_url_ecrire('install');
365
-		}
366
-
367
-		$hidden = predef_ou_cache($adresse_db, $login_db, $pass_db, $server_db)
368
-			. (defined('_INSTALL_NAME_DB') ? ''
369
-				: "\n<input type='hidden' name='sel_db' value=\"" . spip_htmlspecialchars($sel_db) . '" />');
370
-
371
-		$auteur_obligatoire = ($ldap_present ? 0 : !sql_countsel('spip_auteurs', '', '', '', $server_db));
372
-
373
-		$res = "<div class='success'><b>"
374
-			. _T('info_base_installee')
375
-			. '</b></div>'
376
-			. install_premier_auteur(
377
-				_request('email'),
378
-				_request('login'),
379
-				_request('nom'),
380
-				_request('pass'),
381
-				$hidden,
382
-				$auteur_obligatoire
383
-			)
384
-			. (($ldap_present or !function_exists('ldap_connect'))
385
-				? '' : install_propose_ldap());
386
-	}
387
-
388
-	echo install_debut_html();
389
-	echo $res;
390
-	echo install_fin_html();
309
+    $ldap_present = _request('ldap_present');
310
+
311
+    if (!$ldap_present) {
312
+        $adresse_db = defined('_INSTALL_HOST_DB')
313
+            ? _INSTALL_HOST_DB
314
+            : _request('adresse_db');
315
+
316
+        $login_db = defined('_INSTALL_USER_DB')
317
+            ? _INSTALL_USER_DB
318
+            : _request('login_db');
319
+
320
+        $pass_db = defined('_INSTALL_PASS_DB')
321
+            ? _INSTALL_PASS_DB
322
+            : _request('pass_db');
323
+
324
+        $server_db = defined('_INSTALL_SERVER_DB')
325
+            ? _INSTALL_SERVER_DB
326
+            : _request('server_db');
327
+
328
+        $chmod_db = defined('_SPIP_CHMOD')
329
+            ? _SPIP_CHMOD
330
+            : _request('chmod');
331
+
332
+        $choix_db = defined('_INSTALL_NAME_DB')
333
+            ? _INSTALL_NAME_DB
334
+            : _request('choix_db');
335
+
336
+        $sel_db = ($choix_db == 'new_spip')
337
+            ? _request('table_new') : $choix_db;
338
+
339
+        $res = install_bases($adresse_db, $login_db, $pass_db, $server_db, $choix_db, $sel_db, $chmod_db);
340
+
341
+        if ($res) {
342
+            $res = info_progression_etape(2, 'etape_', 'install/', true)
343
+                . "<div class='error'><h3>" . _T('avis_operation_echec') . '</h3>'
344
+                . $res
345
+                . '<p>' . _T('texte_operation_echec') . '</p>'
346
+                . '</div>';
347
+        }
348
+    } else {
349
+        $res = '';
350
+        [$adresse_db, $login_db, $pass_db, $sel_db, $server_db] = analyse_fichier_connection(_FILE_CONNECT_TMP);
351
+        $GLOBALS['connexions'][$server_db] = spip_connect_db($adresse_db, $sel_db, $login_db, $pass_db, $sel_db, $server_db);
352
+    }
353
+
354
+    if (!$res) {
355
+        if (file_exists(_FILE_CONNECT_TMP)) {
356
+            include(_FILE_CONNECT_TMP);
357
+        } else {
358
+            redirige_url_ecrire('install');
359
+        }
360
+
361
+        if (file_exists(_FILE_CHMOD_TMP)) {
362
+            include(_FILE_CHMOD_TMP);
363
+        } else {
364
+            redirige_url_ecrire('install');
365
+        }
366
+
367
+        $hidden = predef_ou_cache($adresse_db, $login_db, $pass_db, $server_db)
368
+            . (defined('_INSTALL_NAME_DB') ? ''
369
+                : "\n<input type='hidden' name='sel_db' value=\"" . spip_htmlspecialchars($sel_db) . '" />');
370
+
371
+        $auteur_obligatoire = ($ldap_present ? 0 : !sql_countsel('spip_auteurs', '', '', '', $server_db));
372
+
373
+        $res = "<div class='success'><b>"
374
+            . _T('info_base_installee')
375
+            . '</b></div>'
376
+            . install_premier_auteur(
377
+                _request('email'),
378
+                _request('login'),
379
+                _request('nom'),
380
+                _request('pass'),
381
+                $hidden,
382
+                $auteur_obligatoire
383
+            )
384
+            . (($ldap_present or !function_exists('ldap_connect'))
385
+                ? '' : install_propose_ldap());
386
+    }
387
+
388
+    echo install_debut_html();
389
+    echo $res;
390
+    echo install_fin_html();
391 391
 }
Please login to merge, or discard this patch.
ecrire/urls/page.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 defined('URLS_PAGE_EXEMPLE') || define('URLS_PAGE_EXEMPLE', 'spip.php?article12');
@@ -37,23 +37,23 @@  discard block
 block discarded – undo
37 37
  */
38 38
 function urls_page_generer_url_objet_dist(int $id, string $objet, string $args = '', string $ancre = ''): string {
39 39
 
40
-	if ($generer_url_externe = charger_fonction_url($objet, 'defaut')) {
41
-		$url = $generer_url_externe($id, $args, $ancre);
42
-		// une url === null indique "je ne traite pas cette url, appliquez le calcul standard"
43
-		// une url vide est une url vide, ne rien faire de plus
44
-		if (!is_null($url)) {
45
-			return $url;
46
-		}
47
-	}
40
+    if ($generer_url_externe = charger_fonction_url($objet, 'defaut')) {
41
+        $url = $generer_url_externe($id, $args, $ancre);
42
+        // une url === null indique "je ne traite pas cette url, appliquez le calcul standard"
43
+        // une url vide est une url vide, ne rien faire de plus
44
+        if (!is_null($url)) {
45
+            return $url;
46
+        }
47
+    }
48 48
 
49
-	$url = \_debut_urls_page . $objet . \_separateur_urls_page
50
-		. $id . \_terminaison_urls_page;
49
+    $url = \_debut_urls_page . $objet . \_separateur_urls_page
50
+        . $id . \_terminaison_urls_page;
51 51
 
52
-	if ($args) {
53
-		$args = strpos($url, '?') ? "&$args" : "?$args";
54
-	}
52
+    if ($args) {
53
+        $args = strpos($url, '?') ? "&$args" : "?$args";
54
+    }
55 55
 
56
-	return _DIR_RACINE . $url . $args . ($ancre ? "#$ancre" : '');
56
+    return _DIR_RACINE . $url . $args . ($ancre ? "#$ancre" : '');
57 57
 }
58 58
 
59 59
 /**
@@ -69,27 +69,27 @@  discard block
 block discarded – undo
69 69
  */
70 70
 function urls_page_decoder_url_dist(string $url, string $entite, array $contexte = []): array {
71 71
 
72
-	// traiter les injections du type domaine.org/spip.php/cestnimportequoi/ou/encore/plus/rubrique23
73
-	if ($GLOBALS['profondeur_url'] > 0 and $entite == 'sommaire') {
74
-		return [[], '404'];
75
-	}
72
+    // traiter les injections du type domaine.org/spip.php/cestnimportequoi/ou/encore/plus/rubrique23
73
+    if ($GLOBALS['profondeur_url'] > 0 and $entite == 'sommaire') {
74
+        return [[], '404'];
75
+    }
76 76
 
77
-	include_spip('inc/urls');
78
-	$r = nettoyer_url_page($url, $contexte);
79
-	if ($r) {
80
-		array_pop($r); // nettoyer_url_page renvoie un argument de plus inutile ici
81
-		return $r;
82
-	}
77
+    include_spip('inc/urls');
78
+    $r = nettoyer_url_page($url, $contexte);
79
+    if ($r) {
80
+        array_pop($r); // nettoyer_url_page renvoie un argument de plus inutile ici
81
+        return $r;
82
+    }
83 83
 
84
-	/*
84
+    /*
85 85
 	 * Le bloc qui suit sert a faciliter les transitions depuis
86 86
 	 * le mode 'urls-propres' vers les modes 'urls-standard' et 'url-html'
87 87
 	 * Il est inutile de le recopier si vous personnalisez vos URLs
88 88
 	 * et votre .htaccess
89 89
 	 */
90
-	// Si on est revenu en mode html, mais c'est une ancienne url_propre
91
-	// on ne redirige pas, on assume le nouveau contexte (si possible)
92
-	$url_propre = $url ?? $_SERVER['REDIRECT_url_propre'] ?? $_ENV['url_propre'] ?? '';
93
-	return urls_transition_retrouver_anciennes_url_propres($url_propre, $entite, $contexte);
94
-	/* Fin du bloc compatibilite url-propres */
90
+    // Si on est revenu en mode html, mais c'est une ancienne url_propre
91
+    // on ne redirige pas, on assume le nouveau contexte (si possible)
92
+    $url_propre = $url ?? $_SERVER['REDIRECT_url_propre'] ?? $_ENV['url_propre'] ?? '';
93
+    return urls_transition_retrouver_anciennes_url_propres($url_propre, $entite, $contexte);
94
+    /* Fin du bloc compatibilite url-propres */
95 95
 }
Please login to merge, or discard this patch.
ecrire/inc/svg.php 1 patch
Indentation   +458 added lines, -458 removed lines patch added patch discarded remove patch
@@ -17,13 +17,13 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 if (!defined('IMG_SVG')) {
24
-	// complete 	IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP
25
-	define('IMG_SVG', 128);
26
-	define('IMAGETYPE_SVG', 19);
24
+    // complete 	IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP
25
+    define('IMG_SVG', 128);
26
+    define('IMAGETYPE_SVG', 19);
27 27
 }
28 28
 
29 29
 /**
@@ -39,39 +39,39 @@  discard block
 block discarded – undo
39 39
  *   false si on a pas pu charger l'image
40 40
  */
41 41
 function svg_charger($fichier, $maxlen = null) {
42
-	if (strpos($fichier, 'data:image/svg+xml') === 0) {
43
-		$image = explode(';', $fichier, 2);
44
-		$image = end($image);
45
-		if (strpos($image, 'base64,') === 0) {
46
-			$image = base64_decode(substr($image, 7));
47
-		}
48
-		if (strpos($image, '<svg') !== false) {
49
-			return $image;
50
-		}
51
-		// encodage inconnu ou autre format d'image ?
52
-		return false;
53
-	}
54
-	// c'est peut etre deja une image svg ?
55
-	if (strpos($fichier, '<svg') !== false) {
56
-		return $fichier;
57
-	}
58
-	if (!file_exists($fichier)) {
59
-		$fichier  = supprimer_timestamp($fichier);
60
-		if (!file_exists($fichier)) {
61
-			return false;
62
-		}
63
-	}
64
-	if (is_null($maxlen)) {
65
-		$image = file_get_contents($fichier);
66
-	}
67
-	else {
68
-		$image = file_get_contents($fichier, false, null, 0, $maxlen);
69
-	}
70
-	// est-ce bien une image svg ?
71
-	if (strpos($image, '<svg') !== false) {
72
-		return $image;
73
-	}
74
-	return false;
42
+    if (strpos($fichier, 'data:image/svg+xml') === 0) {
43
+        $image = explode(';', $fichier, 2);
44
+        $image = end($image);
45
+        if (strpos($image, 'base64,') === 0) {
46
+            $image = base64_decode(substr($image, 7));
47
+        }
48
+        if (strpos($image, '<svg') !== false) {
49
+            return $image;
50
+        }
51
+        // encodage inconnu ou autre format d'image ?
52
+        return false;
53
+    }
54
+    // c'est peut etre deja une image svg ?
55
+    if (strpos($fichier, '<svg') !== false) {
56
+        return $fichier;
57
+    }
58
+    if (!file_exists($fichier)) {
59
+        $fichier  = supprimer_timestamp($fichier);
60
+        if (!file_exists($fichier)) {
61
+            return false;
62
+        }
63
+    }
64
+    if (is_null($maxlen)) {
65
+        $image = file_get_contents($fichier);
66
+    }
67
+    else {
68
+        $image = file_get_contents($fichier, false, null, 0, $maxlen);
69
+    }
70
+    // est-ce bien une image svg ?
71
+    if (strpos($image, '<svg') !== false) {
72
+        return $image;
73
+    }
74
+    return false;
75 75
 }
76 76
 
77 77
 /**
@@ -80,28 +80,28 @@  discard block
 block discarded – undo
80 80
  * @return array|bool
81 81
  */
82 82
 function svg_lire_balise_svg($fichier) {
83
-	if (!$debut_fichier = svg_charger($fichier, 4096)) {
84
-		return false;
85
-	}
86
-
87
-	if (($ps = stripos($debut_fichier, '<svg')) !== false) {
88
-		$pe = stripos($debut_fichier, '>', $ps);
89
-		$balise_svg = substr($debut_fichier, $ps, $pe - $ps + 1);
90
-
91
-		if (preg_match_all(',([\w:\-]+)=,Uims', $balise_svg, $matches)) {
92
-			if (!function_exists('extraire_attribut')) {
93
-				include_spip('inc/filtres');
94
-			}
95
-			$attributs = [];
96
-			foreach ($matches[1] as $att) {
97
-				$attributs[$att] = extraire_attribut($balise_svg, $att);
98
-			}
99
-
100
-			return [$balise_svg, $attributs];
101
-		}
102
-	}
103
-
104
-	return false;
83
+    if (!$debut_fichier = svg_charger($fichier, 4096)) {
84
+        return false;
85
+    }
86
+
87
+    if (($ps = stripos($debut_fichier, '<svg')) !== false) {
88
+        $pe = stripos($debut_fichier, '>', $ps);
89
+        $balise_svg = substr($debut_fichier, $ps, $pe - $ps + 1);
90
+
91
+        if (preg_match_all(',([\w:\-]+)=,Uims', $balise_svg, $matches)) {
92
+            if (!function_exists('extraire_attribut')) {
93
+                include_spip('inc/filtres');
94
+            }
95
+            $attributs = [];
96
+            foreach ($matches[1] as $att) {
97
+                $attributs[$att] = extraire_attribut($balise_svg, $att);
98
+            }
99
+
100
+            return [$balise_svg, $attributs];
101
+        }
102
+    }
103
+
104
+    return false;
105 105
 }
106 106
 
107 107
 /**
@@ -111,12 +111,12 @@  discard block
 block discarded – undo
111 111
  */
112 112
 function svg_lire_attributs($img) {
113 113
 
114
-	if ($svg_infos = svg_lire_balise_svg($img)) {
115
-		[$balise_svg, $attributs] = $svg_infos;
116
-		return $attributs;
117
-	}
114
+    if ($svg_infos = svg_lire_balise_svg($img)) {
115
+        [$balise_svg, $attributs] = $svg_infos;
116
+        return $attributs;
117
+    }
118 118
 
119
-	return false;
119
+    return false;
120 120
 }
121 121
 
122 122
 /**
@@ -126,38 +126,38 @@  discard block
 block discarded – undo
126 126
  * @return bool|float|int
127 127
  */
128 128
 function svg_dimension_to_pixels($dimension, $precision = 2) {
129
-	if (preg_match(',^(-?\d+(\.\d+)?)([^\d]*),i', trim($dimension), $m)) {
130
-		switch (strtolower($m[2])) {
131
-			case '%':
132
-				// on ne sait pas faire :(
133
-				return false;
134
-				break;
135
-			case 'em':
136
-				return round($m[1] * 16, $precision); // 16px font-size par defaut
137
-				break;
138
-			case 'ex':
139
-				return round($m[1] * 16, $precision); // 16px font-size par defaut
140
-				break;
141
-			case 'pc':
142
-				return round($m[1] * 16, $precision); // 1/6 inch = 96px/6 in CSS
143
-				break;
144
-			case 'cm':
145
-				return round($m[1] * 96 / 2.54, $precision); // 96px / 2.54cm;
146
-				break;
147
-			case 'mm':
148
-				return round($m[1] * 96 / 25.4, $precision); // 96px / 25.4mm;
149
-				break;
150
-			case 'in':
151
-				return round($m[1] * 96, $precision); // 1 inch = 96px in CSS
152
-				break;
153
-			case 'px':
154
-			case 'pt':
155
-			default:
156
-				return $m[1];
157
-				break;
158
-		}
159
-	}
160
-	return false;
129
+    if (preg_match(',^(-?\d+(\.\d+)?)([^\d]*),i', trim($dimension), $m)) {
130
+        switch (strtolower($m[2])) {
131
+            case '%':
132
+                // on ne sait pas faire :(
133
+                return false;
134
+                break;
135
+            case 'em':
136
+                return round($m[1] * 16, $precision); // 16px font-size par defaut
137
+                break;
138
+            case 'ex':
139
+                return round($m[1] * 16, $precision); // 16px font-size par defaut
140
+                break;
141
+            case 'pc':
142
+                return round($m[1] * 16, $precision); // 1/6 inch = 96px/6 in CSS
143
+                break;
144
+            case 'cm':
145
+                return round($m[1] * 96 / 2.54, $precision); // 96px / 2.54cm;
146
+                break;
147
+            case 'mm':
148
+                return round($m[1] * 96 / 25.4, $precision); // 96px / 25.4mm;
149
+                break;
150
+            case 'in':
151
+                return round($m[1] * 96, $precision); // 1 inch = 96px in CSS
152
+                break;
153
+            case 'px':
154
+            case 'pt':
155
+            default:
156
+                return $m[1];
157
+                break;
158
+        }
159
+    }
160
+    return false;
161 161
 }
162 162
 
163 163
 /**
@@ -168,15 +168,15 @@  discard block
 block discarded – undo
168 168
  * @return string
169 169
  */
170 170
 function svg_change_balise_svg($svg, $old_balise_svg, $attributs) {
171
-	$new_balise_svg = '<svg';
172
-	foreach ($attributs as $k => $v) {
173
-		$new_balise_svg .= " $k=\"" . entites_html($v) . '"';
174
-	}
175
-	$new_balise_svg .= '>';
176
-
177
-	$p = strpos($svg, $old_balise_svg);
178
-	$svg = substr_replace($svg, $new_balise_svg, $p, strlen($old_balise_svg));
179
-	return $svg;
171
+    $new_balise_svg = '<svg';
172
+    foreach ($attributs as $k => $v) {
173
+        $new_balise_svg .= " $k=\"" . entites_html($v) . '"';
174
+    }
175
+    $new_balise_svg .= '>';
176
+
177
+    $p = strpos($svg, $old_balise_svg);
178
+    $svg = substr_replace($svg, $new_balise_svg, $p, strlen($old_balise_svg));
179
+    return $svg;
180 180
 }
181 181
 
182 182
 /**
@@ -188,15 +188,15 @@  discard block
 block discarded – undo
188 188
  */
189 189
 function svg_insert_shapes($svg, $shapes, $start = true) {
190 190
 
191
-	if ($start === false or $start === 'end') {
192
-		$svg = str_replace('</svg>', $shapes . '</svg>', $svg);
193
-	}
194
-	else {
195
-		$p = stripos($svg, '<svg');
196
-		$p = strpos($svg, '>', $p);
197
-		$svg = substr_replace($svg, $shapes, $p + 1, 0);
198
-	}
199
-	return $svg;
191
+    if ($start === false or $start === 'end') {
192
+        $svg = str_replace('</svg>', $shapes . '</svg>', $svg);
193
+    }
194
+    else {
195
+        $p = stripos($svg, '<svg');
196
+        $p = strpos($svg, '>', $p);
197
+        $svg = substr_replace($svg, $shapes, $p + 1, 0);
198
+    }
199
+    return $svg;
200 200
 }
201 201
 
202 202
 /**
@@ -209,13 +209,13 @@  discard block
 block discarded – undo
209 209
  * @return string
210 210
  */
211 211
 function svg_clip_in_box($svg, $x, $y, $width, $height) {
212
-	$rect = "<rect x=\"$x\" y=\"$y\" width=\"$width\" height=\"$height\" />";
213
-	$id = 'clip-' . substr(md5($rect . strlen($svg)), 0, 8);
214
-	$clippath = "<clipPath id=\"$id\">$rect</clipPath>";
215
-	$g = "<g clip-path=\"url(#$id)\">";
216
-	$svg = svg_insert_shapes($svg, $clippath . $g);
217
-	$svg = svg_insert_shapes($svg, '</g>', false);
218
-	return $svg;
212
+    $rect = "<rect x=\"$x\" y=\"$y\" width=\"$width\" height=\"$height\" />";
213
+    $id = 'clip-' . substr(md5($rect . strlen($svg)), 0, 8);
214
+    $clippath = "<clipPath id=\"$id\">$rect</clipPath>";
215
+    $g = "<g clip-path=\"url(#$id)\">";
216
+    $svg = svg_insert_shapes($svg, $clippath . $g);
217
+    $svg = svg_insert_shapes($svg, '</g>', false);
218
+    return $svg;
219 219
 }
220 220
 
221 221
 /**
@@ -226,22 +226,22 @@  discard block
 block discarded – undo
226 226
  * @return bool|string
227 227
  */
228 228
 function svg_redimensionner($img, $new_width, $new_height) {
229
-	if (
230
-		$svg = svg_charger($img)
231
-		and $svg_infos = svg_lire_balise_svg($svg)
232
-	) {
233
-		[$balise_svg, $attributs] = $svg_infos;
234
-		if (!isset($attributs['viewBox'])) {
235
-			$attributs['viewBox'] = '0 0 ' . $attributs['width'] . ' ' . $attributs['height'];
236
-		}
237
-		$attributs['width'] = strval($new_width);
238
-		$attributs['height'] = strval($new_height);
239
-
240
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
241
-		return $svg;
242
-	}
243
-
244
-	return $img;
229
+    if (
230
+        $svg = svg_charger($img)
231
+        and $svg_infos = svg_lire_balise_svg($svg)
232
+    ) {
233
+        [$balise_svg, $attributs] = $svg_infos;
234
+        if (!isset($attributs['viewBox'])) {
235
+            $attributs['viewBox'] = '0 0 ' . $attributs['width'] . ' ' . $attributs['height'];
236
+        }
237
+        $attributs['width'] = strval($new_width);
238
+        $attributs['height'] = strval($new_height);
239
+
240
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
241
+        return $svg;
242
+    }
243
+
244
+    return $img;
245 245
 }
246 246
 
247 247
 /**
@@ -250,15 +250,15 @@  discard block
 block discarded – undo
250 250
  * @return string
251 251
  */
252 252
 function svg_couleur_to_hexa($couleur) {
253
-	if (strpos($couleur, 'rgb(') === 0) {
254
-		$c = explode(',', substr($couleur, 4));
255
-		$couleur = _couleur_dec_to_hex(intval($c[0]), intval($c[1]), intval($c[2]));
256
-	}
257
-	else {
258
-		$couleur = couleur_html_to_hex($couleur);
259
-	}
260
-	$couleur = '#' . ltrim($couleur, '#');
261
-	return $couleur;
253
+    if (strpos($couleur, 'rgb(') === 0) {
254
+        $c = explode(',', substr($couleur, 4));
255
+        $couleur = _couleur_dec_to_hex(intval($c[0]), intval($c[1]), intval($c[2]));
256
+    }
257
+    else {
258
+        $couleur = couleur_html_to_hex($couleur);
259
+    }
260
+    $couleur = '#' . ltrim($couleur, '#');
261
+    return $couleur;
262 262
 }
263 263
 
264 264
 /**
@@ -267,11 +267,11 @@  discard block
 block discarded – undo
267 267
  * @return array
268 268
  */
269 269
 function svg_couleur_to_rgb($couleur) {
270
-	if (strpos($couleur, 'rgb(') === 0) {
271
-		$c = explode(',', substr($couleur, 4));
272
-		return ['red' => intval($c[0]),'green' => intval($c[1]),'blue' => intval($c[2])];
273
-	}
274
-	return _couleur_hex_to_dec($couleur);
270
+    if (strpos($couleur, 'rgb(') === 0) {
271
+        $c = explode(',', substr($couleur, 4));
272
+        return ['red' => intval($c[0]),'green' => intval($c[1]),'blue' => intval($c[2])];
273
+    }
274
+    return _couleur_hex_to_dec($couleur);
275 275
 }
276 276
 
277 277
 
@@ -281,80 +281,80 @@  discard block
 block discarded – undo
281 281
  * @return array
282 282
  */
283 283
 function svg_getimagesize_from_attr($attributs) {
284
-	$width = 350; // default width
285
-	$height = 150; // default height
286
-
287
-	$viewBox = "0 0 $width $height";
288
-	if (isset($attributs['viewBox'])) {
289
-		$viewBox = $attributs['viewBox'];
290
-		$viewBox = preg_replace(',\s+,', ' ', $viewBox);
291
-	}
292
-	// et on la convertit en px
293
-	$viewBox = explode(' ', $viewBox);
294
-	$viewBox = array_map('svg_dimension_to_pixels', $viewBox);
295
-	if (!$viewBox[2]) {
296
-		$viewBox[2] = $width;
297
-	}
298
-	if (!$viewBox[3]) {
299
-		$viewBox[3] = $height;
300
-	}
301
-
302
-	$coeff = 1;
303
-	if (
304
-		isset($attributs['width'])
305
-		and $w = svg_dimension_to_pixels($attributs['width'])
306
-	) {
307
-		$width = $w;
308
-		// si on avait pas de viewBox, la construire a partir de ce width
309
-		if (empty($attributs['viewBox'])) {
310
-			$viewBox[2] = $width;
311
-			// si pas de height valide, on suppose l'image carree
312
-			$viewBox[3] = $width;
313
-		}
314
-	}
315
-	else {
316
-		// si on recupere la taille de la viewbox mais si la viewbox est petite on met un multiplicateur pour la taille finale
317
-		$width = $viewBox[2];
318
-		if ($width < 1) {
319
-			$coeff = max($coeff, 1000);
320
-		}
321
-		elseif ($width < 10) {
322
-			$coeff = max($coeff, 100);
323
-		}
324
-		elseif ($width < 100) {
325
-			$coeff = max($coeff, 10);
326
-		}
327
-	}
328
-	if (
329
-		isset($attributs['height'])
330
-		and $h = svg_dimension_to_pixels($attributs['height'])
331
-	) {
332
-		$height = $h;
333
-		// si on avait pas de viewBox, la construire a partir de ce height
334
-		if (empty($attributs['viewBox'])) {
335
-			$viewBox[3] = $height;
336
-		}
337
-	}
338
-	else {
339
-		$height = $viewBox[3];
340
-		if ($height < 1) {
341
-			$coeff = max($coeff, 1000);
342
-		}
343
-		elseif ($height < 10) {
344
-			$coeff = max($coeff, 100);
345
-		}
346
-		elseif ($height < 100) {
347
-			$coeff = max($coeff, 10);
348
-		}
349
-	}
350
-
351
-	// arrondir le width et height en pixel in fine
352
-	$width = round($coeff * $width);
353
-	$height = round($coeff * $height);
354
-
355
-	$viewBox = implode(' ', $viewBox);
356
-
357
-	return [$width, $height, $viewBox];
284
+    $width = 350; // default width
285
+    $height = 150; // default height
286
+
287
+    $viewBox = "0 0 $width $height";
288
+    if (isset($attributs['viewBox'])) {
289
+        $viewBox = $attributs['viewBox'];
290
+        $viewBox = preg_replace(',\s+,', ' ', $viewBox);
291
+    }
292
+    // et on la convertit en px
293
+    $viewBox = explode(' ', $viewBox);
294
+    $viewBox = array_map('svg_dimension_to_pixels', $viewBox);
295
+    if (!$viewBox[2]) {
296
+        $viewBox[2] = $width;
297
+    }
298
+    if (!$viewBox[3]) {
299
+        $viewBox[3] = $height;
300
+    }
301
+
302
+    $coeff = 1;
303
+    if (
304
+        isset($attributs['width'])
305
+        and $w = svg_dimension_to_pixels($attributs['width'])
306
+    ) {
307
+        $width = $w;
308
+        // si on avait pas de viewBox, la construire a partir de ce width
309
+        if (empty($attributs['viewBox'])) {
310
+            $viewBox[2] = $width;
311
+            // si pas de height valide, on suppose l'image carree
312
+            $viewBox[3] = $width;
313
+        }
314
+    }
315
+    else {
316
+        // si on recupere la taille de la viewbox mais si la viewbox est petite on met un multiplicateur pour la taille finale
317
+        $width = $viewBox[2];
318
+        if ($width < 1) {
319
+            $coeff = max($coeff, 1000);
320
+        }
321
+        elseif ($width < 10) {
322
+            $coeff = max($coeff, 100);
323
+        }
324
+        elseif ($width < 100) {
325
+            $coeff = max($coeff, 10);
326
+        }
327
+    }
328
+    if (
329
+        isset($attributs['height'])
330
+        and $h = svg_dimension_to_pixels($attributs['height'])
331
+    ) {
332
+        $height = $h;
333
+        // si on avait pas de viewBox, la construire a partir de ce height
334
+        if (empty($attributs['viewBox'])) {
335
+            $viewBox[3] = $height;
336
+        }
337
+    }
338
+    else {
339
+        $height = $viewBox[3];
340
+        if ($height < 1) {
341
+            $coeff = max($coeff, 1000);
342
+        }
343
+        elseif ($height < 10) {
344
+            $coeff = max($coeff, 100);
345
+        }
346
+        elseif ($height < 100) {
347
+            $coeff = max($coeff, 10);
348
+        }
349
+    }
350
+
351
+    // arrondir le width et height en pixel in fine
352
+    $width = round($coeff * $width);
353
+    $height = round($coeff * $height);
354
+
355
+    $viewBox = implode(' ', $viewBox);
356
+
357
+    return [$width, $height, $viewBox];
358 358
 }
359 359
 
360 360
 /**
@@ -370,25 +370,25 @@  discard block
 block discarded – undo
370 370
  * @return string
371 371
  */
372 372
 function svg_force_viewBox_px($img, $force_width_and_height = false) {
373
-	if (
374
-		$svg = svg_charger($img)
375
-		and $svg_infos = svg_lire_balise_svg($svg)
376
-	) {
377
-		[$balise_svg, $attributs] = $svg_infos;
373
+    if (
374
+        $svg = svg_charger($img)
375
+        and $svg_infos = svg_lire_balise_svg($svg)
376
+    ) {
377
+        [$balise_svg, $attributs] = $svg_infos;
378 378
 
379
-		[$width, $height, $viewBox] = svg_getimagesize_from_attr($attributs);
379
+        [$width, $height, $viewBox] = svg_getimagesize_from_attr($attributs);
380 380
 
381
-		if ($force_width_and_height) {
382
-			$attributs['width'] = $width;
383
-			$attributs['height'] = $height;
384
-		}
381
+        if ($force_width_and_height) {
382
+            $attributs['width'] = $width;
383
+            $attributs['height'] = $height;
384
+        }
385 385
 
386
-		$attributs['viewBox'] = $viewBox;
386
+        $attributs['viewBox'] = $viewBox;
387 387
 
388
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
389
-		return $svg;
390
-	}
391
-	return $img;
388
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
389
+        return $svg;
390
+    }
391
+    return $img;
392 392
 }
393 393
 
394 394
 /**
@@ -397,12 +397,12 @@  discard block
 block discarded – undo
397 397
  * @return array|mixed
398 398
  */
399 399
 function svg_extract_couleurs($img) {
400
-	if ($svg = svg_charger($img)) {
401
-		if (preg_match_all('/(#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])|(rgb\([\s\d]+,[\s\d]+,[\s\d]+\))|(#[0-9a-f][0-9a-f][0-9a-f])/imS', $svg, $matches)) {
402
-			return $matches[0];
403
-		}
404
-	}
405
-	return [];
400
+    if ($svg = svg_charger($img)) {
401
+        if (preg_match_all('/(#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])|(rgb\([\s\d]+,[\s\d]+,[\s\d]+\))|(#[0-9a-f][0-9a-f][0-9a-f])/imS', $svg, $matches)) {
402
+            return $matches[0];
403
+        }
404
+    }
405
+    return [];
406 406
 }
407 407
 
408 408
 /**
@@ -413,58 +413,58 @@  discard block
 block discarded – undo
413 413
  * @return bool|string
414 414
  */
415 415
 function svg_recadrer($img, $new_width, $new_height, $offset_width, $offset_height, $background_color = '') {
416
-	if (
417
-		$svg = svg_force_viewBox_px($img)
418
-		and $svg_infos = svg_lire_balise_svg($svg)
419
-	) {
420
-		[$balise_svg, $attributs] = $svg_infos;
421
-		$viewBox = explode(' ', $attributs['viewBox']);
422
-
423
-		$viewport_w = $new_width;
424
-		$viewport_h = $new_height;
425
-		$viewport_ox = $offset_width;
426
-		$viewport_oy = $offset_height;
427
-
428
-		// si on a un width/height qui rescale, il faut rescaler
429
-		if (
430
-			isset($attributs['width'])
431
-			and $w = svg_dimension_to_pixels($attributs['width'])
432
-			and isset($attributs['height'])
433
-			and $h = svg_dimension_to_pixels($attributs['height'])
434
-		) {
435
-			$xscale = $viewBox[2] / $w;
436
-			$viewport_w = round($viewport_w * $xscale, 2);
437
-			$viewport_ox = round($viewport_ox * $xscale, 2);
438
-			$yscale = $viewBox[3] / $h;
439
-			$viewport_h = round($viewport_h * $yscale, 2);
440
-			$viewport_oy = round($viewport_oy * $yscale, 2);
441
-		}
442
-
443
-		if ($viewport_w > $viewBox[2] or $viewport_h > $viewBox[3]) {
444
-			$svg = svg_clip_in_box($svg, $viewBox[0], $viewBox[1], $viewBox[2], $viewBox[3]);
445
-		}
446
-
447
-		// maintenant on redefinit la viewBox
448
-		$viewBox[0] += $viewport_ox;
449
-		$viewBox[1] += $viewport_oy;
450
-		$viewBox[2] = $viewport_w;
451
-		$viewBox[3] = $viewport_h;
452
-
453
-		$attributs['viewBox'] = implode(' ', $viewBox);
454
-		$attributs['width'] = strval($new_width);
455
-		$attributs['height'] = strval($new_height);
456
-
457
-		$svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
458
-
459
-		// ajouter un background
460
-		if ($background_color and $background_color !== 'transparent') {
461
-			$svg = svg_ajouter_background($svg, $background_color);
462
-		}
463
-
464
-		return $svg;
465
-	}
466
-
467
-	return $img;
416
+    if (
417
+        $svg = svg_force_viewBox_px($img)
418
+        and $svg_infos = svg_lire_balise_svg($svg)
419
+    ) {
420
+        [$balise_svg, $attributs] = $svg_infos;
421
+        $viewBox = explode(' ', $attributs['viewBox']);
422
+
423
+        $viewport_w = $new_width;
424
+        $viewport_h = $new_height;
425
+        $viewport_ox = $offset_width;
426
+        $viewport_oy = $offset_height;
427
+
428
+        // si on a un width/height qui rescale, il faut rescaler
429
+        if (
430
+            isset($attributs['width'])
431
+            and $w = svg_dimension_to_pixels($attributs['width'])
432
+            and isset($attributs['height'])
433
+            and $h = svg_dimension_to_pixels($attributs['height'])
434
+        ) {
435
+            $xscale = $viewBox[2] / $w;
436
+            $viewport_w = round($viewport_w * $xscale, 2);
437
+            $viewport_ox = round($viewport_ox * $xscale, 2);
438
+            $yscale = $viewBox[3] / $h;
439
+            $viewport_h = round($viewport_h * $yscale, 2);
440
+            $viewport_oy = round($viewport_oy * $yscale, 2);
441
+        }
442
+
443
+        if ($viewport_w > $viewBox[2] or $viewport_h > $viewBox[3]) {
444
+            $svg = svg_clip_in_box($svg, $viewBox[0], $viewBox[1], $viewBox[2], $viewBox[3]);
445
+        }
446
+
447
+        // maintenant on redefinit la viewBox
448
+        $viewBox[0] += $viewport_ox;
449
+        $viewBox[1] += $viewport_oy;
450
+        $viewBox[2] = $viewport_w;
451
+        $viewBox[3] = $viewport_h;
452
+
453
+        $attributs['viewBox'] = implode(' ', $viewBox);
454
+        $attributs['width'] = strval($new_width);
455
+        $attributs['height'] = strval($new_height);
456
+
457
+        $svg = svg_change_balise_svg($svg, $balise_svg, $attributs);
458
+
459
+        // ajouter un background
460
+        if ($background_color and $background_color !== 'transparent') {
461
+            $svg = svg_ajouter_background($svg, $background_color);
462
+        }
463
+
464
+        return $svg;
465
+    }
466
+
467
+    return $img;
468 468
 }
469 469
 
470 470
 /**
@@ -474,26 +474,26 @@  discard block
 block discarded – undo
474 474
  * @return bool|string
475 475
  */
476 476
 function svg_ajouter_background($img, $background_color) {
477
-	if (
478
-		$svg = svg_charger($img)
479
-		and $svg_infos = svg_lire_balise_svg($svg)
480
-	) {
481
-		if ($background_color and $background_color !== 'transparent') {
482
-			[$balise_svg, $attributs] = $svg_infos;
483
-
484
-			$background_color = svg_couleur_to_hexa($background_color);
485
-			if (isset($attributs['viewBox'])) {
486
-				$viewBox = explode(' ', $attributs['viewBox']);
487
-				$rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\"/>";
488
-			}
489
-			else {
490
-				$rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
491
-			}
492
-			$svg = svg_insert_shapes($svg, $rect);
493
-		}
494
-		return $svg;
495
-	}
496
-	return $img;
477
+    if (
478
+        $svg = svg_charger($img)
479
+        and $svg_infos = svg_lire_balise_svg($svg)
480
+    ) {
481
+        if ($background_color and $background_color !== 'transparent') {
482
+            [$balise_svg, $attributs] = $svg_infos;
483
+
484
+            $background_color = svg_couleur_to_hexa($background_color);
485
+            if (isset($attributs['viewBox'])) {
486
+                $viewBox = explode(' ', $attributs['viewBox']);
487
+                $rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\"/>";
488
+            }
489
+            else {
490
+                $rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
491
+            }
492
+            $svg = svg_insert_shapes($svg, $rect);
493
+        }
494
+        return $svg;
495
+    }
496
+    return $img;
497 497
 }
498 498
 
499 499
 
@@ -504,26 +504,26 @@  discard block
 block discarded – undo
504 504
  * @return bool|string
505 505
  */
506 506
 function svg_ajouter_voile($img, $background_color, $opacity) {
507
-	if (
508
-		$svg = svg_charger($img)
509
-		and $svg_infos = svg_lire_balise_svg($svg)
510
-	) {
511
-		if ($background_color and $background_color !== 'transparent') {
512
-			[$balise_svg, $attributs] = $svg_infos;
513
-
514
-			$background_color = svg_couleur_to_hexa($background_color);
515
-			if (isset($attributs['viewBox'])) {
516
-				$viewBox = explode(' ', $attributs['viewBox']);
517
-				$rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\" opacity=\"$opacity\"/>";
518
-			}
519
-			else {
520
-				$rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
521
-			}
522
-			$svg = svg_insert_shapes($svg, $rect, false);
523
-		}
524
-		return $svg;
525
-	}
526
-	return $img;
507
+    if (
508
+        $svg = svg_charger($img)
509
+        and $svg_infos = svg_lire_balise_svg($svg)
510
+    ) {
511
+        if ($background_color and $background_color !== 'transparent') {
512
+            [$balise_svg, $attributs] = $svg_infos;
513
+
514
+            $background_color = svg_couleur_to_hexa($background_color);
515
+            if (isset($attributs['viewBox'])) {
516
+                $viewBox = explode(' ', $attributs['viewBox']);
517
+                $rect = '<rect x="' . $viewBox[0] . '" y="' . $viewBox[1] . '" width="' . $viewBox[2] . '" height="' . $viewBox[3] . "\" fill=\"$background_color\" opacity=\"$opacity\"/>";
518
+            }
519
+            else {
520
+                $rect = "<rect width=\"100%\" height=\"100%\" fill=\"$background_color\"/>";
521
+            }
522
+            $svg = svg_insert_shapes($svg, $rect, false);
523
+        }
524
+        return $svg;
525
+    }
526
+    return $img;
527 527
 }
528 528
 
529 529
 
@@ -534,27 +534,27 @@  discard block
 block discarded – undo
534 534
  * @return bool|string
535 535
  */
536 536
 function svg_transformer($img, $attributs) {
537
-	if (
538
-		$svg = svg_charger($img)
539
-		and $svg_infos = svg_lire_balise_svg($svg)
540
-	) {
541
-		if ($attributs) {
542
-			[$balise_svg, ] = $svg_infos;
543
-			$g = '<g';
544
-			foreach ($attributs as $k => $v) {
545
-				if (strlen($v)) {
546
-					$g .= " $k=\"" . attribut_html($v) . '"';
547
-				}
548
-			}
549
-			if (strlen($g) > 2) {
550
-				$g .= '>';
551
-				$svg = svg_insert_shapes($svg, $g);
552
-				$svg = svg_insert_shapes($svg, '</g>', false);
553
-			}
554
-		}
555
-		return $svg;
556
-	}
557
-	return $img;
537
+    if (
538
+        $svg = svg_charger($img)
539
+        and $svg_infos = svg_lire_balise_svg($svg)
540
+    ) {
541
+        if ($attributs) {
542
+            [$balise_svg, ] = $svg_infos;
543
+            $g = '<g';
544
+            foreach ($attributs as $k => $v) {
545
+                if (strlen($v)) {
546
+                    $g .= " $k=\"" . attribut_html($v) . '"';
547
+                }
548
+            }
549
+            if (strlen($g) > 2) {
550
+                $g .= '>';
551
+                $svg = svg_insert_shapes($svg, $g);
552
+                $svg = svg_insert_shapes($svg, '</g>', false);
553
+            }
554
+        }
555
+        return $svg;
556
+    }
557
+    return $img;
558 558
 }
559 559
 
560 560
 /**
@@ -565,21 +565,21 @@  discard block
 block discarded – undo
565 565
  * @return bool|string
566 566
  */
567 567
 function svg_apply_filter($img, $filter_def) {
568
-	if (
569
-		$svg = svg_charger($img)
570
-		and $svg_infos = svg_lire_balise_svg($svg)
571
-	) {
572
-		if ($filter_def) {
573
-			[$balise_svg, ] = $svg_infos;
574
-			$filter_id = 'filter-' . substr(md5($filter_def . strlen($svg)), 0, 8);
575
-			$filter = "<defs><filter id=\"$filter_id\">$filter_def</filter></defs>";
576
-			$g = "<g filter=\"url(#$filter_id)\">";
577
-			$svg = svg_insert_shapes($svg, $filter . $g);
578
-			$svg = svg_insert_shapes($svg, '</g>', false);
579
-		}
580
-		return $svg;
581
-	}
582
-	return $img;
568
+    if (
569
+        $svg = svg_charger($img)
570
+        and $svg_infos = svg_lire_balise_svg($svg)
571
+    ) {
572
+        if ($filter_def) {
573
+            [$balise_svg, ] = $svg_infos;
574
+            $filter_id = 'filter-' . substr(md5($filter_def . strlen($svg)), 0, 8);
575
+            $filter = "<defs><filter id=\"$filter_id\">$filter_def</filter></defs>";
576
+            $g = "<g filter=\"url(#$filter_id)\">";
577
+            $svg = svg_insert_shapes($svg, $filter . $g);
578
+            $svg = svg_insert_shapes($svg, '</g>', false);
579
+        }
580
+        return $svg;
581
+    }
582
+    return $img;
583 583
 }
584 584
 
585 585
 /**
@@ -589,8 +589,8 @@  discard block
 block discarded – undo
589 589
  * @return string
590 590
  */
591 591
 function svg_filter_blur($img, $blur_width) {
592
-	$blur_width = intval($blur_width);
593
-	return svg_apply_filter($img, "<feGaussianBlur stdDeviation=\"$blur_width\"/>");
592
+    $blur_width = intval($blur_width);
593
+    return svg_apply_filter($img, "<feGaussianBlur stdDeviation=\"$blur_width\"/>");
594 594
 }
595 595
 
596 596
 /**
@@ -600,10 +600,10 @@  discard block
 block discarded – undo
600 600
  * @return bool|string
601 601
  */
602 602
 function svg_filter_grayscale($img, $intensity) {
603
-	$value = round(1.0 - $intensity, 2);
604
-	//$filter = "<feColorMatrix type=\"matrix\" values=\"0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\"/>";
605
-	$filter = "<feColorMatrix type=\"saturate\" values=\"$value\"/>";
606
-	return svg_apply_filter($img, $filter);
603
+    $value = round(1.0 - $intensity, 2);
604
+    //$filter = "<feColorMatrix type=\"matrix\" values=\"0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\"/>";
605
+    $filter = "<feColorMatrix type=\"saturate\" values=\"$value\"/>";
606
+    return svg_apply_filter($img, $filter);
607 607
 }
608 608
 
609 609
 /**
@@ -613,8 +613,8 @@  discard block
 block discarded – undo
613 613
  * @return bool|string
614 614
  */
615 615
 function svg_filter_sepia($img, $intensity) {
616
-	$filter = '<feColorMatrix type="matrix" values="0.30 0.30 0.30 0.0 0 0.25 0.25 0.25 0.0 0 0.20 0.20 0.20 0.0 0 0.00 0.00 0.00 1 0"/>';
617
-	return svg_apply_filter($img, $filter);
616
+    $filter = '<feColorMatrix type="matrix" values="0.30 0.30 0.30 0.0 0 0.25 0.25 0.25 0.0 0 0.20 0.20 0.20 0.0 0 0.00 0.00 0.00 1 0"/>';
617
+    return svg_apply_filter($img, $filter);
618 618
 }
619 619
 
620 620
 /**
@@ -624,31 +624,31 @@  discard block
 block discarded – undo
624 624
  * @return bool|string
625 625
  */
626 626
 function svg_flip($img, $HorV) {
627
-	if (
628
-		$svg = svg_force_viewBox_px($img)
629
-		and $svg_infos = svg_lire_balise_svg($svg)
630
-	) {
631
-		[$balise_svg, $atts] = $svg_infos;
632
-		$viewBox = explode(' ', $atts['viewBox']);
633
-
634
-		if (!in_array($HorV, ['h', 'H'])) {
635
-			$transform = 'scale(-1,1)';
636
-
637
-			$x = intval($viewBox[0]) + intval($viewBox[2] / 2);
638
-			$mx = -$x;
639
-			$transform = "translate($x, 0) $transform translate($mx, 0)";
640
-		}
641
-		else {
642
-			$transform = 'scale(1,-1)';
643
-
644
-			$y = intval($viewBox[1]) + intval($viewBox[3] / 2);
645
-			$my = -$y;
646
-			$transform = "translate(0, $y) $transform translate(0, $my)";
647
-		}
648
-		$svg = svg_transformer($svg, ['transform' => $transform]);
649
-		return $svg;
650
-	}
651
-	return $img;
627
+    if (
628
+        $svg = svg_force_viewBox_px($img)
629
+        and $svg_infos = svg_lire_balise_svg($svg)
630
+    ) {
631
+        [$balise_svg, $atts] = $svg_infos;
632
+        $viewBox = explode(' ', $atts['viewBox']);
633
+
634
+        if (!in_array($HorV, ['h', 'H'])) {
635
+            $transform = 'scale(-1,1)';
636
+
637
+            $x = intval($viewBox[0]) + intval($viewBox[2] / 2);
638
+            $mx = -$x;
639
+            $transform = "translate($x, 0) $transform translate($mx, 0)";
640
+        }
641
+        else {
642
+            $transform = 'scale(1,-1)';
643
+
644
+            $y = intval($viewBox[1]) + intval($viewBox[3] / 2);
645
+            $my = -$y;
646
+            $transform = "translate(0, $y) $transform translate(0, $my)";
647
+        }
648
+        $svg = svg_transformer($svg, ['transform' => $transform]);
649
+        return $svg;
650
+    }
651
+    return $img;
652 652
 }
653 653
 
654 654
 /**
@@ -662,20 +662,20 @@  discard block
 block discarded – undo
662 662
  * @return bool|string
663 663
  */
664 664
 function svg_rotate($img, $angle, $center_x, $center_y) {
665
-	if (
666
-		$svg = svg_force_viewBox_px($img)
667
-		and $svg_infos = svg_lire_balise_svg($svg)
668
-	) {
669
-		[$balise_svg, $atts] = $svg_infos;
670
-		$viewBox = explode(' ', $atts['viewBox']);
671
-
672
-		$center_x = round($viewBox[0] + $center_x * $viewBox[2]);
673
-		$center_y = round($viewBox[1] + $center_y * $viewBox[3]);
674
-		$svg = svg_transformer($svg, ['transform' => "rotate($angle $center_x $center_y)"]);
675
-
676
-		return $svg;
677
-	}
678
-	return $img;
665
+    if (
666
+        $svg = svg_force_viewBox_px($img)
667
+        and $svg_infos = svg_lire_balise_svg($svg)
668
+    ) {
669
+        [$balise_svg, $atts] = $svg_infos;
670
+        $viewBox = explode(' ', $atts['viewBox']);
671
+
672
+        $center_x = round($viewBox[0] + $center_x * $viewBox[2]);
673
+        $center_y = round($viewBox[1] + $center_y * $viewBox[3]);
674
+        $svg = svg_transformer($svg, ['transform' => "rotate($angle $center_x $center_y)"]);
675
+
676
+        return $svg;
677
+    }
678
+    return $img;
679 679
 }
680 680
 
681 681
 /**
@@ -687,41 +687,41 @@  discard block
 block discarded – undo
687 687
  * @return bool|mixed|string
688 688
  */
689 689
 function svg_filtrer_couleurs($img, $callback_filter) {
690
-	if (
691
-		$svg = svg_force_viewBox_px($img)
692
-		and $colors = svg_extract_couleurs($svg)
693
-	) {
694
-		$colors = array_unique($colors);
695
-
696
-		$short = [];
697
-		$long = [];
698
-		while (count($colors)) {
699
-			$c = array_shift($colors);
700
-			if (strlen($c) == 4) {
701
-				$short[] = $c;
702
-			}
703
-			else {
704
-				$long[] = $c;
705
-			}
706
-		}
707
-
708
-		$colors = [...$long, ...$short];
709
-		$new_colors = [];
710
-		$colors = array_flip($colors);
711
-		foreach ($colors as $c => $k) {
712
-			$colors[$c] = "@@@COLOR$$k$@@@";
713
-		}
714
-
715
-
716
-		foreach ($colors as $original => $replace) {
717
-			$new = svg_couleur_to_hexa($original);
718
-			$new_colors[$replace] = $callback_filter($new);
719
-		}
720
-
721
-		$svg = str_replace(array_keys($colors), array_values($colors), $svg);
722
-		$svg = str_replace(array_keys($new_colors), array_values($new_colors), $svg);
723
-
724
-		return $svg;
725
-	}
726
-	return $img;
690
+    if (
691
+        $svg = svg_force_viewBox_px($img)
692
+        and $colors = svg_extract_couleurs($svg)
693
+    ) {
694
+        $colors = array_unique($colors);
695
+
696
+        $short = [];
697
+        $long = [];
698
+        while (count($colors)) {
699
+            $c = array_shift($colors);
700
+            if (strlen($c) == 4) {
701
+                $short[] = $c;
702
+            }
703
+            else {
704
+                $long[] = $c;
705
+            }
706
+        }
707
+
708
+        $colors = [...$long, ...$short];
709
+        $new_colors = [];
710
+        $colors = array_flip($colors);
711
+        foreach ($colors as $c => $k) {
712
+            $colors[$c] = "@@@COLOR$$k$@@@";
713
+        }
714
+
715
+
716
+        foreach ($colors as $original => $replace) {
717
+            $new = svg_couleur_to_hexa($original);
718
+            $new_colors[$replace] = $callback_filter($new);
719
+        }
720
+
721
+        $svg = str_replace(array_keys($colors), array_values($colors), $svg);
722
+        $svg = str_replace(array_keys($new_colors), array_values($new_colors), $svg);
723
+
724
+        return $svg;
725
+    }
726
+    return $img;
727 727
 }
Please login to merge, or discard this patch.
ecrire/inc/envoyer_mail.php 1 patch
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Mail
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 include_spip('inc/charsets');
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
  * @return string
33 33
  */
34 34
 function nettoyer_titre_email($titre) {
35
-	return str_replace("\n", ' ', nettoyer_caracteres_mail(textebrut(corriger_typo($titre))));
35
+    return str_replace("\n", ' ', nettoyer_caracteres_mail(textebrut(corriger_typo($titre))));
36 36
 }
37 37
 
38 38
 /**
@@ -48,23 +48,23 @@  discard block
 block discarded – undo
48 48
  */
49 49
 function nettoyer_caracteres_mail($t) {
50 50
 
51
-	$t = filtrer_entites($t);
51
+    $t = filtrer_entites($t);
52 52
 
53
-	if ($GLOBALS['meta']['charset'] <> 'utf-8') {
54
-		$t = str_replace(
55
-			['&#8217;', '&#8220;', '&#8221;'],
56
-			["'", '"', '"'],
57
-			$t
58
-		);
59
-	}
53
+    if ($GLOBALS['meta']['charset'] <> 'utf-8') {
54
+        $t = str_replace(
55
+            ['&#8217;', '&#8220;', '&#8221;'],
56
+            ["'", '"', '"'],
57
+            $t
58
+        );
59
+    }
60 60
 
61
-	$t = str_replace(
62
-		['&mdash;', '&endash;'],
63
-		['--', '-'],
64
-		$t
65
-	);
61
+    $t = str_replace(
62
+        ['&mdash;', '&endash;'],
63
+        ['--', '-'],
64
+        $t
65
+    );
66 66
 
67
-	return $t;
67
+    return $t;
68 68
 }
69 69
 
70 70
 /**
@@ -97,87 +97,87 @@  discard block
 block discarded – undo
97 97
  */
98 98
 function inc_envoyer_mail_dist($destinataire, $sujet, $corps, $from = '', $headers = '') {
99 99
 
100
-	if (!email_valide($destinataire)) {
101
-		return false;
102
-	}
103
-	if ($destinataire == _T('info_mail_fournisseur')) {
104
-		return false;
105
-	} // tres fort
106
-
107
-	// Fournir si possible un Message-Id: conforme au RFC1036,
108
-	// sinon SpamAssassin denoncera un MSGID_FROM_MTA_HEADER
109
-
110
-	$email_envoi = $GLOBALS['meta']['email_envoi'];
111
-	if (!email_valide($email_envoi)) {
112
-		spip_log('Meta email_envoi invalide. Le mail sera probablement vu comme spam.');
113
-		$email_envoi = $destinataire;
114
-	}
115
-
116
-	$parts = '';
117
-	if (is_array($corps)) {
118
-		$texte = $corps['texte'];
119
-		$from = ($corps['from'] ?? $from);
120
-		$headers = ($corps['headers'] ?? $headers);
121
-		if (is_array($headers)) {
122
-			$headers = implode("\n", $headers);
123
-		}
124
-		if (isset($corps['pieces_jointes']) and function_exists('mail_embarquer_pieces_jointes')) {
125
-			$parts = mail_embarquer_pieces_jointes($corps['pieces_jointes']);
126
-		}
127
-	} else {
128
-		$texte = $corps;
129
-	}
130
-
131
-	if (!$from) {
132
-		$from = $email_envoi;
133
-	}
134
-
135
-	// ceci est la RegExp NO_REAL_NAME faisant hurler SpamAssassin
136
-	if (preg_match('/^["\s]*\<?\S+\@\S+\>?\s*$/', $from)) {
137
-		$from .= ' (' . str_replace(')', '', translitteration(str_replace('@', ' at ', $from))) . ')';
138
-	}
139
-
140
-	// nettoyer les &eacute; &#8217, &emdash; etc...
141
-	// les 'cliquer ici' etc sont a eviter;  voir:
142
-	// http://mta.org.ua/spamassassin-2.55/stuff/wiki.CustomRulesets/20050914/rules/french_rules.cf
143
-	$texte = nettoyer_caracteres_mail($texte);
144
-	$sujet = nettoyer_caracteres_mail($sujet);
145
-
146
-	// encoder le sujet si possible selon la RFC
147
-	if (init_mb_string()) {
148
-		# un bug de mb_string casse mb_encode_mimeheader si l'encoding interne
149
-		# est UTF-8 et le charset iso-8859-1 (constate php5-mac ; php4.3-debian)
150
-		$charset = $GLOBALS['meta']['charset'];
151
-		mb_internal_encoding($charset);
152
-		$sujet = mb_encode_mimeheader($sujet, $charset, 'Q', "\n");
153
-		mb_internal_encoding('utf-8');
154
-	}
155
-
156
-	$headers = $headers ?? '';
157
-	if (function_exists('wordwrap') && (preg_match(',multipart/mixed,', $headers) == 0)) {
158
-		$texte = wordwrap($texte);
159
-	}
160
-
161
-	[$headers, $texte] = mail_normaliser_headers($headers, $from, $destinataire, $texte, $parts);
162
-
163
-	if (_OS_SERVEUR == 'windows') {
164
-		$texte = preg_replace("@\r*\n@", "\r\n", $texte);
165
-		$headers = preg_replace("@\r*\n@", "\r\n", $headers);
166
-		$sujet = preg_replace("@\r*\n@", "\r\n", $sujet);
167
-	}
168
-
169
-	spip_log("mail $destinataire\n$sujet\n$headers", 'mails');
170
-	// mode TEST : forcer l'email
171
-	if (defined('_TEST_EMAIL_DEST')) {
172
-		if (!_TEST_EMAIL_DEST) {
173
-			return false;
174
-		} else {
175
-			$texte = "Dest : $destinataire\r\n" . $texte;
176
-			$destinataire = _TEST_EMAIL_DEST;
177
-		}
178
-	}
179
-
180
-	return @mail($destinataire, $sujet, $texte, $headers);
100
+    if (!email_valide($destinataire)) {
101
+        return false;
102
+    }
103
+    if ($destinataire == _T('info_mail_fournisseur')) {
104
+        return false;
105
+    } // tres fort
106
+
107
+    // Fournir si possible un Message-Id: conforme au RFC1036,
108
+    // sinon SpamAssassin denoncera un MSGID_FROM_MTA_HEADER
109
+
110
+    $email_envoi = $GLOBALS['meta']['email_envoi'];
111
+    if (!email_valide($email_envoi)) {
112
+        spip_log('Meta email_envoi invalide. Le mail sera probablement vu comme spam.');
113
+        $email_envoi = $destinataire;
114
+    }
115
+
116
+    $parts = '';
117
+    if (is_array($corps)) {
118
+        $texte = $corps['texte'];
119
+        $from = ($corps['from'] ?? $from);
120
+        $headers = ($corps['headers'] ?? $headers);
121
+        if (is_array($headers)) {
122
+            $headers = implode("\n", $headers);
123
+        }
124
+        if (isset($corps['pieces_jointes']) and function_exists('mail_embarquer_pieces_jointes')) {
125
+            $parts = mail_embarquer_pieces_jointes($corps['pieces_jointes']);
126
+        }
127
+    } else {
128
+        $texte = $corps;
129
+    }
130
+
131
+    if (!$from) {
132
+        $from = $email_envoi;
133
+    }
134
+
135
+    // ceci est la RegExp NO_REAL_NAME faisant hurler SpamAssassin
136
+    if (preg_match('/^["\s]*\<?\S+\@\S+\>?\s*$/', $from)) {
137
+        $from .= ' (' . str_replace(')', '', translitteration(str_replace('@', ' at ', $from))) . ')';
138
+    }
139
+
140
+    // nettoyer les &eacute; &#8217, &emdash; etc...
141
+    // les 'cliquer ici' etc sont a eviter;  voir:
142
+    // http://mta.org.ua/spamassassin-2.55/stuff/wiki.CustomRulesets/20050914/rules/french_rules.cf
143
+    $texte = nettoyer_caracteres_mail($texte);
144
+    $sujet = nettoyer_caracteres_mail($sujet);
145
+
146
+    // encoder le sujet si possible selon la RFC
147
+    if (init_mb_string()) {
148
+        # un bug de mb_string casse mb_encode_mimeheader si l'encoding interne
149
+        # est UTF-8 et le charset iso-8859-1 (constate php5-mac ; php4.3-debian)
150
+        $charset = $GLOBALS['meta']['charset'];
151
+        mb_internal_encoding($charset);
152
+        $sujet = mb_encode_mimeheader($sujet, $charset, 'Q', "\n");
153
+        mb_internal_encoding('utf-8');
154
+    }
155
+
156
+    $headers = $headers ?? '';
157
+    if (function_exists('wordwrap') && (preg_match(',multipart/mixed,', $headers) == 0)) {
158
+        $texte = wordwrap($texte);
159
+    }
160
+
161
+    [$headers, $texte] = mail_normaliser_headers($headers, $from, $destinataire, $texte, $parts);
162
+
163
+    if (_OS_SERVEUR == 'windows') {
164
+        $texte = preg_replace("@\r*\n@", "\r\n", $texte);
165
+        $headers = preg_replace("@\r*\n@", "\r\n", $headers);
166
+        $sujet = preg_replace("@\r*\n@", "\r\n", $sujet);
167
+    }
168
+
169
+    spip_log("mail $destinataire\n$sujet\n$headers", 'mails');
170
+    // mode TEST : forcer l'email
171
+    if (defined('_TEST_EMAIL_DEST')) {
172
+        if (!_TEST_EMAIL_DEST) {
173
+            return false;
174
+        } else {
175
+            $texte = "Dest : $destinataire\r\n" . $texte;
176
+            $destinataire = _TEST_EMAIL_DEST;
177
+        }
178
+    }
179
+
180
+    return @mail($destinataire, $sujet, $texte, $headers);
181 181
 }
182 182
 
183 183
 /**
@@ -191,58 +191,58 @@  discard block
 block discarded – undo
191 191
  * @return array
192 192
  */
193 193
 function mail_normaliser_headers($headers, $from, $to, $texte, $parts = '') {
194
-	$charset = $GLOBALS['meta']['charset'];
195
-
196
-	// Ajouter le Content-Type et consort s'il n'y est pas deja
197
-	if (strpos($headers, 'Content-Type: ') === false) {
198
-		$type =
199
-			"Content-Type: text/plain;charset=\"$charset\";\n" .
200
-			"Content-Transfer-Encoding: 8bit\n";
201
-	} else {
202
-		$type = '';
203
-	}
204
-
205
-	// calculer un identifiant unique
206
-	// Marie Toto <[email protected]> => @toto.com
207
-	if (preg_match('/@[^\s>]+/', $from, $domain)) {
208
-		$domain = $domain[0];
209
-	}
210
-	else {
211
-		$domain = '@unknown-' . md5($from) . '.org';
212
-	}
213
-	$uniq = random_int(0, mt_getrandmax()) . '_' . md5($to . $texte) . $domain;
214
-
215
-	// Si multi-part, s'en servir comme borne ...
216
-	if ($parts) {
217
-		$texte = "--$uniq\n$type\n" . $texte . "\n";
218
-		foreach ($parts as $part) {
219
-			$n = strlen($part[1]) . ($part[0] ? "\n" : '');
220
-			$e = join("\n", $part[0]);
221
-			$texte .= "\n--$uniq\nContent-Length: $n$e\n\n" . $part[1];
222
-		}
223
-		$texte .= "\n\n--$uniq--\n";
224
-		// Si boundary n'est pas entre guillemets,
225
-		// elle est comprise mais le charset est ignoree !
226
-		$type = "Content-Type: multipart/mixed; boundary=\"$uniq\"\n";
227
-	}
228
-
229
-	// .. et s'en servir pour plaire a SpamAssassin
230
-
231
-	$mid = 'Message-Id: <' . $uniq . '>';
232
-
233
-	// indispensable pour les sites qui collent d'office From: serveur-http
234
-	// sauf si deja mis par l'envoyeur
235
-	$rep = (strpos($headers, 'Reply-To:') !== false) ? '' : "Reply-To: $from\n";
236
-
237
-	// Nettoyer les en-tetes envoyees
238
-	// Ajouter le \n final
239
-	if (strlen($headers = trim($headers))) {
240
-		$headers .= "\n";
241
-	}
242
-
243
-	// Et mentionner l'indeboulonable nomenclature ratee
244
-
245
-	$headers .= "From: $from\n$type$rep$mid\nMIME-Version: 1.0\n";
246
-
247
-	return [$headers, $texte];
194
+    $charset = $GLOBALS['meta']['charset'];
195
+
196
+    // Ajouter le Content-Type et consort s'il n'y est pas deja
197
+    if (strpos($headers, 'Content-Type: ') === false) {
198
+        $type =
199
+            "Content-Type: text/plain;charset=\"$charset\";\n" .
200
+            "Content-Transfer-Encoding: 8bit\n";
201
+    } else {
202
+        $type = '';
203
+    }
204
+
205
+    // calculer un identifiant unique
206
+    // Marie Toto <[email protected]> => @toto.com
207
+    if (preg_match('/@[^\s>]+/', $from, $domain)) {
208
+        $domain = $domain[0];
209
+    }
210
+    else {
211
+        $domain = '@unknown-' . md5($from) . '.org';
212
+    }
213
+    $uniq = random_int(0, mt_getrandmax()) . '_' . md5($to . $texte) . $domain;
214
+
215
+    // Si multi-part, s'en servir comme borne ...
216
+    if ($parts) {
217
+        $texte = "--$uniq\n$type\n" . $texte . "\n";
218
+        foreach ($parts as $part) {
219
+            $n = strlen($part[1]) . ($part[0] ? "\n" : '');
220
+            $e = join("\n", $part[0]);
221
+            $texte .= "\n--$uniq\nContent-Length: $n$e\n\n" . $part[1];
222
+        }
223
+        $texte .= "\n\n--$uniq--\n";
224
+        // Si boundary n'est pas entre guillemets,
225
+        // elle est comprise mais le charset est ignoree !
226
+        $type = "Content-Type: multipart/mixed; boundary=\"$uniq\"\n";
227
+    }
228
+
229
+    // .. et s'en servir pour plaire a SpamAssassin
230
+
231
+    $mid = 'Message-Id: <' . $uniq . '>';
232
+
233
+    // indispensable pour les sites qui collent d'office From: serveur-http
234
+    // sauf si deja mis par l'envoyeur
235
+    $rep = (strpos($headers, 'Reply-To:') !== false) ? '' : "Reply-To: $from\n";
236
+
237
+    // Nettoyer les en-tetes envoyees
238
+    // Ajouter le \n final
239
+    if (strlen($headers = trim($headers))) {
240
+        $headers .= "\n";
241
+    }
242
+
243
+    // Et mentionner l'indeboulonable nomenclature ratee
244
+
245
+    $headers .= "From: $from\n$type$rep$mid\nMIME-Version: 1.0\n";
246
+
247
+    return [$headers, $texte];
248 248
 }
Please login to merge, or discard this patch.