Completed
Push — master ( 105b0e...0bbf82 )
by cam
04:36
created
ecrire/inc/cookie.php 1 patch
Indentation   +91 added lines, -91 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
 
@@ -52,62 +52,62 @@  discard block
 block discarded – undo
52 52
  *     cookie sécurisé ou non ?
53 53
  **/
54 54
 function spip_setcookie($name = '', $value = '', $options = []) {
55
-	static $to_secure_list = ['spip_session'];
56
-
57
-	if (!is_array($options)) {
58
-		// anciens paramètres :
59
-		# spip_setcookie($name = '', $value = '', $expire = 0, $path = 'AUTO', $domain = '', $secure = '')
60
-		$opt = func_get_args();
61
-		$opt = array_slice($opt, 2);
62
-		$options = []; # /!\ après le func_get_args (sinon $opt[0] référence la nouvelle valeur de $options !);
63
-		if (isset($opt[0])) {
64
-			$options['expires'] = $opt[0];
65
-		}
66
-		if (isset($opt[1])) {
67
-			$options['path'] = $opt[1];
68
-		}
69
-		if (isset($opt[2])) {
70
-			$options['domain'] = $opt[2];
71
-		}
72
-		if (isset($opt[3])) {
73
-			$options['secure'] = $opt[3];
74
-		}
75
-	}
76
-
77
-	$name = preg_replace('/^spip_/', $GLOBALS['cookie_prefix'] . '_', $name);
78
-
79
-	// expires
80
-	if (!isset($options['expires'])) {
81
-		$options['expires'] = 0;
82
-	}
83
-	if (!isset($options['path']) or $options['path'] === 'AUTO') {
84
-		if (defined('_COOKIE_PATH')) {
85
-			$options['path'] = _COOKIE_PATH;
86
-		} else {
87
-			$options['path'] = preg_replace(',^\w+://[^/]*,', '', url_de_base());
88
-		}
89
-	}
90
-	if (empty($options['domain']) and defined('_COOKIE_DOMAIN') and _COOKIE_DOMAIN) {
91
-		$options['domain'] = _COOKIE_DOMAIN;
92
-	}
93
-	if (in_array($name, $to_secure_list)) {
94
-		if (empty($options['secure']) and defined('_COOKIE_SECURE') and _COOKIE_SECURE) {
95
-			$options['secure'] = true;
96
-		}
97
-		if (empty($options['httponly'])) {
98
-			$options['httponly'] = true;
99
-		}
100
-	}
101
-	if (empty($options['samesite'])) {
102
-		$options['samesite'] = 'Lax';
103
-	}
104
-
105
-	#spip_log("cookie('$name', '$value', " . json_encode($options, true) . ")", "cookies");
106
-	$a = @setcookie($name, $value, $options);
107
-
108
-	spip_cookie_envoye(true);
109
-
110
-	return $a;
55
+    static $to_secure_list = ['spip_session'];
56
+
57
+    if (!is_array($options)) {
58
+        // anciens paramètres :
59
+        # spip_setcookie($name = '', $value = '', $expire = 0, $path = 'AUTO', $domain = '', $secure = '')
60
+        $opt = func_get_args();
61
+        $opt = array_slice($opt, 2);
62
+        $options = []; # /!\ après le func_get_args (sinon $opt[0] référence la nouvelle valeur de $options !);
63
+        if (isset($opt[0])) {
64
+            $options['expires'] = $opt[0];
65
+        }
66
+        if (isset($opt[1])) {
67
+            $options['path'] = $opt[1];
68
+        }
69
+        if (isset($opt[2])) {
70
+            $options['domain'] = $opt[2];
71
+        }
72
+        if (isset($opt[3])) {
73
+            $options['secure'] = $opt[3];
74
+        }
75
+    }
76
+
77
+    $name = preg_replace('/^spip_/', $GLOBALS['cookie_prefix'] . '_', $name);
78
+
79
+    // expires
80
+    if (!isset($options['expires'])) {
81
+        $options['expires'] = 0;
82
+    }
83
+    if (!isset($options['path']) or $options['path'] === 'AUTO') {
84
+        if (defined('_COOKIE_PATH')) {
85
+            $options['path'] = _COOKIE_PATH;
86
+        } else {
87
+            $options['path'] = preg_replace(',^\w+://[^/]*,', '', url_de_base());
88
+        }
89
+    }
90
+    if (empty($options['domain']) and defined('_COOKIE_DOMAIN') and _COOKIE_DOMAIN) {
91
+        $options['domain'] = _COOKIE_DOMAIN;
92
+    }
93
+    if (in_array($name, $to_secure_list)) {
94
+        if (empty($options['secure']) and defined('_COOKIE_SECURE') and _COOKIE_SECURE) {
95
+            $options['secure'] = true;
96
+        }
97
+        if (empty($options['httponly'])) {
98
+            $options['httponly'] = true;
99
+        }
100
+    }
101
+    if (empty($options['samesite'])) {
102
+        $options['samesite'] = 'Lax';
103
+    }
104
+
105
+    #spip_log("cookie('$name', '$value', " . json_encode($options, true) . ")", "cookies");
106
+    $a = @setcookie($name, $value, $options);
107
+
108
+    spip_cookie_envoye(true);
109
+
110
+    return $a;
111 111
 }
112 112
 
113 113
 /**
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
  * @return bool
124 124
  **/
125 125
 function spip_cookie_envoye($set = '') {
126
-	static $envoye = false;
127
-	if ($set) {
128
-		$envoye = true;
129
-	}
126
+    static $envoye = false;
127
+    if ($set) {
128
+        $envoye = true;
129
+    }
130 130
 
131
-	return $envoye;
131
+    return $envoye;
132 132
 }
133 133
 
134 134
 /**
@@ -147,21 +147,21 @@  discard block
 block discarded – undo
147 147
  *     Préfixe des cookies de SPIP
148 148
  **/
149 149
 function recuperer_cookies_spip($cookie_prefix) {
150
-	$prefix_long = strlen($cookie_prefix);
151
-
152
-	foreach ($_COOKIE as $name => $value) {
153
-		if (substr($name, 0, 5) == 'spip_' && substr($name, 0, $prefix_long) != $cookie_prefix) {
154
-			unset($_COOKIE[$name]);
155
-			unset($GLOBALS[$name]);
156
-		}
157
-	}
158
-	foreach ($_COOKIE as $name => $value) {
159
-		if (substr($name, 0, $prefix_long) == $cookie_prefix) {
160
-			$spipname = preg_replace('/^' . $cookie_prefix . '_/', 'spip_', $name);
161
-			$_COOKIE[$spipname] = $value;
162
-			$GLOBALS[$spipname] = $value;
163
-		}
164
-	}
150
+    $prefix_long = strlen($cookie_prefix);
151
+
152
+    foreach ($_COOKIE as $name => $value) {
153
+        if (substr($name, 0, 5) == 'spip_' && substr($name, 0, $prefix_long) != $cookie_prefix) {
154
+            unset($_COOKIE[$name]);
155
+            unset($GLOBALS[$name]);
156
+        }
157
+    }
158
+    foreach ($_COOKIE as $name => $value) {
159
+        if (substr($name, 0, $prefix_long) == $cookie_prefix) {
160
+            $spipname = preg_replace('/^' . $cookie_prefix . '_/', 'spip_', $name);
161
+            $_COOKIE[$spipname] = $value;
162
+            $GLOBALS[$spipname] = $value;
163
+        }
164
+    }
165 165
 
166 166
 }
167 167
 
@@ -181,18 +181,18 @@  discard block
 block discarded – undo
181 181
  *
182 182
  **/
183 183
 function exec_test_ajax_dist() {
184
-	switch (_request('js')) {
185
-		// on est appele par <noscript>
186
-		case -1:
187
-			spip_setcookie('spip_accepte_ajax', -1);
188
-			include_spip('inc/headers');
189
-			redirige_par_entete(chemin_image('puce-orange-anim.gif'));
190
-			break;
191
-
192
-		// ou par ajax
193
-		case 1:
194
-		default:
195
-			spip_setcookie('spip_accepte_ajax', 1);
196
-			break;
197
-	}
184
+    switch (_request('js')) {
185
+        // on est appele par <noscript>
186
+        case -1:
187
+            spip_setcookie('spip_accepte_ajax', -1);
188
+            include_spip('inc/headers');
189
+            redirige_par_entete(chemin_image('puce-orange-anim.gif'));
190
+            break;
191
+
192
+        // ou par ajax
193
+        case 1:
194
+        default:
195
+            spip_setcookie('spip_accepte_ajax', 1);
196
+            break;
197
+    }
198 198
 }
Please login to merge, or discard this patch.
ecrire/public/composer.php 2 patches
Indentation   +731 added lines, -731 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  **/
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 include_spip('inc/texte');
@@ -43,239 +43,239 @@  discard block
 block discarded – undo
43 43
 // https://code.spip.net/@public_composer_dist
44 44
 function public_composer_dist($squelette, $mime_type, $gram, $source, $connect = '') {
45 45
 
46
-	$nom = calculer_nom_fonction_squel($squelette, $mime_type, $connect);
47
-
48
-	//  si deja en memoire (INCLURE  a repetition) c'est bon.
49
-	if (function_exists($nom)) {
50
-		return $nom;
51
-	}
52
-
53
-	if (defined('_VAR_MODE') and _VAR_MODE == 'debug') {
54
-		$GLOBALS['debug_objets']['courant'] = $nom;
55
-	}
56
-
57
-	$phpfile = sous_repertoire(_DIR_SKELS, '', false, true) . $nom . '.php';
58
-
59
-	// si squelette est deja compile et perenne, le charger
60
-	if (!squelette_obsolete($phpfile, $source)) {
61
-		include_once $phpfile;
62
-		#if (!squelette_obsolete($phpfile, $source)
63
-		#  AND lire_fichier ($phpfile, $skel_code,
64
-		#  array('critique' => 'oui', 'phpcheck' => 'oui'))){
65
-		## eval('?'.'>'.$skel_code);
66
-		#	 spip_log($skel_code, 'comp')
67
-		#}
68
-	}
69
-
70
-	if (file_exists($lib = $squelette . '_fonctions' . '.php')) {
71
-		include_once $lib;
72
-	}
73
-
74
-	// tester si le eval ci-dessus a mis le squelette en memoire
75
-
76
-	if (function_exists($nom)) {
77
-		return $nom;
78
-	}
79
-
80
-	// charger le source, si possible, et compiler 
81
-	$skel_code = '';
82
-	if (lire_fichier($source, $skel)) {
83
-		$compiler = charger_fonction('compiler', 'public');
84
-		$skel_code = $compiler($skel, $nom, $gram, $source, $connect);
85
-	}
86
-
87
-	// Ne plus rien faire si le compilateur n'a pas pu operer.
88
-	if (!$skel_code) {
89
-		return false;
90
-	}
91
-
92
-	foreach ($skel_code as $id => $boucle) {
93
-		$f = $boucle->return;
94
-		try {
95
-			// @todo : a remplacer quand _PHP_MIN >= 7
96
-			// eval("return true; $f ;");
97
-			// PHP 5.x compat
98
-			if ($ok = @eval("return true; $f ;") === false) {
99
-				// Code syntaxiquement faux (critere etc mal programme')
100
-				$msg = _T('zbug_erreur_compilation');
101
-				erreur_squelette($msg, $boucle);
102
-				// continuer pour trouver d'autres fautes eventuelles
103
-				// mais prevenir que c'est mort
104
-				$nom = '';
105
-			}
106
-		} catch (\ParseError $e) {
107
-			// Code syntaxiquement faux (critere etc mal programme')
108
-			$msg = _T('zbug_erreur_compilation') . ' | Line ' . $e->getLine() . ' : ' . $e->getMessage();
109
-			erreur_squelette($msg, $boucle);
110
-			// continuer pour trouver d'autres fautes eventuelles
111
-			// mais prevenir que c'est mort
112
-			$nom = '';
113
-		}
114
-
115
-		// Contexte de compil inutile a present
116
-		// (mais la derniere valeur de $boucle est utilisee ci-dessous)
117
-		$skel_code[$id] = $f;
118
-	}
119
-
120
-	$code = '';
121
-	if ($nom) {
122
-		// Si le code est bon, concatener et mettre en cache
123
-		if (function_exists($nom)) {
124
-			$code = squelette_traduit($skel, $source, $phpfile, $skel_code);
125
-		} else {
126
-			// code semantiquement faux: bug du compilateur
127
-			// $boucle est en fait ici la fct principale du squelette
128
-			$msg = _T('zbug_erreur_compilation');
129
-			erreur_squelette($msg, $boucle);
130
-			$nom = '';
131
-		}
132
-	}
133
-
134
-	if (defined('_VAR_MODE') and _VAR_MODE == 'debug') {
135
-
136
-		// Tracer ce qui vient d'etre compile
137
-		$GLOBALS['debug_objets']['code'][$nom . 'tout'] = $code;
138
-
139
-		// si c'est ce que demande le debusqueur, lui passer la main
140
-		if ($GLOBALS['debug_objets']['sourcefile']
141
-			and (_request('var_mode_objet') == $nom)
142
-			and (_request('var_mode_affiche') == 'code')
143
-		) {
144
-			erreur_squelette();
145
-		}
146
-	}
147
-
148
-	return $nom ? $nom : false;
46
+    $nom = calculer_nom_fonction_squel($squelette, $mime_type, $connect);
47
+
48
+    //  si deja en memoire (INCLURE  a repetition) c'est bon.
49
+    if (function_exists($nom)) {
50
+        return $nom;
51
+    }
52
+
53
+    if (defined('_VAR_MODE') and _VAR_MODE == 'debug') {
54
+        $GLOBALS['debug_objets']['courant'] = $nom;
55
+    }
56
+
57
+    $phpfile = sous_repertoire(_DIR_SKELS, '', false, true) . $nom . '.php';
58
+
59
+    // si squelette est deja compile et perenne, le charger
60
+    if (!squelette_obsolete($phpfile, $source)) {
61
+        include_once $phpfile;
62
+        #if (!squelette_obsolete($phpfile, $source)
63
+        #  AND lire_fichier ($phpfile, $skel_code,
64
+        #  array('critique' => 'oui', 'phpcheck' => 'oui'))){
65
+        ## eval('?'.'>'.$skel_code);
66
+        #	 spip_log($skel_code, 'comp')
67
+        #}
68
+    }
69
+
70
+    if (file_exists($lib = $squelette . '_fonctions' . '.php')) {
71
+        include_once $lib;
72
+    }
73
+
74
+    // tester si le eval ci-dessus a mis le squelette en memoire
75
+
76
+    if (function_exists($nom)) {
77
+        return $nom;
78
+    }
79
+
80
+    // charger le source, si possible, et compiler 
81
+    $skel_code = '';
82
+    if (lire_fichier($source, $skel)) {
83
+        $compiler = charger_fonction('compiler', 'public');
84
+        $skel_code = $compiler($skel, $nom, $gram, $source, $connect);
85
+    }
86
+
87
+    // Ne plus rien faire si le compilateur n'a pas pu operer.
88
+    if (!$skel_code) {
89
+        return false;
90
+    }
91
+
92
+    foreach ($skel_code as $id => $boucle) {
93
+        $f = $boucle->return;
94
+        try {
95
+            // @todo : a remplacer quand _PHP_MIN >= 7
96
+            // eval("return true; $f ;");
97
+            // PHP 5.x compat
98
+            if ($ok = @eval("return true; $f ;") === false) {
99
+                // Code syntaxiquement faux (critere etc mal programme')
100
+                $msg = _T('zbug_erreur_compilation');
101
+                erreur_squelette($msg, $boucle);
102
+                // continuer pour trouver d'autres fautes eventuelles
103
+                // mais prevenir que c'est mort
104
+                $nom = '';
105
+            }
106
+        } catch (\ParseError $e) {
107
+            // Code syntaxiquement faux (critere etc mal programme')
108
+            $msg = _T('zbug_erreur_compilation') . ' | Line ' . $e->getLine() . ' : ' . $e->getMessage();
109
+            erreur_squelette($msg, $boucle);
110
+            // continuer pour trouver d'autres fautes eventuelles
111
+            // mais prevenir que c'est mort
112
+            $nom = '';
113
+        }
114
+
115
+        // Contexte de compil inutile a present
116
+        // (mais la derniere valeur de $boucle est utilisee ci-dessous)
117
+        $skel_code[$id] = $f;
118
+    }
119
+
120
+    $code = '';
121
+    if ($nom) {
122
+        // Si le code est bon, concatener et mettre en cache
123
+        if (function_exists($nom)) {
124
+            $code = squelette_traduit($skel, $source, $phpfile, $skel_code);
125
+        } else {
126
+            // code semantiquement faux: bug du compilateur
127
+            // $boucle est en fait ici la fct principale du squelette
128
+            $msg = _T('zbug_erreur_compilation');
129
+            erreur_squelette($msg, $boucle);
130
+            $nom = '';
131
+        }
132
+    }
133
+
134
+    if (defined('_VAR_MODE') and _VAR_MODE == 'debug') {
135
+
136
+        // Tracer ce qui vient d'etre compile
137
+        $GLOBALS['debug_objets']['code'][$nom . 'tout'] = $code;
138
+
139
+        // si c'est ce que demande le debusqueur, lui passer la main
140
+        if ($GLOBALS['debug_objets']['sourcefile']
141
+            and (_request('var_mode_objet') == $nom)
142
+            and (_request('var_mode_affiche') == 'code')
143
+        ) {
144
+            erreur_squelette();
145
+        }
146
+    }
147
+
148
+    return $nom ? $nom : false;
149 149
 }
150 150
 
151 151
 function squelette_traduit($squelette, $sourcefile, $phpfile, $boucles) {
152 152
 
153
-	// Le dernier index est '' (fonction principale)
154
-	$noms = substr(join(', ', array_keys($boucles)), 0, -2);
155
-	if (CODE_COMMENTE) {
156
-		$code = "
153
+    // Le dernier index est '' (fonction principale)
154
+    $noms = substr(join(', ', array_keys($boucles)), 0, -2);
155
+    if (CODE_COMMENTE) {
156
+        $code = "
157 157
 /*
158 158
  * Squelette : $sourcefile
159 159
  * Date :      " . gmdate("D, d M Y H:i:s", @filemtime($sourcefile)) . " GMT
160 160
  * Compile :   " . gmdate("D, d M Y H:i:s", time()) . " GMT
161 161
  * " . (!$boucles ? "Pas de boucle" : ("Boucles :   " . $noms)) . "
162 162
  */ ";
163
-	}
163
+    }
164 164
 
165
-	$code = '<' . "?php\n" . $code . join('', $boucles) . "\n?" . '>';
166
-	if (!defined('_VAR_NOCACHE') or !_VAR_NOCACHE) {
167
-		ecrire_fichier($phpfile, $code);
168
-	}
165
+    $code = '<' . "?php\n" . $code . join('', $boucles) . "\n?" . '>';
166
+    if (!defined('_VAR_NOCACHE') or !_VAR_NOCACHE) {
167
+        ecrire_fichier($phpfile, $code);
168
+    }
169 169
 
170
-	return $code;
170
+    return $code;
171 171
 }
172 172
 
173 173
 // Le squelette compile est-il trop vieux ?
174 174
 // https://code.spip.net/@squelette_obsolete
175 175
 function squelette_obsolete($skel, $squelette) {
176
-	static $date_change = null;
177
-	// ne verifier la date de mes_fonctions et mes_options qu'une seule fois
178
-	// par hit
179
-	if (is_null($date_change)) {
180
-		if (@file_exists($fonc = 'mes_fonctions.php')) {
181
-			$date_change = @filemtime($fonc);
182
-		} # compatibilite
183
-		if (defined('_FILE_OPTIONS')) {
184
-			$date_change = max($date_change, @filemtime(_FILE_OPTIONS));
185
-		}
186
-	}
187
-
188
-	return (
189
-		(defined('_VAR_MODE') and in_array(_VAR_MODE, array('recalcul', 'preview', 'debug')))
190
-		or !@file_exists($skel)
191
-		or ((@file_exists($squelette) ? @filemtime($squelette) : 0)
192
-			> ($date = @filemtime($skel)))
193
-		or ($date_change > $date)
194
-	);
176
+    static $date_change = null;
177
+    // ne verifier la date de mes_fonctions et mes_options qu'une seule fois
178
+    // par hit
179
+    if (is_null($date_change)) {
180
+        if (@file_exists($fonc = 'mes_fonctions.php')) {
181
+            $date_change = @filemtime($fonc);
182
+        } # compatibilite
183
+        if (defined('_FILE_OPTIONS')) {
184
+            $date_change = max($date_change, @filemtime(_FILE_OPTIONS));
185
+        }
186
+    }
187
+
188
+    return (
189
+        (defined('_VAR_MODE') and in_array(_VAR_MODE, array('recalcul', 'preview', 'debug')))
190
+        or !@file_exists($skel)
191
+        or ((@file_exists($squelette) ? @filemtime($squelette) : 0)
192
+            > ($date = @filemtime($skel)))
193
+        or ($date_change > $date)
194
+    );
195 195
 }
196 196
 
197 197
 // Activer l'invalideur de session
198 198
 // https://code.spip.net/@invalideur_session
199 199
 function invalideur_session(&$Cache, $code = null) {
200
-	$Cache['session'] = spip_session();
200
+    $Cache['session'] = spip_session();
201 201
 
202
-	return $code;
202
+    return $code;
203 203
 }
204 204
 
205 205
 
206 206
 // https://code.spip.net/@analyse_resultat_skel
207 207
 function analyse_resultat_skel($nom, $cache, $corps, $source = '') {
208
-	static $filtres = array();
209
-	$headers = array();
210
-
211
-	// Recupere les < ?php header('Xx: y'); ? > pour $page['headers']
212
-	// note: on essaie d'attrapper aussi certains de ces entetes codes
213
-	// "a la main" dans les squelettes, mais evidemment sans exhaustivite
214
-	if (stripos($corps, 'header') !== false
215
-		and preg_match_all(
216
-			'/(<[?]php\s+)@?header\s*\(\s*.([^:\'"]*):?\s*([^)]*)[^)]\s*\)\s*[;]?\s*[?]>/ims',
217
-			$corps, $regs, PREG_SET_ORDER)
218
-	) {
219
-		foreach ($regs as $r) {
220
-			$corps = str_replace($r[0], '', $corps);
221
-			# $j = Content-Type, et pas content-TYPE.
222
-			$j = join('-', array_map('ucwords', explode('-', strtolower($r[2]))));
223
-
224
-			if ($j == 'X-Spip-Filtre' and isset($headers[$j])) {
225
-				$headers[$j] .= "|" . $r[3];
226
-			} else {
227
-				$headers[$j] = $r[3];
228
-			}
229
-		}
230
-	}
231
-	// S'agit-il d'un resultat constant ou contenant du code php
232
-	$process_ins = (
233
-		strpos($corps, '<' . '?') === false
234
-		or
235
-		(strpos($corps, '<' . '?xml') !== false and
236
-			strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
237
-	)
238
-		? 'html'
239
-		: 'php';
240
-
241
-	$skel = array(
242
-		'squelette' => $nom,
243
-		'source' => $source,
244
-		'process_ins' => $process_ins,
245
-		'invalideurs' => $cache,
246
-		'entetes' => $headers,
247
-		'duree' => isset($headers['X-Spip-Cache']) ? intval($headers['X-Spip-Cache']) : 0
248
-	);
249
-
250
-	// traiter #FILTRE{} et filtres
251
-	if (!isset($filtres[$nom])) {
252
-		$filtres[$nom] = pipeline('declarer_filtres_squelettes', array('args' => $skel, 'data' => array()));
253
-	}
254
-	$filtres_headers = array();
255
-	if (isset($headers['X-Spip-Filtre']) and strlen($headers['X-Spip-Filtre'])) {
256
-		$filtres_headers = array_filter(explode('|', $headers['X-Spip-Filtre']));
257
-		unset($headers['X-Spip-Filtre']);
258
-	}
259
-	if (count($filtres[$nom]) or count($filtres_headers)) {
260
-		include_spip('public/sandbox');
261
-		$corps = sandbox_filtrer_squelette($skel, $corps, $filtres_headers, $filtres[$nom]);
262
-
263
-		if ($process_ins == 'html') {
264
-			$skel['process_ins'] = (
265
-				strpos($corps, '<' . '?') === false
266
-				or
267
-				(strpos($corps, '<' . '?xml') !== false and
268
-					strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
269
-			)
270
-				? 'html'
271
-				: 'php';
272
-		}
273
-	}
274
-
275
-	$skel['entetes'] = $headers;
276
-	$skel['texte'] = $corps;
277
-
278
-	return $skel;
208
+    static $filtres = array();
209
+    $headers = array();
210
+
211
+    // Recupere les < ?php header('Xx: y'); ? > pour $page['headers']
212
+    // note: on essaie d'attrapper aussi certains de ces entetes codes
213
+    // "a la main" dans les squelettes, mais evidemment sans exhaustivite
214
+    if (stripos($corps, 'header') !== false
215
+        and preg_match_all(
216
+            '/(<[?]php\s+)@?header\s*\(\s*.([^:\'"]*):?\s*([^)]*)[^)]\s*\)\s*[;]?\s*[?]>/ims',
217
+            $corps, $regs, PREG_SET_ORDER)
218
+    ) {
219
+        foreach ($regs as $r) {
220
+            $corps = str_replace($r[0], '', $corps);
221
+            # $j = Content-Type, et pas content-TYPE.
222
+            $j = join('-', array_map('ucwords', explode('-', strtolower($r[2]))));
223
+
224
+            if ($j == 'X-Spip-Filtre' and isset($headers[$j])) {
225
+                $headers[$j] .= "|" . $r[3];
226
+            } else {
227
+                $headers[$j] = $r[3];
228
+            }
229
+        }
230
+    }
231
+    // S'agit-il d'un resultat constant ou contenant du code php
232
+    $process_ins = (
233
+        strpos($corps, '<' . '?') === false
234
+        or
235
+        (strpos($corps, '<' . '?xml') !== false and
236
+            strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
237
+    )
238
+        ? 'html'
239
+        : 'php';
240
+
241
+    $skel = array(
242
+        'squelette' => $nom,
243
+        'source' => $source,
244
+        'process_ins' => $process_ins,
245
+        'invalideurs' => $cache,
246
+        'entetes' => $headers,
247
+        'duree' => isset($headers['X-Spip-Cache']) ? intval($headers['X-Spip-Cache']) : 0
248
+    );
249
+
250
+    // traiter #FILTRE{} et filtres
251
+    if (!isset($filtres[$nom])) {
252
+        $filtres[$nom] = pipeline('declarer_filtres_squelettes', array('args' => $skel, 'data' => array()));
253
+    }
254
+    $filtres_headers = array();
255
+    if (isset($headers['X-Spip-Filtre']) and strlen($headers['X-Spip-Filtre'])) {
256
+        $filtres_headers = array_filter(explode('|', $headers['X-Spip-Filtre']));
257
+        unset($headers['X-Spip-Filtre']);
258
+    }
259
+    if (count($filtres[$nom]) or count($filtres_headers)) {
260
+        include_spip('public/sandbox');
261
+        $corps = sandbox_filtrer_squelette($skel, $corps, $filtres_headers, $filtres[$nom]);
262
+
263
+        if ($process_ins == 'html') {
264
+            $skel['process_ins'] = (
265
+                strpos($corps, '<' . '?') === false
266
+                or
267
+                (strpos($corps, '<' . '?xml') !== false and
268
+                    strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
269
+            )
270
+                ? 'html'
271
+                : 'php';
272
+        }
273
+    }
274
+
275
+    $skel['entetes'] = $headers;
276
+    $skel['texte'] = $corps;
277
+
278
+    return $skel;
279 279
 }
280 280
 
281 281
 //
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 inserer_balise_dynamique(balise_%s_dyn(%s), array(%s));
290 290
 if ($lang_select) lang_select();
291 291
 ?'
292
-	. '>');
292
+    . '>');
293 293
 
294 294
 /**
295 295
  * Synthétise une balise dynamique : crée l'appel à l'inclusion
@@ -309,29 +309,29 @@  discard block
 block discarded – undo
309 309
  *     Code PHP pour inclure le squelette de la balise dynamique
310 310
  **/
311 311
 function synthetiser_balise_dynamique($nom, $args, $file, $context_compil) {
312
-	if (strncmp($file, "/", 1) !== 0) {
313
-		$file = './" . _DIR_RACINE . "' . $file;
314
-	}
315
-
316
-	$lang = $context_compil[4];
317
-	if (preg_match(",\W,", $lang)) {
318
-		$lang = '';
319
-	}
320
-
321
-	$args = array_map('argumenter_squelette', $args);
322
-	if (!empty($context_compil['appel_php_depuis_modele'])) {
323
-		$args[0] = 'arguments_balise_dyn_depuis_modele('.$args[0].')';
324
-	}
325
-	$args = join(', ', $args);
326
-
327
-	$r = sprintf(CODE_INCLURE_BALISE,
328
-		$file,
329
-		$lang,
330
-		$nom,
331
-		$args,
332
-		join(', ', array_map('_q', $context_compil)));
333
-
334
-	return $r;
312
+    if (strncmp($file, "/", 1) !== 0) {
313
+        $file = './" . _DIR_RACINE . "' . $file;
314
+    }
315
+
316
+    $lang = $context_compil[4];
317
+    if (preg_match(",\W,", $lang)) {
318
+        $lang = '';
319
+    }
320
+
321
+    $args = array_map('argumenter_squelette', $args);
322
+    if (!empty($context_compil['appel_php_depuis_modele'])) {
323
+        $args[0] = 'arguments_balise_dyn_depuis_modele('.$args[0].')';
324
+    }
325
+    $args = join(', ', $args);
326
+
327
+    $r = sprintf(CODE_INCLURE_BALISE,
328
+        $file,
329
+        $lang,
330
+        $nom,
331
+        $args,
332
+        join(', ', array_map('_q', $context_compil)));
333
+
334
+    return $r;
335 335
 }
336 336
 
337 337
 /**
@@ -349,18 +349,18 @@  discard block
 block discarded – undo
349 349
  **/
350 350
 function argumenter_squelette($v) {
351 351
 
352
-	if (is_object($v)) {
353
-		return var_export($v, true);
354
-	} elseif (!is_array($v)) {
355
-		return "'" . texte_script($v) . "'";
356
-	} else {
357
-		$out = array();
358
-		foreach ($v as $k => $val) {
359
-			$out [] = argumenter_squelette($k) . '=>' . argumenter_squelette($val);
360
-		}
361
-
362
-		return 'array(' . join(", ", $out) . ')';
363
-	}
352
+    if (is_object($v)) {
353
+        return var_export($v, true);
354
+    } elseif (!is_array($v)) {
355
+        return "'" . texte_script($v) . "'";
356
+    } else {
357
+        $out = array();
358
+        foreach ($v as $k => $val) {
359
+            $out [] = argumenter_squelette($k) . '=>' . argumenter_squelette($val);
360
+        }
361
+
362
+        return 'array(' . join(", ", $out) . ')';
363
+    }
364 364
 }
365 365
 
366 366
 
@@ -391,85 +391,85 @@  discard block
 block discarded – undo
391 391
  *     Code PHP d'exécutant l'inclusion du squelette (ou texte) de la balise dynamique
392 392
  **/
393 393
 function executer_balise_dynamique($nom, $args, $context_compil) {
394
-	/** @var string Nom de la balise à charger (balise demandée ou balise générique) */
395
-	$nom_balise = $nom;
396
-	/** @var string Nom de la balise générique (si utilisée) */
397
-	$nom_balise_generique = "";
398
-
399
-	$appel_php_depuis_modele = false;
400
-	if (is_array($context_compil)
401
-	  and !is_numeric($context_compil[3])
402
-	  and empty($context_compil[0])
403
-		and empty($context_compil[1])
404
-		and empty($context_compil[2])
405
-		and empty($context_compil[3])) {
406
-		$appel_php_depuis_modele = true;
407
-	}
408
-
409
-	if (!$fonction_balise = charger_fonction($nom_balise, 'balise', true)) {
410
-		// Calculer un nom générique (ie. 'formulaire_' dans 'formulaire_editer_article')
411
-		if ($balise_generique = chercher_balise_generique($nom)) {
412
-			// injecter en premier arg le nom de la balise 
413
-			array_unshift($args, $nom);
414
-			$nom_balise_generique = $balise_generique['nom_generique'];
415
-			$fonction_balise = $balise_generique['fonction_generique'];
416
-			$nom_balise = $nom_balise_generique;
417
-		}
418
-		unset($balise_generique);
419
-	}
420
-
421
-	if (!$fonction_balise) {
422
-		$msg = array('zbug_balise_inexistante', array('from' => 'CVT', 'balise' => $nom));
423
-		erreur_squelette($msg, $context_compil);
424
-
425
-		return '';
426
-	}
427
-
428
-	// retrouver le fichier qui a déclaré la fonction
429
-	// même si la fonction dynamique est déclarée dans un fichier de fonctions.
430
-	// Attention sous windows, getFileName() retourne un antislash. 
431
-	$reflector = new ReflectionFunction($fonction_balise);
432
-	$file = str_replace('\\', '/', $reflector->getFileName());
433
-	if (strncmp($file, str_replace('\\', '/', _ROOT_RACINE), strlen(_ROOT_RACINE)) === 0) {
434
-		$file = substr($file, strlen(_ROOT_RACINE));
435
-	}
436
-
437
-	// Y a-t-il une fonction de traitement des arguments ?
438
-	$f = 'balise_' . $nom_balise . '_stat';
439
-
440
-	$r = !function_exists($f) ? $args : $f($args, $context_compil);
441
-
442
-	if (!is_array($r)) {
443
-		return $r;
444
-	}
445
-
446
-	// verifier que la fonction dyn est la, 
447
-	// sinon se replier sur la generique si elle existe
448
-	if (!function_exists('balise_' . $nom_balise . '_dyn')) {
449
-		if (
450
-			$balise_generique = chercher_balise_generique($nom)
451
-			and $nom_balise_generique = $balise_generique['nom_generique']
452
-			and $file = include_spip("balise/" . strtolower($nom_balise_generique))
453
-			and function_exists('balise_' . $nom_balise_generique . '_dyn')
454
-		) {
455
-			// et lui injecter en premier arg le nom de la balise 
456
-			array_unshift($r, $nom);
457
-			$nom_balise = $nom_balise_generique;
458
-			if (!_DIR_RESTREINT) {
459
-				$file = _DIR_RESTREINT_ABS . $file;
460
-			}
461
-		} else {
462
-			$msg = array('zbug_balise_inexistante', array('from' => 'CVT', 'balise' => $nom));
463
-			erreur_squelette($msg, $context_compil);
464
-
465
-			return '';
466
-		}
467
-	}
468
-
469
-	if ($appel_php_depuis_modele) {
470
-		$context_compil['appel_php_depuis_modele'] = true;
471
-	}
472
-	return synthetiser_balise_dynamique($nom_balise, $r, $file, $context_compil);
394
+    /** @var string Nom de la balise à charger (balise demandée ou balise générique) */
395
+    $nom_balise = $nom;
396
+    /** @var string Nom de la balise générique (si utilisée) */
397
+    $nom_balise_generique = "";
398
+
399
+    $appel_php_depuis_modele = false;
400
+    if (is_array($context_compil)
401
+      and !is_numeric($context_compil[3])
402
+      and empty($context_compil[0])
403
+        and empty($context_compil[1])
404
+        and empty($context_compil[2])
405
+        and empty($context_compil[3])) {
406
+        $appel_php_depuis_modele = true;
407
+    }
408
+
409
+    if (!$fonction_balise = charger_fonction($nom_balise, 'balise', true)) {
410
+        // Calculer un nom générique (ie. 'formulaire_' dans 'formulaire_editer_article')
411
+        if ($balise_generique = chercher_balise_generique($nom)) {
412
+            // injecter en premier arg le nom de la balise 
413
+            array_unshift($args, $nom);
414
+            $nom_balise_generique = $balise_generique['nom_generique'];
415
+            $fonction_balise = $balise_generique['fonction_generique'];
416
+            $nom_balise = $nom_balise_generique;
417
+        }
418
+        unset($balise_generique);
419
+    }
420
+
421
+    if (!$fonction_balise) {
422
+        $msg = array('zbug_balise_inexistante', array('from' => 'CVT', 'balise' => $nom));
423
+        erreur_squelette($msg, $context_compil);
424
+
425
+        return '';
426
+    }
427
+
428
+    // retrouver le fichier qui a déclaré la fonction
429
+    // même si la fonction dynamique est déclarée dans un fichier de fonctions.
430
+    // Attention sous windows, getFileName() retourne un antislash. 
431
+    $reflector = new ReflectionFunction($fonction_balise);
432
+    $file = str_replace('\\', '/', $reflector->getFileName());
433
+    if (strncmp($file, str_replace('\\', '/', _ROOT_RACINE), strlen(_ROOT_RACINE)) === 0) {
434
+        $file = substr($file, strlen(_ROOT_RACINE));
435
+    }
436
+
437
+    // Y a-t-il une fonction de traitement des arguments ?
438
+    $f = 'balise_' . $nom_balise . '_stat';
439
+
440
+    $r = !function_exists($f) ? $args : $f($args, $context_compil);
441
+
442
+    if (!is_array($r)) {
443
+        return $r;
444
+    }
445
+
446
+    // verifier que la fonction dyn est la, 
447
+    // sinon se replier sur la generique si elle existe
448
+    if (!function_exists('balise_' . $nom_balise . '_dyn')) {
449
+        if (
450
+            $balise_generique = chercher_balise_generique($nom)
451
+            and $nom_balise_generique = $balise_generique['nom_generique']
452
+            and $file = include_spip("balise/" . strtolower($nom_balise_generique))
453
+            and function_exists('balise_' . $nom_balise_generique . '_dyn')
454
+        ) {
455
+            // et lui injecter en premier arg le nom de la balise 
456
+            array_unshift($r, $nom);
457
+            $nom_balise = $nom_balise_generique;
458
+            if (!_DIR_RESTREINT) {
459
+                $file = _DIR_RESTREINT_ABS . $file;
460
+            }
461
+        } else {
462
+            $msg = array('zbug_balise_inexistante', array('from' => 'CVT', 'balise' => $nom));
463
+            erreur_squelette($msg, $context_compil);
464
+
465
+            return '';
466
+        }
467
+    }
468
+
469
+    if ($appel_php_depuis_modele) {
470
+        $context_compil['appel_php_depuis_modele'] = true;
471
+    }
472
+    return synthetiser_balise_dynamique($nom_balise, $r, $file, $context_compil);
473 473
 
474 474
 }
475 475
 
@@ -485,23 +485,23 @@  discard block
 block discarded – undo
485 485
  * @return array|null
486 486
  */
487 487
 function chercher_balise_generique($nom) {
488
-	if (false === strpos($nom, "_")) {
489
-		return null;
490
-	}
491
-	$nom_generique = $nom;
492
-	while (false !== ($p = strrpos($nom_generique, "_"))) {
493
-		$nom_generique = substr($nom_generique, 0, $p + 1);
494
-		$fonction_generique = charger_fonction($nom_generique, 'balise', true);
495
-		if ($fonction_generique) {
496
-			return [
497
-				'nom' => $nom,
498
-				'nom_generique' => $nom_generique,
499
-				'fonction_generique' => $fonction_generique,
500
-			];
501
-		}
502
-		$nom_generique = substr($nom_generique, 0, -1);
503
-	}
504
-	return null;
488
+    if (false === strpos($nom, "_")) {
489
+        return null;
490
+    }
491
+    $nom_generique = $nom;
492
+    while (false !== ($p = strrpos($nom_generique, "_"))) {
493
+        $nom_generique = substr($nom_generique, 0, $p + 1);
494
+        $fonction_generique = charger_fonction($nom_generique, 'balise', true);
495
+        if ($fonction_generique) {
496
+            return [
497
+                'nom' => $nom,
498
+                'nom_generique' => $nom_generique,
499
+                'fonction_generique' => $fonction_generique,
500
+            ];
501
+        }
502
+        $nom_generique = substr($nom_generique, 0, -1);
503
+    }
504
+    return null;
505 505
 }
506 506
 
507 507
 
@@ -525,27 +525,27 @@  discard block
 block discarded – undo
525 525
  * @return null;
526 526
  **/
527 527
 function lang_select_public($lang, $lang_select, $titre = null) {
528
-	// Cas 1. forcer_lang = true et pas de critere {lang_select}
529
-	if (isset($GLOBALS['forcer_lang']) and $GLOBALS['forcer_lang']
530
-		and $lang_select !== 'oui'
531
-	) {
532
-		$lang = $GLOBALS['spip_lang'];
533
-	} // Cas 2. l'objet n'a pas de langue definie (ou definie a '')
534
-	elseif (!strlen($lang)) {
535
-		$lang = $GLOBALS['spip_lang'];
536
-	} // Cas 3. l'objet est multilingue !
537
-	elseif ($lang_select !== 'oui'
538
-		and strlen($titre) > 10
539
-		and strpos($titre, '<multi>') !== false
540
-		and strpos(echappe_html($titre), '<multi>') !== false
541
-	) {
542
-		$lang = $GLOBALS['spip_lang'];
543
-	}
544
-
545
-	// faire un lang_select() eventuellement sur la langue inchangee
546
-	lang_select($lang);
547
-
548
-	return;
528
+    // Cas 1. forcer_lang = true et pas de critere {lang_select}
529
+    if (isset($GLOBALS['forcer_lang']) and $GLOBALS['forcer_lang']
530
+        and $lang_select !== 'oui'
531
+    ) {
532
+        $lang = $GLOBALS['spip_lang'];
533
+    } // Cas 2. l'objet n'a pas de langue definie (ou definie a '')
534
+    elseif (!strlen($lang)) {
535
+        $lang = $GLOBALS['spip_lang'];
536
+    } // Cas 3. l'objet est multilingue !
537
+    elseif ($lang_select !== 'oui'
538
+        and strlen($titre) > 10
539
+        and strpos($titre, '<multi>') !== false
540
+        and strpos(echappe_html($titre), '<multi>') !== false
541
+    ) {
542
+        $lang = $GLOBALS['spip_lang'];
543
+    }
544
+
545
+    // faire un lang_select() eventuellement sur la langue inchangee
546
+    lang_select($lang);
547
+
548
+    return;
549 549
 }
550 550
 
551 551
 
@@ -553,21 +553,21 @@  discard block
 block discarded – undo
553 553
 // il faut le nettoyer car il pourrait etre injecte en SQL
554 554
 // https://code.spip.net/@nettoyer_env_doublons
555 555
 function nettoyer_env_doublons($envd) {
556
-	foreach ($envd as $table => $liste) {
557
-		$n = '';
558
-		foreach (explode(',', $liste) as $val) {
559
-			if ($a = intval($val) and $val === strval($a)) {
560
-				$n .= ',' . $val;
561
-			}
562
-		}
563
-		if (strlen($n)) {
564
-			$envd[$table] = $n;
565
-		} else {
566
-			unset($envd[$table]);
567
-		}
568
-	}
569
-
570
-	return $envd;
556
+    foreach ($envd as $table => $liste) {
557
+        $n = '';
558
+        foreach (explode(',', $liste) as $val) {
559
+            if ($a = intval($val) and $val === strval($a)) {
560
+                $n .= ',' . $val;
561
+            }
562
+        }
563
+        if (strlen($n)) {
564
+            $envd[$table] = $n;
565
+        } else {
566
+            unset($envd[$table]);
567
+        }
568
+    }
569
+
570
+    return $envd;
571 571
 }
572 572
 
573 573
 /**
@@ -586,21 +586,21 @@  discard block
 block discarded – undo
586 586
  *     Opérateur trouvé (SELF ou SUBSELECT) sinon false.
587 587
  **/
588 588
 function match_self($w) {
589
-	if (is_string($w)) {
590
-		return false;
591
-	}
592
-	if (is_array($w)) {
593
-		if (in_array(reset($w), array("SELF", "SUBSELECT"))) {
594
-			return $w;
595
-		}
596
-		foreach (array_filter($w, 'is_array') as $sw) {
597
-			if ($m = match_self($sw)) {
598
-				return $m;
599
-			}
600
-		}
601
-	}
602
-
603
-	return false;
589
+    if (is_string($w)) {
590
+        return false;
591
+    }
592
+    if (is_array($w)) {
593
+        if (in_array(reset($w), array("SELF", "SUBSELECT"))) {
594
+            return $w;
595
+        }
596
+        foreach (array_filter($w, 'is_array') as $sw) {
597
+            if ($m = match_self($sw)) {
598
+                return $m;
599
+            }
600
+        }
601
+    }
602
+
603
+    return false;
604 604
 }
605 605
 
606 606
 /**
@@ -616,16 +616,16 @@  discard block
 block discarded – undo
616 616
  *     est remplacée par son code.
617 617
  **/
618 618
 function remplace_sous_requete($w, $sousrequete) {
619
-	if (is_array($w)) {
620
-		if (in_array(reset($w), array("SELF", "SUBSELECT"))) {
621
-			return $sousrequete;
622
-		}
623
-		foreach ($w as $k => $sw) {
624
-			$w[$k] = remplace_sous_requete($sw, $sousrequete);
625
-		}
626
-	}
627
-
628
-	return $w;
619
+    if (is_array($w)) {
620
+        if (in_array(reset($w), array("SELF", "SUBSELECT"))) {
621
+            return $sousrequete;
622
+        }
623
+        foreach ($w as $k => $sw) {
624
+            $w[$k] = remplace_sous_requete($sw, $sousrequete);
625
+        }
626
+    }
627
+
628
+    return $w;
629 629
 }
630 630
 
631 631
 /**
@@ -639,17 +639,17 @@  discard block
 block discarded – undo
639 639
  *     - Conditions avec des sous requêtes
640 640
  **/
641 641
 function trouver_sous_requetes($where) {
642
-	$where_simples = array();
643
-	$where_sous = array();
644
-	foreach ($where as $k => $w) {
645
-		if (match_self($w)) {
646
-			$where_sous[$k] = $w;
647
-		} else {
648
-			$where_simples[$k] = $w;
649
-		}
650
-	}
651
-
652
-	return array($where_simples, $where_sous);
642
+    $where_simples = array();
643
+    $where_sous = array();
644
+    foreach ($where as $k => $w) {
645
+        if (match_self($w)) {
646
+            $where_sous[$k] = $w;
647
+        } else {
648
+            $where_simples[$k] = $w;
649
+        }
650
+    }
651
+
652
+    return array($where_simples, $where_sous);
653 653
 }
654 654
 
655 655
 
@@ -675,270 +675,270 @@  discard block
 block discarded – undo
675 675
  * @return resource
676 676
  */
677 677
 function calculer_select(
678
-	$select = array(),
679
-	$from = array(),
680
-	$from_type = array(),
681
-	$where = array(),
682
-	$join = array(),
683
-	$groupby = array(),
684
-	$orderby = array(),
685
-	$limit = '',
686
-	$having = array(),
687
-	$table = '',
688
-	$id = '',
689
-	$serveur = '',
690
-	$requeter = true
678
+    $select = array(),
679
+    $from = array(),
680
+    $from_type = array(),
681
+    $where = array(),
682
+    $join = array(),
683
+    $groupby = array(),
684
+    $orderby = array(),
685
+    $limit = '',
686
+    $having = array(),
687
+    $table = '',
688
+    $id = '',
689
+    $serveur = '',
690
+    $requeter = true
691 691
 ) {
692 692
 
693
-	// retirer les criteres vides:
694
-	// {X ?} avec X absent de l'URL
695
-	// {par #ENV{X}} avec X absent de l'URL
696
-	// IN sur collection vide (ce dernier devrait pouvoir etre fait a la compil)
697
-	$menage = false;
698
-	foreach ($where as $k => $v) {
699
-		if (is_array($v)) {
700
-			if ((count($v) >= 2) && ($v[0] == 'REGEXP') && ($v[2] == "'.*'")) {
701
-				$op = false;
702
-			} elseif ((count($v) >= 2) && ($v[0] == 'LIKE') && ($v[2] == "'%'")) {
703
-				$op = false;
704
-			} else {
705
-				$op = $v[0] ? $v[0] : $v;
706
-			}
707
-		} else {
708
-			$op = $v;
709
-		}
710
-		if ((!$op) or ($op == 1) or ($op == '0=0')) {
711
-			unset($where[$k]);
712
-			$menage = true;
713
-		}
714
-	}
715
-
716
-	// evacuer les eventuels groupby vide issus d'un calcul dynamique
717
-	$groupby = array_diff($groupby, array(''));
718
-
719
-	// remplacer les sous requetes recursives au calcul
720
-	list($where_simples, $where_sous) = trouver_sous_requetes($where);
721
-	foreach ($where_sous as $k => $w) {
722
-		$menage = true;
723
-		// on recupere la sous requete 
724
-		$sous = match_self($w);
725
-		if ($sous[0] == 'SELF') {
726
-			// c'est une sous requete identique a elle meme sous la forme (SELF,$select,$where)
727
-			array_push($where_simples, $sous[2]);
728
-			$wheresub = array(
729
-				$sous[2],
730
-				'0=0'
731
-			); // pour accepter une string et forcer a faire le menage car on a surement simplifie select et where
732
-			$jsub = $join;
733
-			// trouver les jointures utiles a
734
-			// reinjecter dans le where de la sous requete les conditions supplementaires des jointures qui y sont mentionnees
735
-			// ie L1.objet='article'
736
-			// on construit le where une fois, puis on ajoute les where complentaires si besoin, et on reconstruit le where en fonction
737
-			$i = 0;
738
-			do {
739
-				$where[$k] = remplace_sous_requete($w, "(" . calculer_select(
740
-						array($sous[1] . " AS id"),
741
-						$from,
742
-						$from_type,
743
-						$wheresub,
744
-						$jsub,
745
-						array(), array(), '',
746
-						$having, $table, $id, $serveur, false) . ")");
747
-				if (!$i) {
748
-					$i = 1;
749
-					$wherestring = calculer_where_to_string($where[$k]);
750
-					foreach ($join as $cle => $wj) {
751
-						if (count($wj) == 4
752
-							and strpos($wherestring, "{$cle}.") !== false
753
-						) {
754
-							$i = 0;
755
-							$wheresub[] = $wj[3];
756
-							unset($jsub[$cle][3]);
757
-						}
758
-					}
759
-				}
760
-			} while ($i++ < 1);
761
-		}
762
-		if ($sous[0] == 'SUBSELECT') {
763
-			// c'est une sous requete explicite sous la forme identique a sql_select : (SUBSELECT,$select,$from,$where,$groupby,$orderby,$limit,$having)
764
-			array_push($where_simples, $sous[3]); // est-ce utile dans ce cas ?
765
-			$where[$k] = remplace_sous_requete($w, "(" . calculer_select(
766
-					$sous[1], # select
767
-					$sous[2], #from
768
-					array(), #from_type
769
-					$sous[3] ? (is_array($sous[3]) ? $sous[3] : array($sous[3])) : array(),
770
-					#where, qui peut etre de la forme string comme dans sql_select
771
-					array(), #join
772
-					$sous[4] ? $sous[4] : array(), #groupby
773
-					$sous[5] ? $sous[5] : array(), #orderby
774
-					$sous[6], #limit
775
-					$sous[7] ? $sous[7] : array(), #having
776
-					$table, $id, $serveur, false
777
-				) . ")");
778
-		}
779
-		array_pop($where_simples);
780
-	}
781
-
782
-	foreach ($having as $k => $v) {
783
-		if ((!$v) or ($v == 1) or ($v == '0=0')) {
784
-			unset($having[$k]);
785
-		}
786
-	}
787
-
788
-	// Installer les jointures.
789
-	// Retirer celles seulement utiles aux criteres finalement absents mais
790
-	// parcourir de la plus recente a la moins recente pour pouvoir eliminer Ln
791
-	// si elle est seulement utile a Ln+1 elle meme inutile
792
-
793
-	$afrom = array();
794
-	$equiv = array();
795
-	$k = count($join);
796
-	foreach (array_reverse($join, true) as $cledef => $j) {
797
-		$cle = $cledef;
798
-		// le format de join est :
799
-		// array(table depart, cle depart [,cle arrivee[,condition optionnelle and ...]])
800
-		$join[$cle] = array_values($join[$cle]); // recalculer les cles car des unset ont pu perturber
801
-		if (count($join[$cle]) == 2) {
802
-			$join[$cle][] = $join[$cle][1];
803
-		}
804
-		if (count($join[$cle]) == 3) {
805
-			$join[$cle][] = '';
806
-		}
807
-		list($t, $c, $carr, $and) = $join[$cle];
808
-		// si le nom de la jointure n'a pas ete specifiee, on prend Lx avec x sont rang dans la liste
809
-		// pour compat avec ancienne convention
810
-		if (is_numeric($cle)) {
811
-			$cle = "L$k";
812
-		}
813
-		$cle_where_lie = "JOIN-$cle";
814
-		if (!$menage
815
-			or isset($afrom[$cle])
816
-			or calculer_jointnul($cle, $select)
817
-			or calculer_jointnul($cle, array_diff_key($join, array($cle => $join[$cle])))
818
-			or calculer_jointnul($cle, $having)
819
-			or calculer_jointnul($cle, array_diff_key($where_simples, [$cle_where_lie => '']))
820
-		) {
821
-			// corriger les references non explicites dans select
822
-			// ou groupby
823
-			foreach ($select as $i => $s) {
824
-				if ($s == $c) {
825
-					$select[$i] = "$cle.$c AS $c";
826
-					break;
827
-				}
828
-			}
829
-			foreach ($groupby as $i => $g) {
830
-				if ($g == $c) {
831
-					$groupby[$i] = "$cle.$c";
832
-					break;
833
-				}
834
-			}
835
-			// on garde une ecriture decomposee pour permettre une simplification ulterieure si besoin
836
-			// sans recours a preg_match
837
-			// un implode(' ',..) est fait dans reinjecte_joint un peu plus bas
838
-			$afrom[$t][$cle] = array(
839
-				"\n" .
840
-				(isset($from_type[$cle]) ? $from_type[$cle] : "INNER") . " JOIN",
841
-				$from[$cle],
842
-				"AS $cle",
843
-				"ON (",
844
-				"$cle.$c",
845
-				"=",
846
-				"$t.$carr",
847
-				($and ? "AND " . $and : "") .
848
-				")"
849
-			);
850
-			if (isset($afrom[$cle])) {
851
-				$afrom[$t] = $afrom[$t] + $afrom[$cle];
852
-				unset($afrom[$cle]);
853
-			}
854
-			$equiv[] = $carr;
855
-		} else {
856
-			unset($join[$cledef]);
857
-			if (isset($where_simples[$cle_where_lie])) {
858
-				unset($where_simples[$cle_where_lie]);
859
-				unset($where[$cle_where_lie]);
860
-			}
861
-		}
862
-		unset($from[$cle]);
863
-		$k--;
864
-	}
865
-
866
-	if (count($afrom)) {
867
-		// Regarder si la table principale ne sert finalement a rien comme dans
868
-		//<BOUCLE3(MOTS){id_article}{id_mot}> class='on'</BOUCLE3>
869
-		//<BOUCLE2(MOTS){id_article} />#TOTAL_BOUCLE<//B2>
870
-		//<BOUCLE5(RUBRIQUES){id_mot}{tout} />#TOTAL_BOUCLE<//B5>
871
-		// ou dans
872
-		//<BOUCLE8(HIERARCHIE){id_rubrique}{tout}{type='Squelette'}{inverse}{0,1}{lang_select=non} />#TOTAL_BOUCLE<//B8>
873
-		// qui comporte plusieurs jointures
874
-		// ou dans
875
-		// <BOUCLE6(ARTICLES){id_mot=2}{statut==.*} />#TOTAL_BOUCLE<//B6>
876
-		// <BOUCLE7(ARTICLES){id_mot>0}{statut?} />#TOTAL_BOUCLE<//B7>
877
-		// penser a regarder aussi la clause orderby pour ne pas simplifier abusivement
878
-		// <BOUCLE9(ARTICLES){recherche truc}{par titre}>#ID_ARTICLE</BOUCLE9>
879
-		// penser a regarder aussi la clause groubpy pour ne pas simplifier abusivement
880
-		// <BOUCLE10(EVENEMENTS){id_rubrique} />#TOTAL_BOUCLE<//B10>
881
-
882
-		$t = key($from);
883
-		$c = current($from);
884
-		reset($from);
885
-		$e = '/\b(' . "$t\\." . join("|" . $t . '\.', $equiv) . ')\b/';
886
-		if (!(strpos($t, ' ') or // jointure des le depart cf boucle_doc
887
-				calculer_jointnul($t, $select, $e) or
888
-				calculer_jointnul($t, $join, $e) or
889
-				calculer_jointnul($t, $where, $e) or
890
-				calculer_jointnul($t, $orderby, $e) or
891
-				calculer_jointnul($t, $groupby, $e) or
892
-				calculer_jointnul($t, $having, $e))
893
-			&& count($afrom[$t])
894
-		) {
895
-			$nfrom = reset($afrom[$t]);
896
-			$nt = key($afrom[$t]);
897
-			unset($from[$t]);
898
-			$from[$nt] = $nfrom[1];
899
-			unset($afrom[$t][$nt]);
900
-			$afrom[$nt] = $afrom[$t];
901
-			unset($afrom[$t]);
902
-			$e = '/\b' . preg_quote($nfrom[6]) . '\b/';
903
-			$t = $nfrom[4];
904
-			$alias = "";
905
-			// verifier que les deux cles sont homonymes, sinon installer un alias dans le select
906
-			$oldcle = explode('.', $nfrom[6]);
907
-			$oldcle = end($oldcle);
908
-			$newcle = explode('.', $nfrom[4]);
909
-			$newcle = end($newcle);
910
-			if ($newcle != $oldcle) {
911
-				// si l'ancienne cle etait deja dans le select avec un AS
912
-				// reprendre simplement ce AS
913
-				$as = '/\b' . preg_quote($nfrom[6]) . '\s+(AS\s+\w+)\b/';
914
-				if (preg_match($as, implode(',', $select), $m)) {
915
-					$alias = "";
916
-				} else {
917
-					$alias = ", " . $nfrom[4] . " AS $oldcle";
918
-				}
919
-			}
920
-			$select = remplacer_jointnul($t . $alias, $select, $e);
921
-			$join = remplacer_jointnul($t, $join, $e);
922
-			$where = remplacer_jointnul($t, $where, $e);
923
-			$having = remplacer_jointnul($t, $having, $e);
924
-			$groupby = remplacer_jointnul($t, $groupby, $e);
925
-			$orderby = remplacer_jointnul($t, $orderby, $e);
926
-		}
927
-		$from = reinjecte_joint($afrom, $from);
928
-	}
929
-	if (empty($GLOBALS['debug']) or !is_array($GLOBALS['debug'])) {
930
-		$wasdebug = empty($GLOBALS['debug']) ? false : $GLOBALS['debug'];
931
-		$GLOBALS['debug'] = array();
932
-		if ($wasdebug) {
933
-			$GLOBALS['debug']['debug'] = true;
934
-		}
935
-	}
936
-	$GLOBALS['debug']['aucasou'] = array($table, $id, $serveur, $requeter);
937
-	$r = sql_select($select, $from, $where,
938
-		$groupby, array_filter($orderby), $limit, $having, $serveur, $requeter);
939
-	unset($GLOBALS['debug']['aucasou']);
940
-
941
-	return $r;
693
+    // retirer les criteres vides:
694
+    // {X ?} avec X absent de l'URL
695
+    // {par #ENV{X}} avec X absent de l'URL
696
+    // IN sur collection vide (ce dernier devrait pouvoir etre fait a la compil)
697
+    $menage = false;
698
+    foreach ($where as $k => $v) {
699
+        if (is_array($v)) {
700
+            if ((count($v) >= 2) && ($v[0] == 'REGEXP') && ($v[2] == "'.*'")) {
701
+                $op = false;
702
+            } elseif ((count($v) >= 2) && ($v[0] == 'LIKE') && ($v[2] == "'%'")) {
703
+                $op = false;
704
+            } else {
705
+                $op = $v[0] ? $v[0] : $v;
706
+            }
707
+        } else {
708
+            $op = $v;
709
+        }
710
+        if ((!$op) or ($op == 1) or ($op == '0=0')) {
711
+            unset($where[$k]);
712
+            $menage = true;
713
+        }
714
+    }
715
+
716
+    // evacuer les eventuels groupby vide issus d'un calcul dynamique
717
+    $groupby = array_diff($groupby, array(''));
718
+
719
+    // remplacer les sous requetes recursives au calcul
720
+    list($where_simples, $where_sous) = trouver_sous_requetes($where);
721
+    foreach ($where_sous as $k => $w) {
722
+        $menage = true;
723
+        // on recupere la sous requete 
724
+        $sous = match_self($w);
725
+        if ($sous[0] == 'SELF') {
726
+            // c'est une sous requete identique a elle meme sous la forme (SELF,$select,$where)
727
+            array_push($where_simples, $sous[2]);
728
+            $wheresub = array(
729
+                $sous[2],
730
+                '0=0'
731
+            ); // pour accepter une string et forcer a faire le menage car on a surement simplifie select et where
732
+            $jsub = $join;
733
+            // trouver les jointures utiles a
734
+            // reinjecter dans le where de la sous requete les conditions supplementaires des jointures qui y sont mentionnees
735
+            // ie L1.objet='article'
736
+            // on construit le where une fois, puis on ajoute les where complentaires si besoin, et on reconstruit le where en fonction
737
+            $i = 0;
738
+            do {
739
+                $where[$k] = remplace_sous_requete($w, "(" . calculer_select(
740
+                        array($sous[1] . " AS id"),
741
+                        $from,
742
+                        $from_type,
743
+                        $wheresub,
744
+                        $jsub,
745
+                        array(), array(), '',
746
+                        $having, $table, $id, $serveur, false) . ")");
747
+                if (!$i) {
748
+                    $i = 1;
749
+                    $wherestring = calculer_where_to_string($where[$k]);
750
+                    foreach ($join as $cle => $wj) {
751
+                        if (count($wj) == 4
752
+                            and strpos($wherestring, "{$cle}.") !== false
753
+                        ) {
754
+                            $i = 0;
755
+                            $wheresub[] = $wj[3];
756
+                            unset($jsub[$cle][3]);
757
+                        }
758
+                    }
759
+                }
760
+            } while ($i++ < 1);
761
+        }
762
+        if ($sous[0] == 'SUBSELECT') {
763
+            // c'est une sous requete explicite sous la forme identique a sql_select : (SUBSELECT,$select,$from,$where,$groupby,$orderby,$limit,$having)
764
+            array_push($where_simples, $sous[3]); // est-ce utile dans ce cas ?
765
+            $where[$k] = remplace_sous_requete($w, "(" . calculer_select(
766
+                    $sous[1], # select
767
+                    $sous[2], #from
768
+                    array(), #from_type
769
+                    $sous[3] ? (is_array($sous[3]) ? $sous[3] : array($sous[3])) : array(),
770
+                    #where, qui peut etre de la forme string comme dans sql_select
771
+                    array(), #join
772
+                    $sous[4] ? $sous[4] : array(), #groupby
773
+                    $sous[5] ? $sous[5] : array(), #orderby
774
+                    $sous[6], #limit
775
+                    $sous[7] ? $sous[7] : array(), #having
776
+                    $table, $id, $serveur, false
777
+                ) . ")");
778
+        }
779
+        array_pop($where_simples);
780
+    }
781
+
782
+    foreach ($having as $k => $v) {
783
+        if ((!$v) or ($v == 1) or ($v == '0=0')) {
784
+            unset($having[$k]);
785
+        }
786
+    }
787
+
788
+    // Installer les jointures.
789
+    // Retirer celles seulement utiles aux criteres finalement absents mais
790
+    // parcourir de la plus recente a la moins recente pour pouvoir eliminer Ln
791
+    // si elle est seulement utile a Ln+1 elle meme inutile
792
+
793
+    $afrom = array();
794
+    $equiv = array();
795
+    $k = count($join);
796
+    foreach (array_reverse($join, true) as $cledef => $j) {
797
+        $cle = $cledef;
798
+        // le format de join est :
799
+        // array(table depart, cle depart [,cle arrivee[,condition optionnelle and ...]])
800
+        $join[$cle] = array_values($join[$cle]); // recalculer les cles car des unset ont pu perturber
801
+        if (count($join[$cle]) == 2) {
802
+            $join[$cle][] = $join[$cle][1];
803
+        }
804
+        if (count($join[$cle]) == 3) {
805
+            $join[$cle][] = '';
806
+        }
807
+        list($t, $c, $carr, $and) = $join[$cle];
808
+        // si le nom de la jointure n'a pas ete specifiee, on prend Lx avec x sont rang dans la liste
809
+        // pour compat avec ancienne convention
810
+        if (is_numeric($cle)) {
811
+            $cle = "L$k";
812
+        }
813
+        $cle_where_lie = "JOIN-$cle";
814
+        if (!$menage
815
+            or isset($afrom[$cle])
816
+            or calculer_jointnul($cle, $select)
817
+            or calculer_jointnul($cle, array_diff_key($join, array($cle => $join[$cle])))
818
+            or calculer_jointnul($cle, $having)
819
+            or calculer_jointnul($cle, array_diff_key($where_simples, [$cle_where_lie => '']))
820
+        ) {
821
+            // corriger les references non explicites dans select
822
+            // ou groupby
823
+            foreach ($select as $i => $s) {
824
+                if ($s == $c) {
825
+                    $select[$i] = "$cle.$c AS $c";
826
+                    break;
827
+                }
828
+            }
829
+            foreach ($groupby as $i => $g) {
830
+                if ($g == $c) {
831
+                    $groupby[$i] = "$cle.$c";
832
+                    break;
833
+                }
834
+            }
835
+            // on garde une ecriture decomposee pour permettre une simplification ulterieure si besoin
836
+            // sans recours a preg_match
837
+            // un implode(' ',..) est fait dans reinjecte_joint un peu plus bas
838
+            $afrom[$t][$cle] = array(
839
+                "\n" .
840
+                (isset($from_type[$cle]) ? $from_type[$cle] : "INNER") . " JOIN",
841
+                $from[$cle],
842
+                "AS $cle",
843
+                "ON (",
844
+                "$cle.$c",
845
+                "=",
846
+                "$t.$carr",
847
+                ($and ? "AND " . $and : "") .
848
+                ")"
849
+            );
850
+            if (isset($afrom[$cle])) {
851
+                $afrom[$t] = $afrom[$t] + $afrom[$cle];
852
+                unset($afrom[$cle]);
853
+            }
854
+            $equiv[] = $carr;
855
+        } else {
856
+            unset($join[$cledef]);
857
+            if (isset($where_simples[$cle_where_lie])) {
858
+                unset($where_simples[$cle_where_lie]);
859
+                unset($where[$cle_where_lie]);
860
+            }
861
+        }
862
+        unset($from[$cle]);
863
+        $k--;
864
+    }
865
+
866
+    if (count($afrom)) {
867
+        // Regarder si la table principale ne sert finalement a rien comme dans
868
+        //<BOUCLE3(MOTS){id_article}{id_mot}> class='on'</BOUCLE3>
869
+        //<BOUCLE2(MOTS){id_article} />#TOTAL_BOUCLE<//B2>
870
+        //<BOUCLE5(RUBRIQUES){id_mot}{tout} />#TOTAL_BOUCLE<//B5>
871
+        // ou dans
872
+        //<BOUCLE8(HIERARCHIE){id_rubrique}{tout}{type='Squelette'}{inverse}{0,1}{lang_select=non} />#TOTAL_BOUCLE<//B8>
873
+        // qui comporte plusieurs jointures
874
+        // ou dans
875
+        // <BOUCLE6(ARTICLES){id_mot=2}{statut==.*} />#TOTAL_BOUCLE<//B6>
876
+        // <BOUCLE7(ARTICLES){id_mot>0}{statut?} />#TOTAL_BOUCLE<//B7>
877
+        // penser a regarder aussi la clause orderby pour ne pas simplifier abusivement
878
+        // <BOUCLE9(ARTICLES){recherche truc}{par titre}>#ID_ARTICLE</BOUCLE9>
879
+        // penser a regarder aussi la clause groubpy pour ne pas simplifier abusivement
880
+        // <BOUCLE10(EVENEMENTS){id_rubrique} />#TOTAL_BOUCLE<//B10>
881
+
882
+        $t = key($from);
883
+        $c = current($from);
884
+        reset($from);
885
+        $e = '/\b(' . "$t\\." . join("|" . $t . '\.', $equiv) . ')\b/';
886
+        if (!(strpos($t, ' ') or // jointure des le depart cf boucle_doc
887
+                calculer_jointnul($t, $select, $e) or
888
+                calculer_jointnul($t, $join, $e) or
889
+                calculer_jointnul($t, $where, $e) or
890
+                calculer_jointnul($t, $orderby, $e) or
891
+                calculer_jointnul($t, $groupby, $e) or
892
+                calculer_jointnul($t, $having, $e))
893
+            && count($afrom[$t])
894
+        ) {
895
+            $nfrom = reset($afrom[$t]);
896
+            $nt = key($afrom[$t]);
897
+            unset($from[$t]);
898
+            $from[$nt] = $nfrom[1];
899
+            unset($afrom[$t][$nt]);
900
+            $afrom[$nt] = $afrom[$t];
901
+            unset($afrom[$t]);
902
+            $e = '/\b' . preg_quote($nfrom[6]) . '\b/';
903
+            $t = $nfrom[4];
904
+            $alias = "";
905
+            // verifier que les deux cles sont homonymes, sinon installer un alias dans le select
906
+            $oldcle = explode('.', $nfrom[6]);
907
+            $oldcle = end($oldcle);
908
+            $newcle = explode('.', $nfrom[4]);
909
+            $newcle = end($newcle);
910
+            if ($newcle != $oldcle) {
911
+                // si l'ancienne cle etait deja dans le select avec un AS
912
+                // reprendre simplement ce AS
913
+                $as = '/\b' . preg_quote($nfrom[6]) . '\s+(AS\s+\w+)\b/';
914
+                if (preg_match($as, implode(',', $select), $m)) {
915
+                    $alias = "";
916
+                } else {
917
+                    $alias = ", " . $nfrom[4] . " AS $oldcle";
918
+                }
919
+            }
920
+            $select = remplacer_jointnul($t . $alias, $select, $e);
921
+            $join = remplacer_jointnul($t, $join, $e);
922
+            $where = remplacer_jointnul($t, $where, $e);
923
+            $having = remplacer_jointnul($t, $having, $e);
924
+            $groupby = remplacer_jointnul($t, $groupby, $e);
925
+            $orderby = remplacer_jointnul($t, $orderby, $e);
926
+        }
927
+        $from = reinjecte_joint($afrom, $from);
928
+    }
929
+    if (empty($GLOBALS['debug']) or !is_array($GLOBALS['debug'])) {
930
+        $wasdebug = empty($GLOBALS['debug']) ? false : $GLOBALS['debug'];
931
+        $GLOBALS['debug'] = array();
932
+        if ($wasdebug) {
933
+            $GLOBALS['debug']['debug'] = true;
934
+        }
935
+    }
936
+    $GLOBALS['debug']['aucasou'] = array($table, $id, $serveur, $requeter);
937
+    $r = sql_select($select, $from, $where,
938
+        $groupby, array_filter($orderby), $limit, $having, $serveur, $requeter);
939
+    unset($GLOBALS['debug']['aucasou']);
940
+
941
+    return $r;
942 942
 }
943 943
 
944 944
 /**
@@ -949,20 +949,20 @@  discard block
 block discarded – undo
949 949
  * @return string
950 950
  */
951 951
 function calculer_where_to_string($v, $join = 'AND') {
952
-	if (empty($v)) {
953
-		return '';
954
-	}
955
-
956
-	if (!is_array($v)) {
957
-		return $v;
958
-	} else {
959
-		$exp = "";
960
-		if (strtoupper($join) === 'AND') {
961
-			return $exp . join(" $join ", array_map('calculer_where_to_string', $v));
962
-		} else {
963
-			return $exp . join($join, $v);
964
-		}
965
-	}
952
+    if (empty($v)) {
953
+        return '';
954
+    }
955
+
956
+    if (!is_array($v)) {
957
+        return $v;
958
+    } else {
959
+        $exp = "";
960
+        if (strtoupper($join) === 'AND') {
961
+            return $exp . join(" $join ", array_map('calculer_where_to_string', $v));
962
+        } else {
963
+            return $exp . join($join, $v);
964
+        }
965
+    }
966 966
 }
967 967
 
968 968
 
@@ -970,62 +970,62 @@  discard block
 block discarded – undo
970 970
 
971 971
 // https://code.spip.net/@calculer_jointnul
972 972
 function calculer_jointnul($cle, $exp, $equiv = '') {
973
-	if (!is_array($exp)) {
974
-		if ($equiv) {
975
-			$exp = preg_replace($equiv, '', $exp);
976
-		}
977
-
978
-		return preg_match("/\\b$cle\\./", $exp);
979
-	} else {
980
-		foreach ($exp as $v) {
981
-			if (calculer_jointnul($cle, $v, $equiv)) {
982
-				return true;
983
-			}
984
-		}
985
-
986
-		return false;
987
-	}
973
+    if (!is_array($exp)) {
974
+        if ($equiv) {
975
+            $exp = preg_replace($equiv, '', $exp);
976
+        }
977
+
978
+        return preg_match("/\\b$cle\\./", $exp);
979
+    } else {
980
+        foreach ($exp as $v) {
981
+            if (calculer_jointnul($cle, $v, $equiv)) {
982
+                return true;
983
+            }
984
+        }
985
+
986
+        return false;
987
+    }
988 988
 }
989 989
 
990 990
 // https://code.spip.net/@reinjecte_joint
991 991
 function reinjecte_joint($afrom, $from) {
992
-	$from_synth = array();
993
-	foreach ($from as $k => $v) {
994
-		$from_synth[$k] = $from[$k];
995
-		if (isset($afrom[$k])) {
996
-			foreach ($afrom[$k] as $kk => $vv) {
997
-				$afrom[$k][$kk] = implode(' ', $afrom[$k][$kk]);
998
-			}
999
-			$from_synth["$k@"] = implode(' ', $afrom[$k]);
1000
-			unset($afrom[$k]);
1001
-		}
1002
-	}
1003
-
1004
-	return $from_synth;
992
+    $from_synth = array();
993
+    foreach ($from as $k => $v) {
994
+        $from_synth[$k] = $from[$k];
995
+        if (isset($afrom[$k])) {
996
+            foreach ($afrom[$k] as $kk => $vv) {
997
+                $afrom[$k][$kk] = implode(' ', $afrom[$k][$kk]);
998
+            }
999
+            $from_synth["$k@"] = implode(' ', $afrom[$k]);
1000
+            unset($afrom[$k]);
1001
+        }
1002
+    }
1003
+
1004
+    return $from_synth;
1005 1005
 }
1006 1006
 
1007 1007
 // https://code.spip.net/@remplacer_jointnul
1008 1008
 function remplacer_jointnul($cle, $exp, $equiv = '') {
1009
-	if (!is_array($exp)) {
1010
-		return preg_replace($equiv, $cle, $exp);
1011
-	} else {
1012
-		foreach ($exp as $k => $v) {
1013
-			$exp[$k] = remplacer_jointnul($cle, $v, $equiv);
1014
-		}
1015
-
1016
-		return $exp;
1017
-	}
1009
+    if (!is_array($exp)) {
1010
+        return preg_replace($equiv, $cle, $exp);
1011
+    } else {
1012
+        foreach ($exp as $k => $v) {
1013
+            $exp[$k] = remplacer_jointnul($cle, $v, $equiv);
1014
+        }
1015
+
1016
+        return $exp;
1017
+    }
1018 1018
 }
1019 1019
 
1020 1020
 // calcul du nom du squelette
1021 1021
 // https://code.spip.net/@calculer_nom_fonction_squel
1022 1022
 function calculer_nom_fonction_squel($skel, $mime_type = 'html', $connect = '') {
1023
-	// ne pas doublonner les squelette selon qu'ils sont calcules depuis ecrire/ ou depuis la racine
1024
-	if ($l = strlen(_DIR_RACINE) and strncmp($skel, _DIR_RACINE, $l) == 0) {
1025
-		$skel = substr($skel, strlen(_DIR_RACINE));
1026
-	}
1027
-
1028
-	return $mime_type
1029
-	. (!$connect ? '' : preg_replace('/\W/', "_", $connect)) . '_'
1030
-	. md5($GLOBALS['spip_version_code'] . ' * ' . $skel . (isset($GLOBALS['marqueur_skel']) ? '*' . $GLOBALS['marqueur_skel'] : ''));
1023
+    // ne pas doublonner les squelette selon qu'ils sont calcules depuis ecrire/ ou depuis la racine
1024
+    if ($l = strlen(_DIR_RACINE) and strncmp($skel, _DIR_RACINE, $l) == 0) {
1025
+        $skel = substr($skel, strlen(_DIR_RACINE));
1026
+    }
1027
+
1028
+    return $mime_type
1029
+    . (!$connect ? '' : preg_replace('/\W/', "_", $connect)) . '_'
1030
+    . md5($GLOBALS['spip_version_code'] . ' * ' . $skel . (isset($GLOBALS['marqueur_skel']) ? '*' . $GLOBALS['marqueur_skel'] : ''));
1031 1031
 }
Please login to merge, or discard this patch.
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 		$GLOBALS['debug_objets']['courant'] = $nom;
55 55
 	}
56 56
 
57
-	$phpfile = sous_repertoire(_DIR_SKELS, '', false, true) . $nom . '.php';
57
+	$phpfile = sous_repertoire(_DIR_SKELS, '', false, true).$nom.'.php';
58 58
 
59 59
 	// si squelette est deja compile et perenne, le charger
60 60
 	if (!squelette_obsolete($phpfile, $source)) {
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 		#}
68 68
 	}
69 69
 
70
-	if (file_exists($lib = $squelette . '_fonctions' . '.php')) {
70
+	if (file_exists($lib = $squelette.'_fonctions'.'.php')) {
71 71
 		include_once $lib;
72 72
 	}
73 73
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			}
106 106
 		} catch (\ParseError $e) {
107 107
 			// Code syntaxiquement faux (critere etc mal programme')
108
-			$msg = _T('zbug_erreur_compilation') . ' | Line ' . $e->getLine() . ' : ' . $e->getMessage();
108
+			$msg = _T('zbug_erreur_compilation').' | Line '.$e->getLine().' : '.$e->getMessage();
109 109
 			erreur_squelette($msg, $boucle);
110 110
 			// continuer pour trouver d'autres fautes eventuelles
111 111
 			// mais prevenir que c'est mort
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	if (defined('_VAR_MODE') and _VAR_MODE == 'debug') {
135 135
 
136 136
 		// Tracer ce qui vient d'etre compile
137
-		$GLOBALS['debug_objets']['code'][$nom . 'tout'] = $code;
137
+		$GLOBALS['debug_objets']['code'][$nom.'tout'] = $code;
138 138
 
139 139
 		// si c'est ce que demande le debusqueur, lui passer la main
140 140
 		if ($GLOBALS['debug_objets']['sourcefile']
@@ -156,13 +156,13 @@  discard block
 block discarded – undo
156 156
 		$code = "
157 157
 /*
158 158
  * Squelette : $sourcefile
159
- * Date :      " . gmdate("D, d M Y H:i:s", @filemtime($sourcefile)) . " GMT
160
- * Compile :   " . gmdate("D, d M Y H:i:s", time()) . " GMT
161
- * " . (!$boucles ? "Pas de boucle" : ("Boucles :   " . $noms)) . "
159
+ * Date :      ".gmdate("D, d M Y H:i:s", @filemtime($sourcefile))." GMT
160
+ * Compile :   " . gmdate("D, d M Y H:i:s", time())." GMT
161
+ * " . (!$boucles ? "Pas de boucle" : ("Boucles :   ".$noms))."
162 162
  */ ";
163 163
 	}
164 164
 
165
-	$code = '<' . "?php\n" . $code . join('', $boucles) . "\n?" . '>';
165
+	$code = '<'."?php\n".$code.join('', $boucles)."\n?".'>';
166 166
 	if (!defined('_VAR_NOCACHE') or !_VAR_NOCACHE) {
167 167
 		ecrire_fichier($phpfile, $code);
168 168
 	}
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 			$j = join('-', array_map('ucwords', explode('-', strtolower($r[2]))));
223 223
 
224 224
 			if ($j == 'X-Spip-Filtre' and isset($headers[$j])) {
225
-				$headers[$j] .= "|" . $r[3];
225
+				$headers[$j] .= "|".$r[3];
226 226
 			} else {
227 227
 				$headers[$j] = $r[3];
228 228
 			}
@@ -230,10 +230,10 @@  discard block
 block discarded – undo
230 230
 	}
231 231
 	// S'agit-il d'un resultat constant ou contenant du code php
232 232
 	$process_ins = (
233
-		strpos($corps, '<' . '?') === false
233
+		strpos($corps, '<'.'?') === false
234 234
 		or
235
-		(strpos($corps, '<' . '?xml') !== false and
236
-			strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
235
+		(strpos($corps, '<'.'?xml') !== false and
236
+			strpos(str_replace('<'.'?xml', '', $corps), '<'.'?') === false)
237 237
 	)
238 238
 		? 'html'
239 239
 		: 'php';
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
 
263 263
 		if ($process_ins == 'html') {
264 264
 			$skel['process_ins'] = (
265
-				strpos($corps, '<' . '?') === false
265
+				strpos($corps, '<'.'?') === false
266 266
 				or
267
-				(strpos($corps, '<' . '?xml') !== false and
268
-					strpos(str_replace('<' . '?xml', '', $corps), '<' . '?') === false)
267
+				(strpos($corps, '<'.'?xml') !== false and
268
+					strpos(str_replace('<'.'?xml', '', $corps), '<'.'?') === false)
269 269
 			)
270 270
 				? 'html'
271 271
 				: 'php';
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 //
284 284
 
285 285
 /** Code PHP pour inclure une balise dynamique à l'exécution d'une page */
286
-define('CODE_INCLURE_BALISE', '<' . '?php 
286
+define('CODE_INCLURE_BALISE', '<'.'?php 
287 287
 include_once("%s");
288 288
 if ($lang_select = "%s") $lang_select = lang_select($lang_select);
289 289
 inserer_balise_dynamique(balise_%s_dyn(%s), array(%s));
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
  **/
311 311
 function synthetiser_balise_dynamique($nom, $args, $file, $context_compil) {
312 312
 	if (strncmp($file, "/", 1) !== 0) {
313
-		$file = './" . _DIR_RACINE . "' . $file;
313
+		$file = './" . _DIR_RACINE . "'.$file;
314 314
 	}
315 315
 
316 316
 	$lang = $context_compil[4];
@@ -352,14 +352,14 @@  discard block
 block discarded – undo
352 352
 	if (is_object($v)) {
353 353
 		return var_export($v, true);
354 354
 	} elseif (!is_array($v)) {
355
-		return "'" . texte_script($v) . "'";
355
+		return "'".texte_script($v)."'";
356 356
 	} else {
357 357
 		$out = array();
358 358
 		foreach ($v as $k => $val) {
359
-			$out [] = argumenter_squelette($k) . '=>' . argumenter_squelette($val);
359
+			$out [] = argumenter_squelette($k).'=>'.argumenter_squelette($val);
360 360
 		}
361 361
 
362
-		return 'array(' . join(", ", $out) . ')';
362
+		return 'array('.join(", ", $out).')';
363 363
 	}
364 364
 }
365 365
 
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 	}
436 436
 
437 437
 	// Y a-t-il une fonction de traitement des arguments ?
438
-	$f = 'balise_' . $nom_balise . '_stat';
438
+	$f = 'balise_'.$nom_balise.'_stat';
439 439
 
440 440
 	$r = !function_exists($f) ? $args : $f($args, $context_compil);
441 441
 
@@ -445,18 +445,18 @@  discard block
 block discarded – undo
445 445
 
446 446
 	// verifier que la fonction dyn est la, 
447 447
 	// sinon se replier sur la generique si elle existe
448
-	if (!function_exists('balise_' . $nom_balise . '_dyn')) {
448
+	if (!function_exists('balise_'.$nom_balise.'_dyn')) {
449 449
 		if (
450 450
 			$balise_generique = chercher_balise_generique($nom)
451 451
 			and $nom_balise_generique = $balise_generique['nom_generique']
452
-			and $file = include_spip("balise/" . strtolower($nom_balise_generique))
453
-			and function_exists('balise_' . $nom_balise_generique . '_dyn')
452
+			and $file = include_spip("balise/".strtolower($nom_balise_generique))
453
+			and function_exists('balise_'.$nom_balise_generique.'_dyn')
454 454
 		) {
455 455
 			// et lui injecter en premier arg le nom de la balise 
456 456
 			array_unshift($r, $nom);
457 457
 			$nom_balise = $nom_balise_generique;
458 458
 			if (!_DIR_RESTREINT) {
459
-				$file = _DIR_RESTREINT_ABS . $file;
459
+				$file = _DIR_RESTREINT_ABS.$file;
460 460
 			}
461 461
 		} else {
462 462
 			$msg = array('zbug_balise_inexistante', array('from' => 'CVT', 'balise' => $nom));
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 		$n = '';
558 558
 		foreach (explode(',', $liste) as $val) {
559 559
 			if ($a = intval($val) and $val === strval($a)) {
560
-				$n .= ',' . $val;
560
+				$n .= ','.$val;
561 561
 			}
562 562
 		}
563 563
 		if (strlen($n)) {
@@ -736,14 +736,14 @@  discard block
 block discarded – undo
736 736
 			// on construit le where une fois, puis on ajoute les where complentaires si besoin, et on reconstruit le where en fonction
737 737
 			$i = 0;
738 738
 			do {
739
-				$where[$k] = remplace_sous_requete($w, "(" . calculer_select(
740
-						array($sous[1] . " AS id"),
739
+				$where[$k] = remplace_sous_requete($w, "(".calculer_select(
740
+						array($sous[1]." AS id"),
741 741
 						$from,
742 742
 						$from_type,
743 743
 						$wheresub,
744 744
 						$jsub,
745 745
 						array(), array(), '',
746
-						$having, $table, $id, $serveur, false) . ")");
746
+						$having, $table, $id, $serveur, false).")");
747 747
 				if (!$i) {
748 748
 					$i = 1;
749 749
 					$wherestring = calculer_where_to_string($where[$k]);
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 		if ($sous[0] == 'SUBSELECT') {
763 763
 			// c'est une sous requete explicite sous la forme identique a sql_select : (SUBSELECT,$select,$from,$where,$groupby,$orderby,$limit,$having)
764 764
 			array_push($where_simples, $sous[3]); // est-ce utile dans ce cas ?
765
-			$where[$k] = remplace_sous_requete($w, "(" . calculer_select(
765
+			$where[$k] = remplace_sous_requete($w, "(".calculer_select(
766 766
 					$sous[1], # select
767 767
 					$sous[2], #from
768 768
 					array(), #from_type
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 					$sous[6], #limit
775 775
 					$sous[7] ? $sous[7] : array(), #having
776 776
 					$table, $id, $serveur, false
777
-				) . ")");
777
+				).")");
778 778
 		}
779 779
 		array_pop($where_simples);
780 780
 	}
@@ -836,15 +836,15 @@  discard block
 block discarded – undo
836 836
 			// sans recours a preg_match
837 837
 			// un implode(' ',..) est fait dans reinjecte_joint un peu plus bas
838 838
 			$afrom[$t][$cle] = array(
839
-				"\n" .
840
-				(isset($from_type[$cle]) ? $from_type[$cle] : "INNER") . " JOIN",
839
+				"\n".
840
+				(isset($from_type[$cle]) ? $from_type[$cle] : "INNER")." JOIN",
841 841
 				$from[$cle],
842 842
 				"AS $cle",
843 843
 				"ON (",
844 844
 				"$cle.$c",
845 845
 				"=",
846 846
 				"$t.$carr",
847
-				($and ? "AND " . $and : "") .
847
+				($and ? "AND ".$and : "").
848 848
 				")"
849 849
 			);
850 850
 			if (isset($afrom[$cle])) {
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
 		$t = key($from);
883 883
 		$c = current($from);
884 884
 		reset($from);
885
-		$e = '/\b(' . "$t\\." . join("|" . $t . '\.', $equiv) . ')\b/';
885
+		$e = '/\b('."$t\\.".join("|".$t.'\.', $equiv).')\b/';
886 886
 		if (!(strpos($t, ' ') or // jointure des le depart cf boucle_doc
887 887
 				calculer_jointnul($t, $select, $e) or
888 888
 				calculer_jointnul($t, $join, $e) or
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 			unset($afrom[$t][$nt]);
900 900
 			$afrom[$nt] = $afrom[$t];
901 901
 			unset($afrom[$t]);
902
-			$e = '/\b' . preg_quote($nfrom[6]) . '\b/';
902
+			$e = '/\b'.preg_quote($nfrom[6]).'\b/';
903 903
 			$t = $nfrom[4];
904 904
 			$alias = "";
905 905
 			// verifier que les deux cles sont homonymes, sinon installer un alias dans le select
@@ -910,14 +910,14 @@  discard block
 block discarded – undo
910 910
 			if ($newcle != $oldcle) {
911 911
 				// si l'ancienne cle etait deja dans le select avec un AS
912 912
 				// reprendre simplement ce AS
913
-				$as = '/\b' . preg_quote($nfrom[6]) . '\s+(AS\s+\w+)\b/';
913
+				$as = '/\b'.preg_quote($nfrom[6]).'\s+(AS\s+\w+)\b/';
914 914
 				if (preg_match($as, implode(',', $select), $m)) {
915 915
 					$alias = "";
916 916
 				} else {
917
-					$alias = ", " . $nfrom[4] . " AS $oldcle";
917
+					$alias = ", ".$nfrom[4]." AS $oldcle";
918 918
 				}
919 919
 			}
920
-			$select = remplacer_jointnul($t . $alias, $select, $e);
920
+			$select = remplacer_jointnul($t.$alias, $select, $e);
921 921
 			$join = remplacer_jointnul($t, $join, $e);
922 922
 			$where = remplacer_jointnul($t, $where, $e);
923 923
 			$having = remplacer_jointnul($t, $having, $e);
@@ -958,9 +958,9 @@  discard block
 block discarded – undo
958 958
 	} else {
959 959
 		$exp = "";
960 960
 		if (strtoupper($join) === 'AND') {
961
-			return $exp . join(" $join ", array_map('calculer_where_to_string', $v));
961
+			return $exp.join(" $join ", array_map('calculer_where_to_string', $v));
962 962
 		} else {
963
-			return $exp . join($join, $v);
963
+			return $exp.join($join, $v);
964 964
 		}
965 965
 	}
966 966
 }
@@ -1026,6 +1026,6 @@  discard block
 block discarded – undo
1026 1026
 	}
1027 1027
 
1028 1028
 	return $mime_type
1029
-	. (!$connect ? '' : preg_replace('/\W/', "_", $connect)) . '_'
1030
-	. md5($GLOBALS['spip_version_code'] . ' * ' . $skel . (isset($GLOBALS['marqueur_skel']) ? '*' . $GLOBALS['marqueur_skel'] : ''));
1029
+	. (!$connect ? '' : preg_replace('/\W/', "_", $connect)).'_'
1030
+	. md5($GLOBALS['spip_version_code'].' * '.$skel.(isset($GLOBALS['marqueur_skel']) ? '*'.$GLOBALS['marqueur_skel'] : ''));
1031 1031
 }
Please login to merge, or discard this patch.
ecrire/inc/distant.php 1 patch
Indentation   +1074 added lines, -1074 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', 2097152);
32
+    define('_INC_DISTANT_MAX_SIZE', 2097152);
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
-		(isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
-	)
44
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
39
+    preg_replace(
40
+        '@^https?:@',
41
+        'https?:',
42
+        (isset($GLOBALS['meta']['adresse_site']) ? $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
 
@@ -68,77 +68,77 @@  discard block
 block discarded – undo
68 68
  */
69 69
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null) {
70 70
 
71
-	// si c'est la protection de soi-meme, retourner le path
72
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
-
75
-		return @file_exists($source) ? $source : false;
76
-	}
77
-
78
-	if (is_null($local)) {
79
-		$local = fichier_copie_locale($source);
80
-	} else {
81
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
-			$local = substr($local, strlen(_DIR_RACINE));
83
-		}
84
-	}
85
-
86
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
-	// par exemple un fichier qui ne figure pas dans nos documents ;
88
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
-	if (!$local) {
90
-		return false;
91
-	}
92
-
93
-	$localrac = _DIR_RACINE . $local;
94
-	$t = ($mode == 'force') ? false : @file_exists($localrac);
95
-
96
-	// test d'existence du fichier
97
-	if ($mode == 'test') {
98
-		return $t ? $local : '';
99
-	}
100
-
101
-	// sinon voir si on doit/peut le telecharger
102
-	if ($local == $source or !tester_url_absolue($source)) {
103
-		return $local;
104
-	}
105
-
106
-	if ($mode == 'modif' or !$t) {
107
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
-		// et des eventuelles recuperations concurantes
109
-		include_spip('inc/acces');
110
-		if (!$taille_max) {
111
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
112
-		}
113
-		$res = recuperer_url(
114
-			$source,
115
-			array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
-		);
117
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
-		}
120
-		if (!$res['length']) {
121
-			// si $t c'est sans doute juste un not-modified-since
122
-			return $t ? $local : false;
123
-		}
124
-		spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
-
126
-		// pour une eventuelle indexation
127
-		pipeline(
128
-			'post_edition',
129
-			array(
130
-				'args' => array(
131
-					'operation' => 'copie_locale',
132
-					'source' => $source,
133
-					'fichier' => $local,
134
-					'http_res' => $res['length'],
135
-				),
136
-				'data' => null
137
-			)
138
-		);
139
-	}
140
-
141
-	return $local;
71
+    // si c'est la protection de soi-meme, retourner le path
72
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
+
75
+        return @file_exists($source) ? $source : false;
76
+    }
77
+
78
+    if (is_null($local)) {
79
+        $local = fichier_copie_locale($source);
80
+    } else {
81
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
+            $local = substr($local, strlen(_DIR_RACINE));
83
+        }
84
+    }
85
+
86
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
+    // par exemple un fichier qui ne figure pas dans nos documents ;
88
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
+    if (!$local) {
90
+        return false;
91
+    }
92
+
93
+    $localrac = _DIR_RACINE . $local;
94
+    $t = ($mode == 'force') ? false : @file_exists($localrac);
95
+
96
+    // test d'existence du fichier
97
+    if ($mode == 'test') {
98
+        return $t ? $local : '';
99
+    }
100
+
101
+    // sinon voir si on doit/peut le telecharger
102
+    if ($local == $source or !tester_url_absolue($source)) {
103
+        return $local;
104
+    }
105
+
106
+    if ($mode == 'modif' or !$t) {
107
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
+        // et des eventuelles recuperations concurantes
109
+        include_spip('inc/acces');
110
+        if (!$taille_max) {
111
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
112
+        }
113
+        $res = recuperer_url(
114
+            $source,
115
+            array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
+        );
117
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
+            spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
+        }
120
+        if (!$res['length']) {
121
+            // si $t c'est sans doute juste un not-modified-since
122
+            return $t ? $local : false;
123
+        }
124
+        spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
+
126
+        // pour une eventuelle indexation
127
+        pipeline(
128
+            'post_edition',
129
+            array(
130
+                'args' => array(
131
+                    'operation' => 'copie_locale',
132
+                    'source' => $source,
133
+                    'fichier' => $local,
134
+                    'http_res' => $res['length'],
135
+                ),
136
+                'data' => null
137
+            )
138
+        );
139
+    }
140
+
141
+    return $local;
142 142
 }
143 143
 
144 144
 /**
@@ -153,88 +153,88 @@  discard block
 block discarded – undo
153 153
  *   url ou false en cas d'echec
154 154
  */
155 155
 function valider_url_distante($url, $known_hosts = array()) {
156
-	if (!function_exists('protocole_verifier')){
157
-		include_spip('inc/filtres_mini');
158
-	}
156
+    if (!function_exists('protocole_verifier')){
157
+        include_spip('inc/filtres_mini');
158
+    }
159 159
 
160
-	if (!protocole_verifier($url, array('http', 'https'))) {
161
-		return false;
162
-	}
160
+    if (!protocole_verifier($url, array('http', 'https'))) {
161
+        return false;
162
+    }
163 163
 	
164
-	$parsed_url = parse_url($url);
165
-	if (!$parsed_url or empty($parsed_url['host']) ) {
166
-		return false;
167
-	}
168
-
169
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
-		return false;
171
-	}
172
-
173
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
-		return false;
175
-	}
176
-
177
-	if (!is_array($known_hosts)) {
178
-		$known_hosts = array($known_hosts);
179
-	}
180
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
-	$known_hosts[] = url_de_base();
182
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
-
184
-	$is_known_host = false;
185
-	foreach ($known_hosts as $known_host) {
186
-		$parse_known = parse_url($known_host);
187
-		if ($parse_known
188
-		  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
-			$is_known_host = true;
190
-			break;
191
-		}
192
-	}
193
-
194
-	if (!$is_known_host) {
195
-		$host = trim($parsed_url['host'], '.');
196
-		if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
-			$ip = $host;
198
-		} else {
199
-			$ip = gethostbyname($host);
200
-			if ($ip === $host) {
201
-				// Error condition for gethostbyname()
202
-				$ip = false;
203
-			}
204
-		}
205
-		if ($ip) {
206
-			$parts = array_map('intval', explode( '.', $ip ));
207
-			if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
-			  or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
-			  or ( 192 === $parts[0] && 168 === $parts[1] )
210
-			) {
211
-				return false;
212
-			}
213
-		}
214
-	}
215
-
216
-	if (empty($parsed_url['port'])) {
217
-		return $url;
218
-	}
219
-
220
-	$port = $parsed_url['port'];
221
-	if ($port === 80  or $port === 443  or $port === 8080) {
222
-		return $url;
223
-	}
224
-
225
-	if ($is_known_host) {
226
-		foreach ($known_hosts as $known_host) {
227
-			$parse_known = parse_url($known_host);
228
-			if ($parse_known
229
-				and !empty($parse_known['port'])
230
-			  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
-			  and $parse_known['port'] == $port) {
232
-				return $url;
233
-			}
234
-		}
235
-	}
236
-
237
-	return false;
164
+    $parsed_url = parse_url($url);
165
+    if (!$parsed_url or empty($parsed_url['host']) ) {
166
+        return false;
167
+    }
168
+
169
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
+        return false;
171
+    }
172
+
173
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
+        return false;
175
+    }
176
+
177
+    if (!is_array($known_hosts)) {
178
+        $known_hosts = array($known_hosts);
179
+    }
180
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
+    $known_hosts[] = url_de_base();
182
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
+
184
+    $is_known_host = false;
185
+    foreach ($known_hosts as $known_host) {
186
+        $parse_known = parse_url($known_host);
187
+        if ($parse_known
188
+          and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
+            $is_known_host = true;
190
+            break;
191
+        }
192
+    }
193
+
194
+    if (!$is_known_host) {
195
+        $host = trim($parsed_url['host'], '.');
196
+        if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
+            $ip = $host;
198
+        } else {
199
+            $ip = gethostbyname($host);
200
+            if ($ip === $host) {
201
+                // Error condition for gethostbyname()
202
+                $ip = false;
203
+            }
204
+        }
205
+        if ($ip) {
206
+            $parts = array_map('intval', explode( '.', $ip ));
207
+            if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
+              or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
+              or ( 192 === $parts[0] && 168 === $parts[1] )
210
+            ) {
211
+                return false;
212
+            }
213
+        }
214
+    }
215
+
216
+    if (empty($parsed_url['port'])) {
217
+        return $url;
218
+    }
219
+
220
+    $port = $parsed_url['port'];
221
+    if ($port === 80  or $port === 443  or $port === 8080) {
222
+        return $url;
223
+    }
224
+
225
+    if ($is_known_host) {
226
+        foreach ($known_hosts as $known_host) {
227
+            $parse_known = parse_url($known_host);
228
+            if ($parse_known
229
+                and !empty($parse_known['port'])
230
+              and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
+              and $parse_known['port'] == $port) {
232
+                return $url;
233
+            }
234
+        }
235
+    }
236
+
237
+    return false;
238 238
 }
239 239
 
240 240
 /**
@@ -254,86 +254,86 @@  discard block
 block discarded – undo
254 254
  */
255 255
 function prepare_donnees_post($donnees, $boundary = '') {
256 256
 
257
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
258
-	// pour un appel soap par exemple
259
-	// l'entete est separe des donnees par un double retour a la ligne
260
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
261
-	if (is_string($donnees) && strlen($donnees)) {
262
-		$entete = '';
263
-		// on repasse tous les \r\n et \r en simples \n
264
-		$donnees = str_replace("\r\n", "\n", $donnees);
265
-		$donnees = str_replace("\r", "\n", $donnees);
266
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
267
-		$p = strpos($donnees, "\n\n");
268
-		if ($p !== false) {
269
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
270
-			$donnees = substr($donnees, $p + 2);
271
-		}
272
-		$chaine = str_replace("\n", "\r\n", $donnees);
273
-	} else {
274
-		/* boundary automatique */
275
-		// Si on a plus de 500 octects de donnees, on "boundarise"
276
-		if ($boundary === '') {
277
-			$taille = 0;
278
-			foreach ($donnees as $cle => $valeur) {
279
-				if (is_array($valeur)) {
280
-					foreach ($valeur as $val2) {
281
-						$taille += strlen($val2);
282
-					}
283
-				} else {
284
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
285
-					$taille += strlen($valeur);
286
-				}
287
-			}
288
-			if ($taille > 500) {
289
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
290
-			}
291
-		}
292
-
293
-		if (is_string($boundary) and strlen($boundary)) {
294
-			// fabrique une chaine HTTP pour un POST avec boundary
295
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
296
-			$chaine = '';
297
-			if (is_array($donnees)) {
298
-				foreach ($donnees as $cle => $valeur) {
299
-					if (is_array($valeur)) {
300
-						foreach ($valeur as $val2) {
301
-							$chaine .= "\r\n--$boundary\r\n";
302
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
303
-							$chaine .= "\r\n";
304
-							$chaine .= $val2;
305
-						}
306
-					} else {
307
-						$chaine .= "\r\n--$boundary\r\n";
308
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
309
-						$chaine .= "\r\n";
310
-						$chaine .= $valeur;
311
-					}
312
-				}
313
-				$chaine .= "\r\n--$boundary\r\n";
314
-			}
315
-		} else {
316
-			// fabrique une chaine HTTP simple pour un POST
317
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
318
-			$chaine = array();
319
-			if (is_array($donnees)) {
320
-				foreach ($donnees as $cle => $valeur) {
321
-					if (is_array($valeur)) {
322
-						foreach ($valeur as $val2) {
323
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
324
-						}
325
-					} else {
326
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
327
-					}
328
-				}
329
-				$chaine = implode('&', $chaine);
330
-			} else {
331
-				$chaine = $donnees;
332
-			}
333
-		}
334
-	}
335
-
336
-	return array($entete, $chaine);
257
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
258
+    // pour un appel soap par exemple
259
+    // l'entete est separe des donnees par un double retour a la ligne
260
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
261
+    if (is_string($donnees) && strlen($donnees)) {
262
+        $entete = '';
263
+        // on repasse tous les \r\n et \r en simples \n
264
+        $donnees = str_replace("\r\n", "\n", $donnees);
265
+        $donnees = str_replace("\r", "\n", $donnees);
266
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
267
+        $p = strpos($donnees, "\n\n");
268
+        if ($p !== false) {
269
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
270
+            $donnees = substr($donnees, $p + 2);
271
+        }
272
+        $chaine = str_replace("\n", "\r\n", $donnees);
273
+    } else {
274
+        /* boundary automatique */
275
+        // Si on a plus de 500 octects de donnees, on "boundarise"
276
+        if ($boundary === '') {
277
+            $taille = 0;
278
+            foreach ($donnees as $cle => $valeur) {
279
+                if (is_array($valeur)) {
280
+                    foreach ($valeur as $val2) {
281
+                        $taille += strlen($val2);
282
+                    }
283
+                } else {
284
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
285
+                    $taille += strlen($valeur);
286
+                }
287
+            }
288
+            if ($taille > 500) {
289
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
290
+            }
291
+        }
292
+
293
+        if (is_string($boundary) and strlen($boundary)) {
294
+            // fabrique une chaine HTTP pour un POST avec boundary
295
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
296
+            $chaine = '';
297
+            if (is_array($donnees)) {
298
+                foreach ($donnees as $cle => $valeur) {
299
+                    if (is_array($valeur)) {
300
+                        foreach ($valeur as $val2) {
301
+                            $chaine .= "\r\n--$boundary\r\n";
302
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
303
+                            $chaine .= "\r\n";
304
+                            $chaine .= $val2;
305
+                        }
306
+                    } else {
307
+                        $chaine .= "\r\n--$boundary\r\n";
308
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
309
+                        $chaine .= "\r\n";
310
+                        $chaine .= $valeur;
311
+                    }
312
+                }
313
+                $chaine .= "\r\n--$boundary\r\n";
314
+            }
315
+        } else {
316
+            // fabrique une chaine HTTP simple pour un POST
317
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
318
+            $chaine = array();
319
+            if (is_array($donnees)) {
320
+                foreach ($donnees as $cle => $valeur) {
321
+                    if (is_array($valeur)) {
322
+                        foreach ($valeur as $val2) {
323
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
324
+                        }
325
+                    } else {
326
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
327
+                    }
328
+                }
329
+                $chaine = implode('&', $chaine);
330
+            } else {
331
+                $chaine = $donnees;
332
+            }
333
+        }
334
+    }
335
+
336
+    return array($entete, $chaine);
337 337
 }
338 338
 
339 339
 /**
@@ -347,20 +347,20 @@  discard block
 block discarded – undo
347 347
  */
348 348
 function url_to_ascii($url_idn) {
349 349
 
350
-	if ($parts = parse_url($url_idn)) {
351
-		$host = $parts['host'];
352
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
353
-			include_spip('inc/idna_convert.class');
354
-			$IDN = new idna_convert();
355
-			$host_ascii = $IDN->encode($host);
356
-			$url_idn = explode($host, $url_idn, 2);
357
-			$url_idn = implode($host_ascii, $url_idn);
358
-		}
359
-		// et on urlencode les char utf si besoin dans le path
360
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
361
-	}
362
-
363
-	return $url_idn;
350
+    if ($parts = parse_url($url_idn)) {
351
+        $host = $parts['host'];
352
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
353
+            include_spip('inc/idna_convert.class');
354
+            $IDN = new idna_convert();
355
+            $host_ascii = $IDN->encode($host);
356
+            $url_idn = explode($host, $url_idn, 2);
357
+            $url_idn = implode($host_ascii, $url_idn);
358
+        }
359
+        // et on urlencode les char utf si besoin dans le path
360
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
361
+    }
362
+
363
+    return $url_idn;
364 364
 }
365 365
 
366 366
 /**
@@ -400,176 +400,176 @@  discard block
 block discarded – undo
400 400
  *     string file : nom du fichier si enregistre dans un fichier
401 401
  */
402 402
 function recuperer_url($url, $options = array()) {
403
-	$default = array(
404
-		'transcoder' => false,
405
-		'methode' => 'GET',
406
-		'taille_max' => null,
407
-		'datas' => '',
408
-		'boundary' => '',
409
-		'refuser_gz' => false,
410
-		'if_modified_since' => '',
411
-		'uri_referer' => '',
412
-		'file' => '',
413
-		'follow_location' => 10,
414
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
415
-	);
416
-	$options = array_merge($default, $options);
417
-	// copier directement dans un fichier ?
418
-	$copy = $options['file'];
419
-
420
-	if ($options['methode'] == 'HEAD') {
421
-		$options['taille_max'] = 0;
422
-	}
423
-	if (is_null($options['taille_max'])) {
424
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
425
-	}
426
-
427
-	if (!empty($options['datas'])) {
428
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
429
-		if (stripos($head, 'Content-Length:') === false) {
430
-			$head .= 'Content-Length: ' . strlen($postdata);
431
-		}
432
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
433
-		if (strlen($postdata)) {
434
-			$options['methode'] = 'POST';
435
-		}
436
-	}
437
-
438
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
439
-	$url = preg_replace(',^feed://,i', 'http://', $url);
440
-	if (!tester_url_absolue($url)) {
441
-		$url = 'http://' . $url;
442
-	} elseif (strncmp($url, '//', 2) == 0) {
443
-		$url = 'http:' . $url;
444
-	}
445
-
446
-	$url = url_to_ascii($url);
447
-
448
-	$result = array(
449
-		'status' => 0,
450
-		'headers' => '',
451
-		'page' => '',
452
-		'length' => 0,
453
-		'last_modified' => '',
454
-		'location' => '',
455
-		'url' => $url
456
-	);
457
-
458
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
459
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
460
-
461
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
462
-	list($handle, $fopen) = init_http(
463
-		$options['methode'],
464
-		$url,
465
-		$refuser_gz,
466
-		$options['uri_referer'],
467
-		$options['datas'],
468
-		$options['version_http'],
469
-		$options['if_modified_since']
470
-	);
471
-	if (!$handle) {
472
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
473
-
474
-		return false;
475
-	}
476
-
477
-	// Sauf en fopen, envoyer le flux d'entree
478
-	// et recuperer les en-tetes de reponses
479
-	if (!$fopen) {
480
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
481
-		if (!$res) {
482
-			fclose($handle);
483
-			$t = @parse_url($url);
484
-			$host = $t['host'];
485
-			// Chinoisierie inexplicable pour contrer
486
-			// les actions liberticides de l'empire du milieu
487
-			if (!need_proxy($host)
488
-				and $res = @file_get_contents($url)
489
-			) {
490
-				$result['length'] = strlen($res);
491
-				if ($copy) {
492
-					ecrire_fichier($copy, $res);
493
-					$result['file'] = $copy;
494
-				} else {
495
-					$result['page'] = $res;
496
-				}
497
-				$res = array(
498
-					'status' => 200,
499
-				);
500
-			} else {
501
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
502
-				return false;
503
-			}
504
-		} elseif ($res['location'] and $options['follow_location']) {
505
-			$options['follow_location']--;
506
-			fclose($handle);
507
-			include_spip('inc/filtres');
508
-			$url = suivre_lien($url, $res['location']);
509
-			spip_log("recuperer_url recommence sur $url", 'distant');
510
-
511
-			return recuperer_url($url, $options);
512
-		} elseif ($res['status'] !== 200) {
513
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
514
-		}
515
-		$result['status'] = $res['status'];
516
-		if (isset($res['headers'])) {
517
-			$result['headers'] = $res['headers'];
518
-		}
519
-		if (isset($res['last_modified'])) {
520
-			$result['last_modified'] = $res['last_modified'];
521
-		}
522
-		if (isset($res['location'])) {
523
-			$result['location'] = $res['location'];
524
-		}
525
-	}
526
-
527
-	// on ne veut que les entetes
528
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
529
-		return $result;
530
-	}
531
-
532
-
533
-	// s'il faut deballer, le faire via un fichier temporaire
534
-	// sinon la memoire explose pour les gros flux
535
-
536
-	$gz = false;
537
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
538
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
539
-	}
540
-
541
-	// si on a pas deja recuperer le contenu par une methode detournee
542
-	if (!$result['length']) {
543
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
544
-		fclose($handle);
545
-		if ($copy) {
546
-			$result['length'] = $res;
547
-			$result['file'] = $copy;
548
-		} elseif ($res) {
549
-			$result['page'] = &$res;
550
-			$result['length'] = strlen($result['page']);
551
-		}
552
-		if (!$result['status']) {
553
-			$result['status'] = 200; // on a reussi, donc !
554
-		}
555
-	}
556
-	if (!$result['page']) {
557
-		return $result;
558
-	}
559
-
560
-	// Decompresser au besoin
561
-	if ($gz) {
562
-		$result['page'] = implode('', gzfile($gz));
563
-		supprimer_fichier($gz);
564
-	}
565
-
566
-	// Faut-il l'importer dans notre charset local ?
567
-	if ($options['transcoder']) {
568
-		include_spip('inc/charsets');
569
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
570
-	}
571
-
572
-	return $result;
403
+    $default = array(
404
+        'transcoder' => false,
405
+        'methode' => 'GET',
406
+        'taille_max' => null,
407
+        'datas' => '',
408
+        'boundary' => '',
409
+        'refuser_gz' => false,
410
+        'if_modified_since' => '',
411
+        'uri_referer' => '',
412
+        'file' => '',
413
+        'follow_location' => 10,
414
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
415
+    );
416
+    $options = array_merge($default, $options);
417
+    // copier directement dans un fichier ?
418
+    $copy = $options['file'];
419
+
420
+    if ($options['methode'] == 'HEAD') {
421
+        $options['taille_max'] = 0;
422
+    }
423
+    if (is_null($options['taille_max'])) {
424
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
425
+    }
426
+
427
+    if (!empty($options['datas'])) {
428
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
429
+        if (stripos($head, 'Content-Length:') === false) {
430
+            $head .= 'Content-Length: ' . strlen($postdata);
431
+        }
432
+        $options['datas'] = $head . "\r\n\r\n" . $postdata;
433
+        if (strlen($postdata)) {
434
+            $options['methode'] = 'POST';
435
+        }
436
+    }
437
+
438
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
439
+    $url = preg_replace(',^feed://,i', 'http://', $url);
440
+    if (!tester_url_absolue($url)) {
441
+        $url = 'http://' . $url;
442
+    } elseif (strncmp($url, '//', 2) == 0) {
443
+        $url = 'http:' . $url;
444
+    }
445
+
446
+    $url = url_to_ascii($url);
447
+
448
+    $result = array(
449
+        'status' => 0,
450
+        'headers' => '',
451
+        'page' => '',
452
+        'length' => 0,
453
+        'last_modified' => '',
454
+        'location' => '',
455
+        'url' => $url
456
+    );
457
+
458
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
459
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
460
+
461
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
462
+    list($handle, $fopen) = init_http(
463
+        $options['methode'],
464
+        $url,
465
+        $refuser_gz,
466
+        $options['uri_referer'],
467
+        $options['datas'],
468
+        $options['version_http'],
469
+        $options['if_modified_since']
470
+    );
471
+    if (!$handle) {
472
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
473
+
474
+        return false;
475
+    }
476
+
477
+    // Sauf en fopen, envoyer le flux d'entree
478
+    // et recuperer les en-tetes de reponses
479
+    if (!$fopen) {
480
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
481
+        if (!$res) {
482
+            fclose($handle);
483
+            $t = @parse_url($url);
484
+            $host = $t['host'];
485
+            // Chinoisierie inexplicable pour contrer
486
+            // les actions liberticides de l'empire du milieu
487
+            if (!need_proxy($host)
488
+                and $res = @file_get_contents($url)
489
+            ) {
490
+                $result['length'] = strlen($res);
491
+                if ($copy) {
492
+                    ecrire_fichier($copy, $res);
493
+                    $result['file'] = $copy;
494
+                } else {
495
+                    $result['page'] = $res;
496
+                }
497
+                $res = array(
498
+                    'status' => 200,
499
+                );
500
+            } else {
501
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
502
+                return false;
503
+            }
504
+        } elseif ($res['location'] and $options['follow_location']) {
505
+            $options['follow_location']--;
506
+            fclose($handle);
507
+            include_spip('inc/filtres');
508
+            $url = suivre_lien($url, $res['location']);
509
+            spip_log("recuperer_url recommence sur $url", 'distant');
510
+
511
+            return recuperer_url($url, $options);
512
+        } elseif ($res['status'] !== 200) {
513
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
514
+        }
515
+        $result['status'] = $res['status'];
516
+        if (isset($res['headers'])) {
517
+            $result['headers'] = $res['headers'];
518
+        }
519
+        if (isset($res['last_modified'])) {
520
+            $result['last_modified'] = $res['last_modified'];
521
+        }
522
+        if (isset($res['location'])) {
523
+            $result['location'] = $res['location'];
524
+        }
525
+    }
526
+
527
+    // on ne veut que les entetes
528
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
529
+        return $result;
530
+    }
531
+
532
+
533
+    // s'il faut deballer, le faire via un fichier temporaire
534
+    // sinon la memoire explose pour les gros flux
535
+
536
+    $gz = false;
537
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
538
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
539
+    }
540
+
541
+    // si on a pas deja recuperer le contenu par une methode detournee
542
+    if (!$result['length']) {
543
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
544
+        fclose($handle);
545
+        if ($copy) {
546
+            $result['length'] = $res;
547
+            $result['file'] = $copy;
548
+        } elseif ($res) {
549
+            $result['page'] = &$res;
550
+            $result['length'] = strlen($result['page']);
551
+        }
552
+        if (!$result['status']) {
553
+            $result['status'] = 200; // on a reussi, donc !
554
+        }
555
+    }
556
+    if (!$result['page']) {
557
+        return $result;
558
+    }
559
+
560
+    // Decompresser au besoin
561
+    if ($gz) {
562
+        $result['page'] = implode('', gzfile($gz));
563
+        supprimer_fichier($gz);
564
+    }
565
+
566
+    // Faut-il l'importer dans notre charset local ?
567
+    if ($options['transcoder']) {
568
+        include_spip('inc/charsets');
569
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
570
+    }
571
+
572
+    return $result;
573 573
 }
574 574
 
575 575
 /**
@@ -585,72 +585,72 @@  discard block
 block discarded – undo
585 585
  * @return array|bool|mixed
586 586
  */
587 587
 function recuperer_url_cache($url, $options = array()) {
588
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
589
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
590
-	}
591
-	$default = array(
592
-		'transcoder' => false,
593
-		'methode' => 'GET',
594
-		'taille_max' => null,
595
-		'datas' => '',
596
-		'boundary' => '',
597
-		'refuser_gz' => false,
598
-		'if_modified_since' => '',
599
-		'uri_referer' => '',
600
-		'file' => '',
601
-		'follow_location' => 10,
602
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
603
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
604
-	);
605
-	$options = array_merge($default, $options);
606
-
607
-	// cas ou il n'est pas possible de cacher
608
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
609
-		return recuperer_url($url, $options);
610
-	}
611
-
612
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
613
-	static $errors = array();
614
-	if (isset($errors[$url])) {
615
-		return $errors[$url];
616
-	}
617
-
618
-	$sig = $options;
619
-	unset($sig['if_modified_since']);
620
-	unset($sig['delai_cache']);
621
-	$sig['url'] = $url;
622
-
623
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
624
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
625
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
626
-	$cache = "$sub$cache";
627
-
628
-	$res = false;
629
-	$is_cached = file_exists($cache);
630
-	if ($is_cached
631
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
632
-	) {
633
-		lire_fichier($cache, $res);
634
-		if ($res = unserialize($res)) {
635
-			// mettre le last_modified et le status=304 ?
636
-		}
637
-	}
638
-	if (!$res) {
639
-		$res = recuperer_url($url, $options);
640
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
641
-		if (!$res) {
642
-			if ($is_cached) {
643
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
644
-				lire_fichier($cache, $res);
645
-				$res = unserialize($res);
646
-			}
647
-
648
-			return $errors[$url] = $res;
649
-		}
650
-		ecrire_fichier($cache, serialize($res));
651
-	}
652
-
653
-	return $res;
588
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
589
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
590
+    }
591
+    $default = array(
592
+        'transcoder' => false,
593
+        'methode' => 'GET',
594
+        'taille_max' => null,
595
+        'datas' => '',
596
+        'boundary' => '',
597
+        'refuser_gz' => false,
598
+        'if_modified_since' => '',
599
+        'uri_referer' => '',
600
+        'file' => '',
601
+        'follow_location' => 10,
602
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
603
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
604
+    );
605
+    $options = array_merge($default, $options);
606
+
607
+    // cas ou il n'est pas possible de cacher
608
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
609
+        return recuperer_url($url, $options);
610
+    }
611
+
612
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
613
+    static $errors = array();
614
+    if (isset($errors[$url])) {
615
+        return $errors[$url];
616
+    }
617
+
618
+    $sig = $options;
619
+    unset($sig['if_modified_since']);
620
+    unset($sig['delai_cache']);
621
+    $sig['url'] = $url;
622
+
623
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
624
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
625
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
626
+    $cache = "$sub$cache";
627
+
628
+    $res = false;
629
+    $is_cached = file_exists($cache);
630
+    if ($is_cached
631
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
632
+    ) {
633
+        lire_fichier($cache, $res);
634
+        if ($res = unserialize($res)) {
635
+            // mettre le last_modified et le status=304 ?
636
+        }
637
+    }
638
+    if (!$res) {
639
+        $res = recuperer_url($url, $options);
640
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
641
+        if (!$res) {
642
+            if ($is_cached) {
643
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
644
+                lire_fichier($cache, $res);
645
+                $res = unserialize($res);
646
+            }
647
+
648
+            return $errors[$url] = $res;
649
+        }
650
+        ecrire_fichier($cache, serialize($res));
651
+    }
652
+
653
+    return $res;
654 654
 }
655 655
 
656 656
 /**
@@ -688,52 +688,52 @@  discard block
 block discarded – undo
688 688
  *     - false si la page n'a pu être récupérée (status different de 200)
689 689
  **/
690 690
 function recuperer_page(
691
-	$url,
692
-	$trans = false,
693
-	$get_headers = false,
694
-	$taille_max = null,
695
-	$datas = '',
696
-	$boundary = '',
697
-	$refuser_gz = false,
698
-	$date_verif = '',
699
-	$uri_referer = ''
691
+    $url,
692
+    $trans = false,
693
+    $get_headers = false,
694
+    $taille_max = null,
695
+    $datas = '',
696
+    $boundary = '',
697
+    $refuser_gz = false,
698
+    $date_verif = '',
699
+    $uri_referer = ''
700 700
 ) {
701
-	// $copy = copier le fichier ?
702
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
703
-
704
-	if (!is_null($taille_max) and ($taille_max == 0)) {
705
-		$get = 'HEAD';
706
-	} else {
707
-		$get = 'GET';
708
-	}
709
-
710
-	$options = array(
711
-		'transcoder' => $trans === true,
712
-		'methode' => $get,
713
-		'datas' => $datas,
714
-		'boundary' => $boundary,
715
-		'refuser_gz' => $refuser_gz,
716
-		'if_modified_since' => $date_verif,
717
-		'uri_referer' => $uri_referer,
718
-		'file' => $copy ? $trans : '',
719
-		'follow_location' => 10,
720
-	);
721
-	if (!is_null($taille_max)) {
722
-		$options['taille_max'] = $taille_max;
723
-	}
724
-	// dix tentatives maximum en cas d'entetes 301...
725
-	$res = recuperer_url($url, $options);
726
-	if (!$res) {
727
-		return false;
728
-	}
729
-	if ($res['status'] !== 200) {
730
-		return false;
731
-	}
732
-	if ($get_headers) {
733
-		return $res['headers'] . "\n" . $res['page'];
734
-	}
735
-
736
-	return $res['page'];
701
+    // $copy = copier le fichier ?
702
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
703
+
704
+    if (!is_null($taille_max) and ($taille_max == 0)) {
705
+        $get = 'HEAD';
706
+    } else {
707
+        $get = 'GET';
708
+    }
709
+
710
+    $options = array(
711
+        'transcoder' => $trans === true,
712
+        'methode' => $get,
713
+        'datas' => $datas,
714
+        'boundary' => $boundary,
715
+        'refuser_gz' => $refuser_gz,
716
+        'if_modified_since' => $date_verif,
717
+        'uri_referer' => $uri_referer,
718
+        'file' => $copy ? $trans : '',
719
+        'follow_location' => 10,
720
+    );
721
+    if (!is_null($taille_max)) {
722
+        $options['taille_max'] = $taille_max;
723
+    }
724
+    // dix tentatives maximum en cas d'entetes 301...
725
+    $res = recuperer_url($url, $options);
726
+    if (!$res) {
727
+        return false;
728
+    }
729
+    if ($res['status'] !== 200) {
730
+        return false;
731
+    }
732
+    if ($get_headers) {
733
+        return $res['headers'] . "\n" . $res['page'];
734
+    }
735
+
736
+    return $res['page'];
737 737
 }
738 738
 
739 739
 
@@ -770,48 +770,48 @@  discard block
 block discarded – undo
770 770
  *     - false sinon
771 771
  **/
772 772
 function recuperer_lapage(
773
-	$url,
774
-	$trans = false,
775
-	$get = 'GET',
776
-	$taille_max = 1048576,
777
-	$datas = '',
778
-	$refuser_gz = false,
779
-	$date_verif = '',
780
-	$uri_referer = ''
773
+    $url,
774
+    $trans = false,
775
+    $get = 'GET',
776
+    $taille_max = 1048576,
777
+    $datas = '',
778
+    $refuser_gz = false,
779
+    $date_verif = '',
780
+    $uri_referer = ''
781 781
 ) {
782
-	// $copy = copier le fichier ?
783
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
784
-
785
-	// si on ecrit directement dans un fichier, pour ne pas manipuler
786
-	// en memoire refuser gz
787
-	if ($copy) {
788
-		$refuser_gz = true;
789
-	}
790
-
791
-	$options = array(
792
-		'transcoder' => $trans === true,
793
-		'methode' => $get,
794
-		'datas' => $datas,
795
-		'refuser_gz' => $refuser_gz,
796
-		'if_modified_since' => $date_verif,
797
-		'uri_referer' => $uri_referer,
798
-		'file' => $copy ? $trans : '',
799
-		'follow_location' => false,
800
-	);
801
-	if (!is_null($taille_max)) {
802
-		$options['taille_max'] = $taille_max;
803
-	}
804
-	// dix tentatives maximum en cas d'entetes 301...
805
-	$res = recuperer_url($url, $options);
806
-
807
-	if (!$res) {
808
-		return false;
809
-	}
810
-	if ($res['status'] !== 200) {
811
-		return false;
812
-	}
813
-
814
-	return array($res['headers'], $res['page']);
782
+    // $copy = copier le fichier ?
783
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
784
+
785
+    // si on ecrit directement dans un fichier, pour ne pas manipuler
786
+    // en memoire refuser gz
787
+    if ($copy) {
788
+        $refuser_gz = true;
789
+    }
790
+
791
+    $options = array(
792
+        'transcoder' => $trans === true,
793
+        'methode' => $get,
794
+        'datas' => $datas,
795
+        'refuser_gz' => $refuser_gz,
796
+        'if_modified_since' => $date_verif,
797
+        'uri_referer' => $uri_referer,
798
+        'file' => $copy ? $trans : '',
799
+        'follow_location' => false,
800
+    );
801
+    if (!is_null($taille_max)) {
802
+        $options['taille_max'] = $taille_max;
803
+    }
804
+    // dix tentatives maximum en cas d'entetes 301...
805
+    $res = recuperer_url($url, $options);
806
+
807
+    if (!$res) {
808
+        return false;
809
+    }
810
+    if ($res['status'] !== 200) {
811
+        return false;
812
+    }
813
+
814
+    return array($res['headers'], $res['page']);
815 815
 }
816 816
 
817 817
 /**
@@ -829,41 +829,41 @@  discard block
 block discarded – undo
829 829
  *   string contenu de la resource
830 830
  */
831 831
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
832
-	$taille = 0;
833
-	$result = '';
834
-	$fp = false;
835
-	if ($fichier) {
836
-		include_spip('inc/acces');
837
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
838
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
839
-		if (!$fp and file_exists($fichier)) {
840
-			return filesize($fichier);
841
-		}
842
-		if (!$fp) {
843
-			return false;
844
-		}
845
-		$result = 0; // on renvoie la taille du fichier
846
-	}
847
-	while (!feof($handle) and $taille < $taille_max) {
848
-		$res = fread($handle, 16384);
849
-		$taille += strlen($res);
850
-		if ($fp) {
851
-			fwrite($fp, $res);
852
-			$result = $taille;
853
-		} else {
854
-			$result .= $res;
855
-		}
856
-	}
857
-	if ($fp) {
858
-		spip_fclose_unlock($fp);
859
-		spip_unlink($fichier);
860
-		@rename($tmpfile, $fichier);
861
-		if (!file_exists($fichier)) {
862
-			return false;
863
-		}
864
-	}
865
-
866
-	return $result;
832
+    $taille = 0;
833
+    $result = '';
834
+    $fp = false;
835
+    if ($fichier) {
836
+        include_spip('inc/acces');
837
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
838
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
839
+        if (!$fp and file_exists($fichier)) {
840
+            return filesize($fichier);
841
+        }
842
+        if (!$fp) {
843
+            return false;
844
+        }
845
+        $result = 0; // on renvoie la taille du fichier
846
+    }
847
+    while (!feof($handle) and $taille < $taille_max) {
848
+        $res = fread($handle, 16384);
849
+        $taille += strlen($res);
850
+        if ($fp) {
851
+            fwrite($fp, $res);
852
+            $result = $taille;
853
+        } else {
854
+            $result .= $res;
855
+        }
856
+    }
857
+    if ($fp) {
858
+        spip_fclose_unlock($fp);
859
+        spip_unlink($fichier);
860
+        @rename($tmpfile, $fichier);
861
+        if (!file_exists($fichier)) {
862
+            return false;
863
+        }
864
+    }
865
+
866
+    return $result;
867 867
 }
868 868
 
869 869
 /**
@@ -885,34 +885,34 @@  discard block
 block discarded – undo
885 885
  *   string location
886 886
  */
887 887
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
888
-	$result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
889
-
890
-	$s = @trim(fgets($handle, 16384));
891
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
892
-		return false;
893
-	}
894
-	$result['status'] = intval($r[1]);
895
-	while ($s = trim(fgets($handle, 16384))) {
896
-		$result['headers'][] = $s . "\n";
897
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
898
-		list(, $d, $v) = $r;
899
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
900
-			$result['location'] = $v;
901
-		} elseif ($d == 'Last-Modified') {
902
-			$result['last_modified'] = strtotime($v);
903
-		}
904
-	}
905
-	if ($if_modified_since
906
-		and $result['last_modified']
907
-		and $if_modified_since > $result['last_modified']
908
-		and $result['status'] == 200
909
-	) {
910
-		$result['status'] = 304;
911
-	}
912
-
913
-	$result['headers'] = implode('', $result['headers']);
914
-
915
-	return $result;
888
+    $result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
889
+
890
+    $s = @trim(fgets($handle, 16384));
891
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
892
+        return false;
893
+    }
894
+    $result['status'] = intval($r[1]);
895
+    while ($s = trim(fgets($handle, 16384))) {
896
+        $result['headers'][] = $s . "\n";
897
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
898
+        list(, $d, $v) = $r;
899
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
900
+            $result['location'] = $v;
901
+        } elseif ($d == 'Last-Modified') {
902
+            $result['last_modified'] = strtotime($v);
903
+        }
904
+    }
905
+    if ($if_modified_since
906
+        and $result['last_modified']
907
+        and $if_modified_since > $result['last_modified']
908
+        and $result['status'] == 200
909
+    ) {
910
+        $result['status'] = 304;
911
+    }
912
+
913
+    $result['headers'] = implode('', $result['headers']);
914
+
915
+    return $result;
916 916
 }
917 917
 
918 918
 /**
@@ -934,20 +934,20 @@  discard block
 block discarded – undo
934 934
  *     - le tableau des entetes dans tous les autres cas
935 935
  **/
936 936
 function recuperer_entetes($f, $date_verif = '') {
937
-	//Cas ou la page distante n'a pas bouge depuis
938
-	//la derniere visite
939
-	$res = recuperer_entetes_complets($f, $date_verif);
940
-	if (!$res) {
941
-		return false;
942
-	}
943
-	if ($res['location']) {
944
-		return $res['location'];
945
-	}
946
-	if ($res['status'] != 200) {
947
-		return $res['status'];
948
-	}
949
-
950
-	return explode("\n", $res['headers']);
937
+    //Cas ou la page distante n'a pas bouge depuis
938
+    //la derniere visite
939
+    $res = recuperer_entetes_complets($f, $date_verif);
940
+    if (!$res) {
941
+        return false;
942
+    }
943
+    if ($res['location']) {
944
+        return $res['location'];
945
+    }
946
+    if ($res['status'] != 200) {
947
+        return $res['status'];
948
+    }
949
+
950
+    return explode("\n", $res['headers']);
951 951
 }
952 952
 
953 953
 /**
@@ -969,22 +969,22 @@  discard block
 block discarded – undo
969 969
  *     Nom du fichier pour copie locale
970 970
  **/
971 971
 function nom_fichier_copie_locale($source, $extension) {
972
-	include_spip('inc/documents');
972
+    include_spip('inc/documents');
973 973
 
974
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
975
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
974
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
975
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
976 976
 
977
-	// on se place tout le temps comme si on etait a la racine
978
-	if (_DIR_RACINE) {
979
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
980
-	}
977
+    // on se place tout le temps comme si on etait a la racine
978
+    if (_DIR_RACINE) {
979
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
980
+    }
981 981
 
982
-	$m = md5($source);
982
+    $m = md5($source);
983 983
 
984
-	return $d
985
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
986
-	. substr($m, 0, 4)
987
-	. ".$extension";
984
+    return $d
985
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
986
+    . substr($m, 0, 4)
987
+    . ".$extension";
988 988
 }
989 989
 
990 990
 /**
@@ -1002,68 +1002,68 @@  discard block
 block discarded – undo
1002 1002
  *      Nom du fichier calculé
1003 1003
  **/
1004 1004
 function fichier_copie_locale($source) {
1005
-	// Si c'est deja local pas de souci
1006
-	if (!tester_url_absolue($source)) {
1007
-		if (_DIR_RACINE) {
1008
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1009
-		}
1010
-
1011
-		return $source;
1012
-	}
1013
-
1014
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1015
-	// a deja ete copie en local avec cette extension
1016
-	// dans ce cas elle est fiable, pas la peine de requeter en base
1017
-	$path_parts = pathinfo($source);
1018
-	if (!isset($path_parts['extension'])) {
1019
-		$path_parts['extension'] = '';
1020
-	}
1021
-	$ext = $path_parts ? $path_parts['extension'] : '';
1022
-	if ($ext
1023
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1024
-		and $f = nom_fichier_copie_locale($source, $ext)
1025
-		and file_exists(_DIR_RACINE . $f)
1026
-	) {
1027
-		return $f;
1028
-	}
1029
-
1030
-
1031
-	// Si c'est deja dans la table des documents,
1032
-	// ramener le nom de sa copie potentielle
1033
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1034
-
1035
-	if ($ext) {
1036
-		return nom_fichier_copie_locale($source, $ext);
1037
-	}
1038
-
1039
-	// voir si l'extension indiquee dans le nom du fichier est ok
1040
-	// et si il n'aurait pas deja ete rapatrie
1041
-
1042
-	$ext = $path_parts ? $path_parts['extension'] : '';
1043
-
1044
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1045
-		$f = nom_fichier_copie_locale($source, $ext);
1046
-		if (file_exists(_DIR_RACINE . $f)) {
1047
-			return $f;
1048
-		}
1049
-	}
1050
-
1051
-	// Ping  pour voir si son extension est connue et autorisee
1052
-	// avec mise en cache du resultat du ping
1053
-
1054
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1055
-	if (!@file_exists($cache)
1056
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1057
-		or _request('var_mode') == 'recalcul'
1058
-	) {
1059
-		$path_parts = recuperer_infos_distantes($source, 0, false);
1060
-		ecrire_fichier($cache, serialize($path_parts));
1061
-	}
1062
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1063
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1064
-		return nom_fichier_copie_locale($source, $ext);
1065
-	}
1066
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1005
+    // Si c'est deja local pas de souci
1006
+    if (!tester_url_absolue($source)) {
1007
+        if (_DIR_RACINE) {
1008
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1009
+        }
1010
+
1011
+        return $source;
1012
+    }
1013
+
1014
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1015
+    // a deja ete copie en local avec cette extension
1016
+    // dans ce cas elle est fiable, pas la peine de requeter en base
1017
+    $path_parts = pathinfo($source);
1018
+    if (!isset($path_parts['extension'])) {
1019
+        $path_parts['extension'] = '';
1020
+    }
1021
+    $ext = $path_parts ? $path_parts['extension'] : '';
1022
+    if ($ext
1023
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1024
+        and $f = nom_fichier_copie_locale($source, $ext)
1025
+        and file_exists(_DIR_RACINE . $f)
1026
+    ) {
1027
+        return $f;
1028
+    }
1029
+
1030
+
1031
+    // Si c'est deja dans la table des documents,
1032
+    // ramener le nom de sa copie potentielle
1033
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1034
+
1035
+    if ($ext) {
1036
+        return nom_fichier_copie_locale($source, $ext);
1037
+    }
1038
+
1039
+    // voir si l'extension indiquee dans le nom du fichier est ok
1040
+    // et si il n'aurait pas deja ete rapatrie
1041
+
1042
+    $ext = $path_parts ? $path_parts['extension'] : '';
1043
+
1044
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1045
+        $f = nom_fichier_copie_locale($source, $ext);
1046
+        if (file_exists(_DIR_RACINE . $f)) {
1047
+            return $f;
1048
+        }
1049
+    }
1050
+
1051
+    // Ping  pour voir si son extension est connue et autorisee
1052
+    // avec mise en cache du resultat du ping
1053
+
1054
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1055
+    if (!@file_exists($cache)
1056
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
1057
+        or _request('var_mode') == 'recalcul'
1058
+    ) {
1059
+        $path_parts = recuperer_infos_distantes($source, 0, false);
1060
+        ecrire_fichier($cache, serialize($path_parts));
1061
+    }
1062
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1063
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1064
+        return nom_fichier_copie_locale($source, $ext);
1065
+    }
1066
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1067 1067
 }
1068 1068
 
1069 1069
 
@@ -1091,144 +1091,144 @@  discard block
 block discarded – undo
1091 1091
  **/
1092 1092
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
1093 1093
 
1094
-	// pas la peine de perdre son temps
1095
-	if (!tester_url_absolue($source)) {
1096
-		return false;
1097
-	}
1098
-
1099
-	# charger les alias des types mime
1100
-	include_spip('base/typedoc');
1101
-
1102
-	$a = array();
1103
-	$mime_type = '';
1104
-	// On va directement charger le debut des images et des fichiers html,
1105
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1106
-	// ca echoue l'utilisateur devra les entrer...
1107
-	if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1108
-		list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1109
-
1110
-		if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1111
-			$mime_type = (trim($regs[1]));
1112
-		} else {
1113
-			$mime_type = '';
1114
-		} // inconnu
1115
-
1116
-		// Appliquer les alias
1117
-		while (isset($GLOBALS['mime_alias'][$mime_type])) {
1118
-			$mime_type = $GLOBALS['mime_alias'][$mime_type];
1119
-		}
1120
-
1121
-		// Si on a un mime-type insignifiant
1122
-		// text/plain,application/octet-stream ou vide
1123
-		// c'est peut-etre que le serveur ne sait pas
1124
-		// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1125
-		// ou le Content-Disposition: attachment; filename=...
1126
-		$t = null;
1127
-		if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1128
-			if (!$t
1129
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1130
-			) {
1131
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1132
-			}
1133
-			if (!$t
1134
-				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1135
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1136
-			) {
1137
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1138
-			}
1139
-		}
1140
-
1141
-		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1142
-		if (!$t) {
1143
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1144
-		}
1145
-
1146
-		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1147
-		// On essaie de nouveau avec l'extension
1148
-		if (!$t
1149
-			and $mime_type != 'text/plain'
1150
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1151
-		) {
1152
-			# eviter xxx.3 => 3gp (> SPIP 3)
1153
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1154
-		}
1155
-
1156
-		if ($t) {
1157
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1158
-			$a['extension'] = $t['extension'];
1159
-		} else {
1160
-			# par defaut on retombe sur '.bin' si c'est autorise
1161
-			spip_log("mime-type $mime_type inconnu", 'distant');
1162
-			$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1163
-			if (!$t) {
1164
-				return false;
1165
-			}
1166
-			$a['extension'] = $t['extension'];
1167
-		}
1168
-
1169
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1170
-			$a['taille'] = intval($regs[1]);
1171
-		}
1172
-	}
1173
-
1174
-	// Echec avec HEAD, on tente avec GET
1175
-	if (!$a and !$max) {
1176
-		spip_log("tenter GET $source", 'distant');
1177
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1178
-	}
1179
-
1180
-	// si on a rien trouve pas la peine d'insister
1181
-	if (!$a) {
1182
-		return false;
1183
-	}
1184
-
1185
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1186
-	// recharger le document en GET et recuperer des donnees supplementaires...
1187
-	include_spip('inc/filtres_images_lib_mini');
1188
-	if (strpos($mime_type, "image/") === 0
1189
-	  and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1190
-		if ($max == 0
1191
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1192
-			and in_array($extension, formats_image_acceptables())
1193
-			and $charger_si_petite_image
1194
-		) {
1195
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1196
-		} else {
1197
-			if ($a['body']) {
1198
-				$a['extension'] = $extension;
1199
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1200
-				ecrire_fichier($a['fichier'], $a['body']);
1201
-				$size_image = @spip_getimagesize($a['fichier']);
1202
-				$a['largeur'] = intval($size_image[0]);
1203
-				$a['hauteur'] = intval($size_image[1]);
1204
-				$a['type_image'] = true;
1205
-			}
1206
-		}
1207
-	}
1208
-
1209
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1210
-	// ce sera mieux que 0x0
1211
-	// Flash is dead!
1212
-	if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1213
-		and empty($a['largeur'])
1214
-	) {
1215
-		$a['largeur'] = 425;
1216
-		$a['hauteur'] = 350;
1217
-	}
1218
-
1219
-	if ($mime_type == 'text/html') {
1220
-		include_spip('inc/filtres');
1221
-		$page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1222
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1223
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1224
-		}
1225
-		if (!isset($a['taille']) or !$a['taille']) {
1226
-			$a['taille'] = strlen($page); # a peu pres
1227
-		}
1228
-	}
1229
-	$a['mime_type'] = $mime_type;
1230
-
1231
-	return $a;
1094
+    // pas la peine de perdre son temps
1095
+    if (!tester_url_absolue($source)) {
1096
+        return false;
1097
+    }
1098
+
1099
+    # charger les alias des types mime
1100
+    include_spip('base/typedoc');
1101
+
1102
+    $a = array();
1103
+    $mime_type = '';
1104
+    // On va directement charger le debut des images et des fichiers html,
1105
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1106
+    // ca echoue l'utilisateur devra les entrer...
1107
+    if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1108
+        list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1109
+
1110
+        if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1111
+            $mime_type = (trim($regs[1]));
1112
+        } else {
1113
+            $mime_type = '';
1114
+        } // inconnu
1115
+
1116
+        // Appliquer les alias
1117
+        while (isset($GLOBALS['mime_alias'][$mime_type])) {
1118
+            $mime_type = $GLOBALS['mime_alias'][$mime_type];
1119
+        }
1120
+
1121
+        // Si on a un mime-type insignifiant
1122
+        // text/plain,application/octet-stream ou vide
1123
+        // c'est peut-etre que le serveur ne sait pas
1124
+        // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1125
+        // ou le Content-Disposition: attachment; filename=...
1126
+        $t = null;
1127
+        if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1128
+            if (!$t
1129
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1130
+            ) {
1131
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1132
+            }
1133
+            if (!$t
1134
+                and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1135
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1136
+            ) {
1137
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1138
+            }
1139
+        }
1140
+
1141
+        // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1142
+        if (!$t) {
1143
+            $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1144
+        }
1145
+
1146
+        // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1147
+        // On essaie de nouveau avec l'extension
1148
+        if (!$t
1149
+            and $mime_type != 'text/plain'
1150
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1151
+        ) {
1152
+            # eviter xxx.3 => 3gp (> SPIP 3)
1153
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1154
+        }
1155
+
1156
+        if ($t) {
1157
+            spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1158
+            $a['extension'] = $t['extension'];
1159
+        } else {
1160
+            # par defaut on retombe sur '.bin' si c'est autorise
1161
+            spip_log("mime-type $mime_type inconnu", 'distant');
1162
+            $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1163
+            if (!$t) {
1164
+                return false;
1165
+            }
1166
+            $a['extension'] = $t['extension'];
1167
+        }
1168
+
1169
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1170
+            $a['taille'] = intval($regs[1]);
1171
+        }
1172
+    }
1173
+
1174
+    // Echec avec HEAD, on tente avec GET
1175
+    if (!$a and !$max) {
1176
+        spip_log("tenter GET $source", 'distant');
1177
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1178
+    }
1179
+
1180
+    // si on a rien trouve pas la peine d'insister
1181
+    if (!$a) {
1182
+        return false;
1183
+    }
1184
+
1185
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1186
+    // recharger le document en GET et recuperer des donnees supplementaires...
1187
+    include_spip('inc/filtres_images_lib_mini');
1188
+    if (strpos($mime_type, "image/") === 0
1189
+      and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1190
+        if ($max == 0
1191
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1192
+            and in_array($extension, formats_image_acceptables())
1193
+            and $charger_si_petite_image
1194
+        ) {
1195
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1196
+        } else {
1197
+            if ($a['body']) {
1198
+                $a['extension'] = $extension;
1199
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1200
+                ecrire_fichier($a['fichier'], $a['body']);
1201
+                $size_image = @spip_getimagesize($a['fichier']);
1202
+                $a['largeur'] = intval($size_image[0]);
1203
+                $a['hauteur'] = intval($size_image[1]);
1204
+                $a['type_image'] = true;
1205
+            }
1206
+        }
1207
+    }
1208
+
1209
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1210
+    // ce sera mieux que 0x0
1211
+    // Flash is dead!
1212
+    if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1213
+        and empty($a['largeur'])
1214
+    ) {
1215
+        $a['largeur'] = 425;
1216
+        $a['hauteur'] = 350;
1217
+    }
1218
+
1219
+    if ($mime_type == 'text/html') {
1220
+        include_spip('inc/filtres');
1221
+        $page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1222
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1223
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1224
+        }
1225
+        if (!isset($a['taille']) or !$a['taille']) {
1226
+            $a['taille'] = strlen($page); # a peu pres
1227
+        }
1228
+    }
1229
+    $a['mime_type'] = $mime_type;
1230
+
1231
+    return $a;
1232 1232
 }
1233 1233
 
1234 1234
 
@@ -1244,45 +1244,45 @@  discard block
 block discarded – undo
1244 1244
  * @return string
1245 1245
  */
1246 1246
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1247
-	if (is_null($http_proxy)) {
1248
-		$http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1249
-	}
1250
-	// rien a faire si pas de proxy :)
1251
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1252
-		return '';
1253
-	}
1254
-
1255
-	if (is_null($http_noproxy)) {
1256
-		$http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1257
-	}
1258
-	// si pas d'exception, on retourne le proxy
1259
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1260
-		return $http_proxy;
1261
-	}
1262
-
1263
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1264
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1265
-	$http_noproxy = str_replace("\n", " ", $http_noproxy);
1266
-	$http_noproxy = str_replace("\r", " ", $http_noproxy);
1267
-	$http_noproxy = " $http_noproxy ";
1268
-	$domain = $host;
1269
-	// si le domaine exact www.example.org est dans les exceptions
1270
-	if (strpos($http_noproxy, " $domain ") !== false)
1271
-		return '';
1272
-
1273
-	while (strpos($domain, '.') !== false) {
1274
-		$domain = explode('.', $domain);
1275
-		array_shift($domain);
1276
-		$domain = implode('.', $domain);
1277
-
1278
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1279
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1280
-			return '';
1281
-		}
1282
-	}
1283
-
1284
-	// ok c'est pas une exception
1285
-	return $http_proxy;
1247
+    if (is_null($http_proxy)) {
1248
+        $http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1249
+    }
1250
+    // rien a faire si pas de proxy :)
1251
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1252
+        return '';
1253
+    }
1254
+
1255
+    if (is_null($http_noproxy)) {
1256
+        $http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1257
+    }
1258
+    // si pas d'exception, on retourne le proxy
1259
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1260
+        return $http_proxy;
1261
+    }
1262
+
1263
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1264
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1265
+    $http_noproxy = str_replace("\n", " ", $http_noproxy);
1266
+    $http_noproxy = str_replace("\r", " ", $http_noproxy);
1267
+    $http_noproxy = " $http_noproxy ";
1268
+    $domain = $host;
1269
+    // si le domaine exact www.example.org est dans les exceptions
1270
+    if (strpos($http_noproxy, " $domain ") !== false)
1271
+        return '';
1272
+
1273
+    while (strpos($domain, '.') !== false) {
1274
+        $domain = explode('.', $domain);
1275
+        array_shift($domain);
1276
+        $domain = implode('.', $domain);
1277
+
1278
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1279
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1280
+            return '';
1281
+        }
1282
+    }
1283
+
1284
+    // ok c'est pas une exception
1285
+    return $http_proxy;
1286 1286
 }
1287 1287
 
1288 1288
 
@@ -1305,58 +1305,58 @@  discard block
 block discarded – undo
1305 1305
  * @return array
1306 1306
  */
1307 1307
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1308
-	$user = $via_proxy = $proxy_user = '';
1309
-	$fopen = false;
1310
-
1311
-	$t = @parse_url($url);
1312
-	$host = $t['host'];
1313
-	if ($t['scheme'] == 'http') {
1314
-		$scheme = 'http';
1315
-		$noproxy = '';
1316
-	} elseif ($t['scheme'] == 'https') {
1317
-		$scheme = 'ssl';
1318
-		$noproxy = 'ssl://';
1319
-		if (!isset($t['port']) || !($port = $t['port'])) {
1320
-			$t['port'] = 443;
1321
-		}
1322
-	} else {
1323
-		$scheme = $t['scheme'];
1324
-		$noproxy = $scheme . '://';
1325
-	}
1326
-	if (isset($t['user'])) {
1327
-		$user = array($t['user'], $t['pass']);
1328
-	}
1329
-
1330
-	if (!isset($t['port']) || !($port = $t['port'])) {
1331
-		$port = 80;
1332
-	}
1333
-	if (!isset($t['path']) || !($path = $t['path'])) {
1334
-		$path = '/';
1335
-	}
1336
-
1337
-	if (!empty($t['query'])) {
1338
-		$path .= '?' . $t['query'];
1339
-	}
1340
-
1341
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1342
-	if (!$f or !is_resource($f)) {
1343
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1344
-		// ce qui correspond a $f===110
1345
-		if ($f !== 110
1346
-			and !need_proxy($host)
1347
-			and !_request('tester_proxy')
1348
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1349
-		) {
1350
-			$f = @fopen($url, 'rb');
1351
-			spip_log("connexion vers $url par simple fopen", 'distant');
1352
-			$fopen = true;
1353
-		} else {
1354
-			// echec total
1355
-			$f = false;
1356
-		}
1357
-	}
1358
-
1359
-	return array($f, $fopen);
1308
+    $user = $via_proxy = $proxy_user = '';
1309
+    $fopen = false;
1310
+
1311
+    $t = @parse_url($url);
1312
+    $host = $t['host'];
1313
+    if ($t['scheme'] == 'http') {
1314
+        $scheme = 'http';
1315
+        $noproxy = '';
1316
+    } elseif ($t['scheme'] == 'https') {
1317
+        $scheme = 'ssl';
1318
+        $noproxy = 'ssl://';
1319
+        if (!isset($t['port']) || !($port = $t['port'])) {
1320
+            $t['port'] = 443;
1321
+        }
1322
+    } else {
1323
+        $scheme = $t['scheme'];
1324
+        $noproxy = $scheme . '://';
1325
+    }
1326
+    if (isset($t['user'])) {
1327
+        $user = array($t['user'], $t['pass']);
1328
+    }
1329
+
1330
+    if (!isset($t['port']) || !($port = $t['port'])) {
1331
+        $port = 80;
1332
+    }
1333
+    if (!isset($t['path']) || !($path = $t['path'])) {
1334
+        $path = '/';
1335
+    }
1336
+
1337
+    if (!empty($t['query'])) {
1338
+        $path .= '?' . $t['query'];
1339
+    }
1340
+
1341
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1342
+    if (!$f or !is_resource($f)) {
1343
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1344
+        // ce qui correspond a $f===110
1345
+        if ($f !== 110
1346
+            and !need_proxy($host)
1347
+            and !_request('tester_proxy')
1348
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1349
+        ) {
1350
+            $f = @fopen($url, 'rb');
1351
+            spip_log("connexion vers $url par simple fopen", 'distant');
1352
+            $fopen = true;
1353
+        } else {
1354
+            // echec total
1355
+            $f = false;
1356
+        }
1357
+    }
1358
+
1359
+    return array($f, $fopen);
1360 1360
 }
1361 1361
 
1362 1362
 /**
@@ -1391,124 +1391,124 @@  discard block
 block discarded – undo
1391 1391
  *   resource socket vers l'url demandee
1392 1392
  */
1393 1393
 function lance_requete(
1394
-	$method,
1395
-	$scheme,
1396
-	$user,
1397
-	$host,
1398
-	$path,
1399
-	$port,
1400
-	$noproxy,
1401
-	$refuse_gz = false,
1402
-	$referer = '',
1403
-	$datas = '',
1404
-	$vers = 'HTTP/1.0',
1405
-	$date = ''
1394
+    $method,
1395
+    $scheme,
1396
+    $user,
1397
+    $host,
1398
+    $path,
1399
+    $port,
1400
+    $noproxy,
1401
+    $refuse_gz = false,
1402
+    $referer = '',
1403
+    $datas = '',
1404
+    $vers = 'HTTP/1.0',
1405
+    $date = ''
1406 1406
 ) {
1407 1407
 
1408
-	$proxy_user = '';
1409
-	$http_proxy = need_proxy($host);
1410
-	if ($user) {
1411
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1412
-	}
1413
-
1414
-	$connect = '';
1415
-	if ($http_proxy) {
1416
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1417
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1418
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1419
-				. "Host: $path_host\r\n"
1420
-				. "Proxy-Connection: Keep-Alive\r\n";
1421
-		} else {
1422
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1423
-				. (!$user ? '' : "$user@")
1424
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1425
-		}
1426
-		$t2 = @parse_url($http_proxy);
1427
-		$first_host = $t2['host'];
1428
-		if (!($port = $t2['port'])) {
1429
-			$port = 80;
1430
-		}
1431
-		if ($t2['user']) {
1432
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1433
-		}
1434
-	} else {
1435
-		$first_host = $noproxy . $host;
1436
-	}
1437
-
1438
-	if ($connect) {
1439
-		$streamContext = stream_context_create(array(
1440
-			'ssl' => array(
1441
-				'verify_peer' => false,
1442
-				'allow_self_signed' => true,
1443
-				'SNI_enabled' => true,
1444
-				'peer_name' => $host,
1445
-			)
1446
-		));
1447
-		$f = @stream_socket_client(
1448
-			"tcp://$first_host:$port",
1449
-			$errno,
1450
-			$errstr,
1451
-			_INC_DISTANT_CONNECT_TIMEOUT,
1452
-			STREAM_CLIENT_CONNECT,
1453
-			$streamContext
1454
-		);
1455
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1456
-		if (!$f) {
1457
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1458
-			return $errno;
1459
-		}
1460
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1461
-
1462
-		fputs($f, $connect);
1463
-		fputs($f, "\r\n");
1464
-		$res = fread($f, 1024);
1465
-		if (!$res
1466
-			or !count($res = explode(' ', $res))
1467
-			or $res[1] !== '200'
1468
-		) {
1469
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1470
-			fclose($f);
1471
-
1472
-			return false;
1473
-		}
1474
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1475
-		stream_set_blocking($f, true);
1476
-		// envoyer le handshake
1477
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1478
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1479
-	} else {
1480
-		$ntry = 3;
1481
-		do {
1482
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1483
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1484
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1485
-		if (!$f) {
1486
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1487
-
1488
-			return $errno;
1489
-		}
1490
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1491
-	}
1492
-
1493
-	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1494
-
1495
-	$host_port = $host;
1496
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1497
-		$host_port .= ":$port";
1498
-	}
1499
-	$req = "$method $path $vers\r\n"
1500
-		. "Host: $host_port\r\n"
1501
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1502
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1503
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1504
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1505
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1506
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1507
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1408
+    $proxy_user = '';
1409
+    $http_proxy = need_proxy($host);
1410
+    if ($user) {
1411
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1412
+    }
1413
+
1414
+    $connect = '';
1415
+    if ($http_proxy) {
1416
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1417
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1418
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1419
+                . "Host: $path_host\r\n"
1420
+                . "Proxy-Connection: Keep-Alive\r\n";
1421
+        } else {
1422
+            $path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1423
+                . (!$user ? '' : "$user@")
1424
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1425
+        }
1426
+        $t2 = @parse_url($http_proxy);
1427
+        $first_host = $t2['host'];
1428
+        if (!($port = $t2['port'])) {
1429
+            $port = 80;
1430
+        }
1431
+        if ($t2['user']) {
1432
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1433
+        }
1434
+    } else {
1435
+        $first_host = $noproxy . $host;
1436
+    }
1437
+
1438
+    if ($connect) {
1439
+        $streamContext = stream_context_create(array(
1440
+            'ssl' => array(
1441
+                'verify_peer' => false,
1442
+                'allow_self_signed' => true,
1443
+                'SNI_enabled' => true,
1444
+                'peer_name' => $host,
1445
+            )
1446
+        ));
1447
+        $f = @stream_socket_client(
1448
+            "tcp://$first_host:$port",
1449
+            $errno,
1450
+            $errstr,
1451
+            _INC_DISTANT_CONNECT_TIMEOUT,
1452
+            STREAM_CLIENT_CONNECT,
1453
+            $streamContext
1454
+        );
1455
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1456
+        if (!$f) {
1457
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1458
+            return $errno;
1459
+        }
1460
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1461
+
1462
+        fputs($f, $connect);
1463
+        fputs($f, "\r\n");
1464
+        $res = fread($f, 1024);
1465
+        if (!$res
1466
+            or !count($res = explode(' ', $res))
1467
+            or $res[1] !== '200'
1468
+        ) {
1469
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1470
+            fclose($f);
1471
+
1472
+            return false;
1473
+        }
1474
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1475
+        stream_set_blocking($f, true);
1476
+        // envoyer le handshake
1477
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1478
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1479
+    } else {
1480
+        $ntry = 3;
1481
+        do {
1482
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1483
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1484
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1485
+        if (!$f) {
1486
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1487
+
1488
+            return $errno;
1489
+        }
1490
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1491
+    }
1492
+
1493
+    $site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1494
+
1495
+    $host_port = $host;
1496
+    if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1497
+        $host_port .= ":$port";
1498
+    }
1499
+    $req = "$method $path $vers\r\n"
1500
+        . "Host: $host_port\r\n"
1501
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1502
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1503
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1504
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1505
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1506
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1507
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1508 1508
 
1509 1509
 #	spip_log("Requete\n$req", 'distant');
1510
-	fputs($f, $req);
1511
-	fputs($f, $datas ? $datas : "\r\n");
1510
+    fputs($f, $req);
1511
+    fputs($f, $datas ? $datas : "\r\n");
1512 1512
 
1513
-	return $f;
1513
+    return $f;
1514 1514
 }
Please login to merge, or discard this patch.