Completed
Push — master ( 14acf4...b6bfef )
by cam
05:18
created
ecrire/inc/distant.php 1 patch
Indentation   +1077 added lines, -1077 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
 /**
@@ -253,86 +253,86 @@  discard block
 block discarded – undo
253 253
  */
254 254
 function prepare_donnees_post($donnees, $boundary = '') {
255 255
 
256
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
257
-	// pour un appel soap par exemple
258
-	// l'entete est separe des donnees par un double retour a la ligne
259
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
260
-	if (is_string($donnees) && strlen($donnees)) {
261
-		$entete = '';
262
-		// on repasse tous les \r\n et \r en simples \n
263
-		$donnees = str_replace("\r\n", "\n", $donnees);
264
-		$donnees = str_replace("\r", "\n", $donnees);
265
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
266
-		$p = strpos($donnees, "\n\n");
267
-		if ($p !== false) {
268
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
269
-			$donnees = substr($donnees, $p + 2);
270
-		}
271
-		$chaine = str_replace("\n", "\r\n", $donnees);
272
-	} else {
273
-		/* boundary automatique */
274
-		// Si on a plus de 500 octects de donnees, on "boundarise"
275
-		if ($boundary === '') {
276
-			$taille = 0;
277
-			foreach ($donnees as $cle => $valeur) {
278
-				if (is_array($valeur)) {
279
-					foreach ($valeur as $val2) {
280
-						$taille += strlen($val2);
281
-					}
282
-				} else {
283
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
284
-					$taille += strlen($valeur);
285
-				}
286
-			}
287
-			if ($taille > 500) {
288
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
289
-			}
290
-		}
291
-
292
-		if (is_string($boundary) and strlen($boundary)) {
293
-			// fabrique une chaine HTTP pour un POST avec boundary
294
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
295
-			$chaine = '';
296
-			if (is_array($donnees)) {
297
-				foreach ($donnees as $cle => $valeur) {
298
-					if (is_array($valeur)) {
299
-						foreach ($valeur as $val2) {
300
-							$chaine .= "\r\n--$boundary\r\n";
301
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
302
-							$chaine .= "\r\n";
303
-							$chaine .= $val2;
304
-						}
305
-					} else {
306
-						$chaine .= "\r\n--$boundary\r\n";
307
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
308
-						$chaine .= "\r\n";
309
-						$chaine .= $valeur;
310
-					}
311
-				}
312
-				$chaine .= "\r\n--$boundary\r\n";
313
-			}
314
-		} else {
315
-			// fabrique une chaine HTTP simple pour un POST
316
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
317
-			$chaine = array();
318
-			if (is_array($donnees)) {
319
-				foreach ($donnees as $cle => $valeur) {
320
-					if (is_array($valeur)) {
321
-						foreach ($valeur as $val2) {
322
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
323
-						}
324
-					} else {
325
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
326
-					}
327
-				}
328
-				$chaine = implode('&', $chaine);
329
-			} else {
330
-				$chaine = $donnees;
331
-			}
332
-		}
333
-	}
334
-
335
-	return array($entete, $chaine);
256
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
257
+    // pour un appel soap par exemple
258
+    // l'entete est separe des donnees par un double retour a la ligne
259
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
260
+    if (is_string($donnees) && strlen($donnees)) {
261
+        $entete = '';
262
+        // on repasse tous les \r\n et \r en simples \n
263
+        $donnees = str_replace("\r\n", "\n", $donnees);
264
+        $donnees = str_replace("\r", "\n", $donnees);
265
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
266
+        $p = strpos($donnees, "\n\n");
267
+        if ($p !== false) {
268
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
269
+            $donnees = substr($donnees, $p + 2);
270
+        }
271
+        $chaine = str_replace("\n", "\r\n", $donnees);
272
+    } else {
273
+        /* boundary automatique */
274
+        // Si on a plus de 500 octects de donnees, on "boundarise"
275
+        if ($boundary === '') {
276
+            $taille = 0;
277
+            foreach ($donnees as $cle => $valeur) {
278
+                if (is_array($valeur)) {
279
+                    foreach ($valeur as $val2) {
280
+                        $taille += strlen($val2);
281
+                    }
282
+                } else {
283
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
284
+                    $taille += strlen($valeur);
285
+                }
286
+            }
287
+            if ($taille > 500) {
288
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
289
+            }
290
+        }
291
+
292
+        if (is_string($boundary) and strlen($boundary)) {
293
+            // fabrique une chaine HTTP pour un POST avec boundary
294
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
295
+            $chaine = '';
296
+            if (is_array($donnees)) {
297
+                foreach ($donnees as $cle => $valeur) {
298
+                    if (is_array($valeur)) {
299
+                        foreach ($valeur as $val2) {
300
+                            $chaine .= "\r\n--$boundary\r\n";
301
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
302
+                            $chaine .= "\r\n";
303
+                            $chaine .= $val2;
304
+                        }
305
+                    } else {
306
+                        $chaine .= "\r\n--$boundary\r\n";
307
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
308
+                        $chaine .= "\r\n";
309
+                        $chaine .= $valeur;
310
+                    }
311
+                }
312
+                $chaine .= "\r\n--$boundary\r\n";
313
+            }
314
+        } else {
315
+            // fabrique une chaine HTTP simple pour un POST
316
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
317
+            $chaine = array();
318
+            if (is_array($donnees)) {
319
+                foreach ($donnees as $cle => $valeur) {
320
+                    if (is_array($valeur)) {
321
+                        foreach ($valeur as $val2) {
322
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
323
+                        }
324
+                    } else {
325
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
326
+                    }
327
+                }
328
+                $chaine = implode('&', $chaine);
329
+            } else {
330
+                $chaine = $donnees;
331
+            }
332
+        }
333
+    }
334
+
335
+    return array($entete, $chaine);
336 336
 }
337 337
 
338 338
 /**
@@ -346,20 +346,20 @@  discard block
 block discarded – undo
346 346
  */
347 347
 function url_to_ascii($url_idn) {
348 348
 
349
-	if ($parts = parse_url($url_idn)) {
350
-		$host = $parts['host'];
351
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
352
-			include_spip('inc/idna_convert.class');
353
-			$IDN = new idna_convert();
354
-			$host_ascii = $IDN->encode($host);
355
-			$url_idn = explode($host, $url_idn, 2);
356
-			$url_idn = implode($host_ascii, $url_idn);
357
-		}
358
-		// et on urlencode les char utf si besoin dans le path
359
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
360
-	}
361
-
362
-	return $url_idn;
349
+    if ($parts = parse_url($url_idn)) {
350
+        $host = $parts['host'];
351
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
352
+            include_spip('inc/idna_convert.class');
353
+            $IDN = new idna_convert();
354
+            $host_ascii = $IDN->encode($host);
355
+            $url_idn = explode($host, $url_idn, 2);
356
+            $url_idn = implode($host_ascii, $url_idn);
357
+        }
358
+        // et on urlencode les char utf si besoin dans le path
359
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
360
+    }
361
+
362
+    return $url_idn;
363 363
 }
364 364
 
365 365
 /**
@@ -398,176 +398,176 @@  discard block
 block discarded – undo
398 398
  *     string file : nom du fichier si enregistre dans un fichier
399 399
  */
400 400
 function recuperer_url($url, $options = array()) {
401
-	$default = array(
402
-		'transcoder' => false,
403
-		'methode' => 'GET',
404
-		'taille_max' => null,
405
-		'datas' => '',
406
-		'boundary' => '',
407
-		'refuser_gz' => false,
408
-		'if_modified_since' => '',
409
-		'uri_referer' => '',
410
-		'file' => '',
411
-		'follow_location' => 10,
412
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
413
-	);
414
-	$options = array_merge($default, $options);
415
-	// copier directement dans un fichier ?
416
-	$copy = $options['file'];
417
-
418
-	if ($options['methode'] == 'HEAD') {
419
-		$options['taille_max'] = 0;
420
-	}
421
-	if (is_null($options['taille_max'])) {
422
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
423
-	}
424
-
425
-	if (!empty($options['datas'])) {
426
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
427
-		if (stripos($head, 'Content-Length:') === false) {
428
-			$head .= 'Content-Length: ' . strlen($postdata);
429
-		}
430
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
431
-		if (strlen($postdata)) {
432
-			$options['methode'] = 'POST';
433
-		}
434
-	}
435
-
436
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
437
-	$url = preg_replace(',^feed://,i', 'http://', $url);
438
-	if (!tester_url_absolue($url)) {
439
-		$url = 'http://' . $url;
440
-	} elseif (strncmp($url, '//', 2) == 0) {
441
-		$url = 'http:' . $url;
442
-	}
443
-
444
-	$url = url_to_ascii($url);
445
-
446
-	$result = array(
447
-		'status' => 0,
448
-		'headers' => '',
449
-		'page' => '',
450
-		'length' => 0,
451
-		'last_modified' => '',
452
-		'location' => '',
453
-		'url' => $url
454
-	);
455
-
456
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
457
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
458
-
459
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
460
-	list($handle, $fopen) = init_http(
461
-		$options['methode'],
462
-		$url,
463
-		$refuser_gz,
464
-		$options['uri_referer'],
465
-		$options['datas'],
466
-		$options['version_http'],
467
-		$options['if_modified_since']
468
-	);
469
-	if (!$handle) {
470
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
471
-
472
-		return false;
473
-	}
474
-
475
-	// Sauf en fopen, envoyer le flux d'entree
476
-	// et recuperer les en-tetes de reponses
477
-	if (!$fopen) {
478
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
479
-		if (!$res) {
480
-			fclose($handle);
481
-			$t = @parse_url($url);
482
-			$host = $t['host'];
483
-			// Chinoisierie inexplicable pour contrer
484
-			// les actions liberticides de l'empire du milieu
485
-			if (!need_proxy($host)
486
-				and $res = @file_get_contents($url)
487
-			) {
488
-				$result['length'] = strlen($res);
489
-				if ($copy) {
490
-					ecrire_fichier($copy, $res);
491
-					$result['file'] = $copy;
492
-				} else {
493
-					$result['page'] = $res;
494
-				}
495
-				$res = array(
496
-					'status' => 200,
497
-				);
498
-			} else {
499
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
500
-				return false;
501
-			}
502
-		} elseif ($res['location'] and $options['follow_location']) {
503
-			$options['follow_location']--;
504
-			fclose($handle);
505
-			include_spip('inc/filtres');
506
-			$url = suivre_lien($url, $res['location']);
507
-			spip_log("recuperer_url recommence sur $url", 'distant');
508
-
509
-			return recuperer_url($url, $options);
510
-		} elseif ($res['status'] !== 200) {
511
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
512
-		}
513
-		$result['status'] = $res['status'];
514
-		if (isset($res['headers'])) {
515
-			$result['headers'] = $res['headers'];
516
-		}
517
-		if (isset($res['last_modified'])) {
518
-			$result['last_modified'] = $res['last_modified'];
519
-		}
520
-		if (isset($res['location'])) {
521
-			$result['location'] = $res['location'];
522
-		}
523
-	}
524
-
525
-	// on ne veut que les entetes
526
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
527
-		return $result;
528
-	}
529
-
530
-
531
-	// s'il faut deballer, le faire via un fichier temporaire
532
-	// sinon la memoire explose pour les gros flux
533
-
534
-	$gz = false;
535
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
536
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
537
-	}
538
-
539
-	// si on a pas deja recuperer le contenu par une methode detournee
540
-	if (!$result['length']) {
541
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
542
-		fclose($handle);
543
-		if ($copy) {
544
-			$result['length'] = $res;
545
-			$result['file'] = $copy;
546
-		} elseif ($res) {
547
-			$result['page'] = &$res;
548
-			$result['length'] = strlen($result['page']);
549
-		}
550
-		if (!$result['status']) {
551
-			$result['status'] = 200; // on a reussi, donc !
552
-		}
553
-	}
554
-	if (!$result['page']) {
555
-		return $result;
556
-	}
557
-
558
-	// Decompresser au besoin
559
-	if ($gz) {
560
-		$result['page'] = implode('', gzfile($gz));
561
-		supprimer_fichier($gz);
562
-	}
563
-
564
-	// Faut-il l'importer dans notre charset local ?
565
-	if ($options['transcoder']) {
566
-		include_spip('inc/charsets');
567
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
568
-	}
569
-
570
-	return $result;
401
+    $default = array(
402
+        'transcoder' => false,
403
+        'methode' => 'GET',
404
+        'taille_max' => null,
405
+        'datas' => '',
406
+        'boundary' => '',
407
+        'refuser_gz' => false,
408
+        'if_modified_since' => '',
409
+        'uri_referer' => '',
410
+        'file' => '',
411
+        'follow_location' => 10,
412
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
413
+    );
414
+    $options = array_merge($default, $options);
415
+    // copier directement dans un fichier ?
416
+    $copy = $options['file'];
417
+
418
+    if ($options['methode'] == 'HEAD') {
419
+        $options['taille_max'] = 0;
420
+    }
421
+    if (is_null($options['taille_max'])) {
422
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
423
+    }
424
+
425
+    if (!empty($options['datas'])) {
426
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
427
+        if (stripos($head, 'Content-Length:') === false) {
428
+            $head .= 'Content-Length: ' . strlen($postdata);
429
+        }
430
+        $options['datas'] = $head . "\r\n\r\n" . $postdata;
431
+        if (strlen($postdata)) {
432
+            $options['methode'] = 'POST';
433
+        }
434
+    }
435
+
436
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
437
+    $url = preg_replace(',^feed://,i', 'http://', $url);
438
+    if (!tester_url_absolue($url)) {
439
+        $url = 'http://' . $url;
440
+    } elseif (strncmp($url, '//', 2) == 0) {
441
+        $url = 'http:' . $url;
442
+    }
443
+
444
+    $url = url_to_ascii($url);
445
+
446
+    $result = array(
447
+        'status' => 0,
448
+        'headers' => '',
449
+        'page' => '',
450
+        'length' => 0,
451
+        'last_modified' => '',
452
+        'location' => '',
453
+        'url' => $url
454
+    );
455
+
456
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
457
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
458
+
459
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
460
+    list($handle, $fopen) = init_http(
461
+        $options['methode'],
462
+        $url,
463
+        $refuser_gz,
464
+        $options['uri_referer'],
465
+        $options['datas'],
466
+        $options['version_http'],
467
+        $options['if_modified_since']
468
+    );
469
+    if (!$handle) {
470
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
471
+
472
+        return false;
473
+    }
474
+
475
+    // Sauf en fopen, envoyer le flux d'entree
476
+    // et recuperer les en-tetes de reponses
477
+    if (!$fopen) {
478
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
479
+        if (!$res) {
480
+            fclose($handle);
481
+            $t = @parse_url($url);
482
+            $host = $t['host'];
483
+            // Chinoisierie inexplicable pour contrer
484
+            // les actions liberticides de l'empire du milieu
485
+            if (!need_proxy($host)
486
+                and $res = @file_get_contents($url)
487
+            ) {
488
+                $result['length'] = strlen($res);
489
+                if ($copy) {
490
+                    ecrire_fichier($copy, $res);
491
+                    $result['file'] = $copy;
492
+                } else {
493
+                    $result['page'] = $res;
494
+                }
495
+                $res = array(
496
+                    'status' => 200,
497
+                );
498
+            } else {
499
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
500
+                return false;
501
+            }
502
+        } elseif ($res['location'] and $options['follow_location']) {
503
+            $options['follow_location']--;
504
+            fclose($handle);
505
+            include_spip('inc/filtres');
506
+            $url = suivre_lien($url, $res['location']);
507
+            spip_log("recuperer_url recommence sur $url", 'distant');
508
+
509
+            return recuperer_url($url, $options);
510
+        } elseif ($res['status'] !== 200) {
511
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
512
+        }
513
+        $result['status'] = $res['status'];
514
+        if (isset($res['headers'])) {
515
+            $result['headers'] = $res['headers'];
516
+        }
517
+        if (isset($res['last_modified'])) {
518
+            $result['last_modified'] = $res['last_modified'];
519
+        }
520
+        if (isset($res['location'])) {
521
+            $result['location'] = $res['location'];
522
+        }
523
+    }
524
+
525
+    // on ne veut que les entetes
526
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
527
+        return $result;
528
+    }
529
+
530
+
531
+    // s'il faut deballer, le faire via un fichier temporaire
532
+    // sinon la memoire explose pour les gros flux
533
+
534
+    $gz = false;
535
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
536
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
537
+    }
538
+
539
+    // si on a pas deja recuperer le contenu par une methode detournee
540
+    if (!$result['length']) {
541
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
542
+        fclose($handle);
543
+        if ($copy) {
544
+            $result['length'] = $res;
545
+            $result['file'] = $copy;
546
+        } elseif ($res) {
547
+            $result['page'] = &$res;
548
+            $result['length'] = strlen($result['page']);
549
+        }
550
+        if (!$result['status']) {
551
+            $result['status'] = 200; // on a reussi, donc !
552
+        }
553
+    }
554
+    if (!$result['page']) {
555
+        return $result;
556
+    }
557
+
558
+    // Decompresser au besoin
559
+    if ($gz) {
560
+        $result['page'] = implode('', gzfile($gz));
561
+        supprimer_fichier($gz);
562
+    }
563
+
564
+    // Faut-il l'importer dans notre charset local ?
565
+    if ($options['transcoder']) {
566
+        include_spip('inc/charsets');
567
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
568
+    }
569
+
570
+    return $result;
571 571
 }
572 572
 
573 573
 /**
@@ -583,72 +583,72 @@  discard block
 block discarded – undo
583 583
  * @return array|bool|mixed
584 584
  */
585 585
 function recuperer_url_cache($url, $options = array()) {
586
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
587
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
588
-	}
589
-	$default = array(
590
-		'transcoder' => false,
591
-		'methode' => 'GET',
592
-		'taille_max' => null,
593
-		'datas' => '',
594
-		'boundary' => '',
595
-		'refuser_gz' => false,
596
-		'if_modified_since' => '',
597
-		'uri_referer' => '',
598
-		'file' => '',
599
-		'follow_location' => 10,
600
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
601
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
602
-	);
603
-	$options = array_merge($default, $options);
604
-
605
-	// cas ou il n'est pas possible de cacher
606
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
607
-		return recuperer_url($url, $options);
608
-	}
609
-
610
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
611
-	static $errors = array();
612
-	if (isset($errors[$url])) {
613
-		return $errors[$url];
614
-	}
615
-
616
-	$sig = $options;
617
-	unset($sig['if_modified_since']);
618
-	unset($sig['delai_cache']);
619
-	$sig['url'] = $url;
620
-
621
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
622
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
623
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
624
-	$cache = "$sub$cache";
625
-
626
-	$res = false;
627
-	$is_cached = file_exists($cache);
628
-	if ($is_cached
629
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
630
-	) {
631
-		lire_fichier($cache, $res);
632
-		if ($res = unserialize($res)) {
633
-			// mettre le last_modified et le status=304 ?
634
-		}
635
-	}
636
-	if (!$res) {
637
-		$res = recuperer_url($url, $options);
638
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
639
-		if (!$res) {
640
-			if ($is_cached) {
641
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
642
-				lire_fichier($cache, $res);
643
-				$res = unserialize($res);
644
-			}
645
-
646
-			return $errors[$url] = $res;
647
-		}
648
-		ecrire_fichier($cache, serialize($res));
649
-	}
650
-
651
-	return $res;
586
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
587
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
588
+    }
589
+    $default = array(
590
+        'transcoder' => false,
591
+        'methode' => 'GET',
592
+        'taille_max' => null,
593
+        'datas' => '',
594
+        'boundary' => '',
595
+        'refuser_gz' => false,
596
+        'if_modified_since' => '',
597
+        'uri_referer' => '',
598
+        'file' => '',
599
+        'follow_location' => 10,
600
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
601
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
602
+    );
603
+    $options = array_merge($default, $options);
604
+
605
+    // cas ou il n'est pas possible de cacher
606
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
607
+        return recuperer_url($url, $options);
608
+    }
609
+
610
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
611
+    static $errors = array();
612
+    if (isset($errors[$url])) {
613
+        return $errors[$url];
614
+    }
615
+
616
+    $sig = $options;
617
+    unset($sig['if_modified_since']);
618
+    unset($sig['delai_cache']);
619
+    $sig['url'] = $url;
620
+
621
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
622
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
623
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
624
+    $cache = "$sub$cache";
625
+
626
+    $res = false;
627
+    $is_cached = file_exists($cache);
628
+    if ($is_cached
629
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
630
+    ) {
631
+        lire_fichier($cache, $res);
632
+        if ($res = unserialize($res)) {
633
+            // mettre le last_modified et le status=304 ?
634
+        }
635
+    }
636
+    if (!$res) {
637
+        $res = recuperer_url($url, $options);
638
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
639
+        if (!$res) {
640
+            if ($is_cached) {
641
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
642
+                lire_fichier($cache, $res);
643
+                $res = unserialize($res);
644
+            }
645
+
646
+            return $errors[$url] = $res;
647
+        }
648
+        ecrire_fichier($cache, serialize($res));
649
+    }
650
+
651
+    return $res;
652 652
 }
653 653
 
654 654
 /**
@@ -686,52 +686,52 @@  discard block
 block discarded – undo
686 686
  *     - false si la page n'a pu être récupérée (status different de 200)
687 687
  **/
688 688
 function recuperer_page(
689
-	$url,
690
-	$trans = false,
691
-	$get_headers = false,
692
-	$taille_max = null,
693
-	$datas = '',
694
-	$boundary = '',
695
-	$refuser_gz = false,
696
-	$date_verif = '',
697
-	$uri_referer = ''
689
+    $url,
690
+    $trans = false,
691
+    $get_headers = false,
692
+    $taille_max = null,
693
+    $datas = '',
694
+    $boundary = '',
695
+    $refuser_gz = false,
696
+    $date_verif = '',
697
+    $uri_referer = ''
698 698
 ) {
699
-	// $copy = copier le fichier ?
700
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
701
-
702
-	if (!is_null($taille_max) and ($taille_max == 0)) {
703
-		$get = 'HEAD';
704
-	} else {
705
-		$get = 'GET';
706
-	}
707
-
708
-	$options = array(
709
-		'transcoder' => $trans === true,
710
-		'methode' => $get,
711
-		'datas' => $datas,
712
-		'boundary' => $boundary,
713
-		'refuser_gz' => $refuser_gz,
714
-		'if_modified_since' => $date_verif,
715
-		'uri_referer' => $uri_referer,
716
-		'file' => $copy ? $trans : '',
717
-		'follow_location' => 10,
718
-	);
719
-	if (!is_null($taille_max)) {
720
-		$options['taille_max'] = $taille_max;
721
-	}
722
-	// dix tentatives maximum en cas d'entetes 301...
723
-	$res = recuperer_url($url, $options);
724
-	if (!$res) {
725
-		return false;
726
-	}
727
-	if ($res['status'] !== 200) {
728
-		return false;
729
-	}
730
-	if ($get_headers) {
731
-		return $res['headers'] . "\n" . $res['page'];
732
-	}
733
-
734
-	return $res['page'];
699
+    // $copy = copier le fichier ?
700
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
701
+
702
+    if (!is_null($taille_max) and ($taille_max == 0)) {
703
+        $get = 'HEAD';
704
+    } else {
705
+        $get = 'GET';
706
+    }
707
+
708
+    $options = array(
709
+        'transcoder' => $trans === true,
710
+        'methode' => $get,
711
+        'datas' => $datas,
712
+        'boundary' => $boundary,
713
+        'refuser_gz' => $refuser_gz,
714
+        'if_modified_since' => $date_verif,
715
+        'uri_referer' => $uri_referer,
716
+        'file' => $copy ? $trans : '',
717
+        'follow_location' => 10,
718
+    );
719
+    if (!is_null($taille_max)) {
720
+        $options['taille_max'] = $taille_max;
721
+    }
722
+    // dix tentatives maximum en cas d'entetes 301...
723
+    $res = recuperer_url($url, $options);
724
+    if (!$res) {
725
+        return false;
726
+    }
727
+    if ($res['status'] !== 200) {
728
+        return false;
729
+    }
730
+    if ($get_headers) {
731
+        return $res['headers'] . "\n" . $res['page'];
732
+    }
733
+
734
+    return $res['page'];
735 735
 }
736 736
 
737 737
 
@@ -768,48 +768,48 @@  discard block
 block discarded – undo
768 768
  *     - false sinon
769 769
  **/
770 770
 function recuperer_lapage(
771
-	$url,
772
-	$trans = false,
773
-	$get = 'GET',
774
-	$taille_max = 1048576,
775
-	$datas = '',
776
-	$refuser_gz = false,
777
-	$date_verif = '',
778
-	$uri_referer = ''
771
+    $url,
772
+    $trans = false,
773
+    $get = 'GET',
774
+    $taille_max = 1048576,
775
+    $datas = '',
776
+    $refuser_gz = false,
777
+    $date_verif = '',
778
+    $uri_referer = ''
779 779
 ) {
780
-	// $copy = copier le fichier ?
781
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
782
-
783
-	// si on ecrit directement dans un fichier, pour ne pas manipuler
784
-	// en memoire refuser gz
785
-	if ($copy) {
786
-		$refuser_gz = true;
787
-	}
788
-
789
-	$options = array(
790
-		'transcoder' => $trans === true,
791
-		'methode' => $get,
792
-		'datas' => $datas,
793
-		'refuser_gz' => $refuser_gz,
794
-		'if_modified_since' => $date_verif,
795
-		'uri_referer' => $uri_referer,
796
-		'file' => $copy ? $trans : '',
797
-		'follow_location' => false,
798
-	);
799
-	if (!is_null($taille_max)) {
800
-		$options['taille_max'] = $taille_max;
801
-	}
802
-	// dix tentatives maximum en cas d'entetes 301...
803
-	$res = recuperer_url($url, $options);
804
-
805
-	if (!$res) {
806
-		return false;
807
-	}
808
-	if ($res['status'] !== 200) {
809
-		return false;
810
-	}
811
-
812
-	return array($res['headers'], $res['page']);
780
+    // $copy = copier le fichier ?
781
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
782
+
783
+    // si on ecrit directement dans un fichier, pour ne pas manipuler
784
+    // en memoire refuser gz
785
+    if ($copy) {
786
+        $refuser_gz = true;
787
+    }
788
+
789
+    $options = array(
790
+        'transcoder' => $trans === true,
791
+        'methode' => $get,
792
+        'datas' => $datas,
793
+        'refuser_gz' => $refuser_gz,
794
+        'if_modified_since' => $date_verif,
795
+        'uri_referer' => $uri_referer,
796
+        'file' => $copy ? $trans : '',
797
+        'follow_location' => false,
798
+    );
799
+    if (!is_null($taille_max)) {
800
+        $options['taille_max'] = $taille_max;
801
+    }
802
+    // dix tentatives maximum en cas d'entetes 301...
803
+    $res = recuperer_url($url, $options);
804
+
805
+    if (!$res) {
806
+        return false;
807
+    }
808
+    if ($res['status'] !== 200) {
809
+        return false;
810
+    }
811
+
812
+    return array($res['headers'], $res['page']);
813 813
 }
814 814
 
815 815
 /**
@@ -827,41 +827,41 @@  discard block
 block discarded – undo
827 827
  *   string contenu de la resource
828 828
  */
829 829
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
830
-	$taille = 0;
831
-	$result = '';
832
-	$fp = false;
833
-	if ($fichier) {
834
-		include_spip('inc/acces');
835
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
836
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
837
-		if (!$fp and file_exists($fichier)) {
838
-			return filesize($fichier);
839
-		}
840
-		if (!$fp) {
841
-			return false;
842
-		}
843
-		$result = 0; // on renvoie la taille du fichier
844
-	}
845
-	while (!feof($handle) and $taille < $taille_max) {
846
-		$res = fread($handle, 16384);
847
-		$taille += strlen($res);
848
-		if ($fp) {
849
-			fwrite($fp, $res);
850
-			$result = $taille;
851
-		} else {
852
-			$result .= $res;
853
-		}
854
-	}
855
-	if ($fp) {
856
-		spip_fclose_unlock($fp);
857
-		spip_unlink($fichier);
858
-		@rename($tmpfile, $fichier);
859
-		if (!file_exists($fichier)) {
860
-			return false;
861
-		}
862
-	}
863
-
864
-	return $result;
830
+    $taille = 0;
831
+    $result = '';
832
+    $fp = false;
833
+    if ($fichier) {
834
+        include_spip('inc/acces');
835
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
836
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
837
+        if (!$fp and file_exists($fichier)) {
838
+            return filesize($fichier);
839
+        }
840
+        if (!$fp) {
841
+            return false;
842
+        }
843
+        $result = 0; // on renvoie la taille du fichier
844
+    }
845
+    while (!feof($handle) and $taille < $taille_max) {
846
+        $res = fread($handle, 16384);
847
+        $taille += strlen($res);
848
+        if ($fp) {
849
+            fwrite($fp, $res);
850
+            $result = $taille;
851
+        } else {
852
+            $result .= $res;
853
+        }
854
+    }
855
+    if ($fp) {
856
+        spip_fclose_unlock($fp);
857
+        spip_unlink($fichier);
858
+        @rename($tmpfile, $fichier);
859
+        if (!file_exists($fichier)) {
860
+            return false;
861
+        }
862
+    }
863
+
864
+    return $result;
865 865
 }
866 866
 
867 867
 /**
@@ -883,34 +883,34 @@  discard block
 block discarded – undo
883 883
  *   string location
884 884
  */
885 885
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
886
-	$result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
887
-
888
-	$s = @trim(fgets($handle, 16384));
889
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
890
-		return false;
891
-	}
892
-	$result['status'] = intval($r[1]);
893
-	while ($s = trim(fgets($handle, 16384))) {
894
-		$result['headers'][] = $s . "\n";
895
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
896
-		list(, $d, $v) = $r;
897
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
898
-			$result['location'] = $v;
899
-		} elseif ($d == 'Last-Modified') {
900
-			$result['last_modified'] = strtotime($v);
901
-		}
902
-	}
903
-	if ($if_modified_since
904
-		and $result['last_modified']
905
-		and $if_modified_since > $result['last_modified']
906
-		and $result['status'] == 200
907
-	) {
908
-		$result['status'] = 304;
909
-	}
910
-
911
-	$result['headers'] = implode('', $result['headers']);
912
-
913
-	return $result;
886
+    $result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
887
+
888
+    $s = @trim(fgets($handle, 16384));
889
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
890
+        return false;
891
+    }
892
+    $result['status'] = intval($r[1]);
893
+    while ($s = trim(fgets($handle, 16384))) {
894
+        $result['headers'][] = $s . "\n";
895
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
896
+        list(, $d, $v) = $r;
897
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
898
+            $result['location'] = $v;
899
+        } elseif ($d == 'Last-Modified') {
900
+            $result['last_modified'] = strtotime($v);
901
+        }
902
+    }
903
+    if ($if_modified_since
904
+        and $result['last_modified']
905
+        and $if_modified_since > $result['last_modified']
906
+        and $result['status'] == 200
907
+    ) {
908
+        $result['status'] = 304;
909
+    }
910
+
911
+    $result['headers'] = implode('', $result['headers']);
912
+
913
+    return $result;
914 914
 }
915 915
 
916 916
 /**
@@ -932,20 +932,20 @@  discard block
 block discarded – undo
932 932
  *     - le tableau des entetes dans tous les autres cas
933 933
  **/
934 934
 function recuperer_entetes($f, $date_verif = '') {
935
-	//Cas ou la page distante n'a pas bouge depuis
936
-	//la derniere visite
937
-	$res = recuperer_entetes_complets($f, $date_verif);
938
-	if (!$res) {
939
-		return false;
940
-	}
941
-	if ($res['location']) {
942
-		return $res['location'];
943
-	}
944
-	if ($res['status'] != 200) {
945
-		return $res['status'];
946
-	}
947
-
948
-	return explode("\n", $res['headers']);
935
+    //Cas ou la page distante n'a pas bouge depuis
936
+    //la derniere visite
937
+    $res = recuperer_entetes_complets($f, $date_verif);
938
+    if (!$res) {
939
+        return false;
940
+    }
941
+    if ($res['location']) {
942
+        return $res['location'];
943
+    }
944
+    if ($res['status'] != 200) {
945
+        return $res['status'];
946
+    }
947
+
948
+    return explode("\n", $res['headers']);
949 949
 }
950 950
 
951 951
 /**
@@ -967,22 +967,22 @@  discard block
 block discarded – undo
967 967
  *     Nom du fichier pour copie locale
968 968
  **/
969 969
 function nom_fichier_copie_locale($source, $extension) {
970
-	include_spip('inc/documents');
970
+    include_spip('inc/documents');
971 971
 
972
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
973
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
972
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
973
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
974 974
 
975
-	// on se place tout le temps comme si on etait a la racine
976
-	if (_DIR_RACINE) {
977
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
978
-	}
975
+    // on se place tout le temps comme si on etait a la racine
976
+    if (_DIR_RACINE) {
977
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
978
+    }
979 979
 
980
-	$m = md5($source);
980
+    $m = md5($source);
981 981
 
982
-	return $d
983
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
984
-	. substr($m, 0, 4)
985
-	. ".$extension";
982
+    return $d
983
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
984
+    . substr($m, 0, 4)
985
+    . ".$extension";
986 986
 }
987 987
 
988 988
 /**
@@ -1000,68 +1000,68 @@  discard block
 block discarded – undo
1000 1000
  *      Nom du fichier calculé
1001 1001
  **/
1002 1002
 function fichier_copie_locale($source) {
1003
-	// Si c'est deja local pas de souci
1004
-	if (!tester_url_absolue($source)) {
1005
-		if (_DIR_RACINE) {
1006
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1007
-		}
1008
-
1009
-		return $source;
1010
-	}
1011
-
1012
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1013
-	// a deja ete copie en local avec cette extension
1014
-	// dans ce cas elle est fiable, pas la peine de requeter en base
1015
-	$path_parts = pathinfo($source);
1016
-	if (!isset($path_parts['extension'])) {
1017
-		$path_parts['extension'] = '';
1018
-	}
1019
-	$ext = $path_parts ? $path_parts['extension'] : '';
1020
-	if ($ext
1021
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1022
-		and $f = nom_fichier_copie_locale($source, $ext)
1023
-		and file_exists(_DIR_RACINE . $f)
1024
-	) {
1025
-		return $f;
1026
-	}
1027
-
1028
-
1029
-	// Si c'est deja dans la table des documents,
1030
-	// ramener le nom de sa copie potentielle
1031
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1032
-
1033
-	if ($ext) {
1034
-		return nom_fichier_copie_locale($source, $ext);
1035
-	}
1036
-
1037
-	// voir si l'extension indiquee dans le nom du fichier est ok
1038
-	// et si il n'aurait pas deja ete rapatrie
1039
-
1040
-	$ext = $path_parts ? $path_parts['extension'] : '';
1041
-
1042
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1043
-		$f = nom_fichier_copie_locale($source, $ext);
1044
-		if (file_exists(_DIR_RACINE . $f)) {
1045
-			return $f;
1046
-		}
1047
-	}
1048
-
1049
-	// Ping  pour voir si son extension est connue et autorisee
1050
-	// avec mise en cache du resultat du ping
1051
-
1052
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1053
-	if (!@file_exists($cache)
1054
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1055
-		or _request('var_mode') == 'recalcul'
1056
-	) {
1057
-		$path_parts = recuperer_infos_distantes($source, 0, false);
1058
-		ecrire_fichier($cache, serialize($path_parts));
1059
-	}
1060
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1061
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1062
-		return nom_fichier_copie_locale($source, $ext);
1063
-	}
1064
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1003
+    // Si c'est deja local pas de souci
1004
+    if (!tester_url_absolue($source)) {
1005
+        if (_DIR_RACINE) {
1006
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1007
+        }
1008
+
1009
+        return $source;
1010
+    }
1011
+
1012
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1013
+    // a deja ete copie en local avec cette extension
1014
+    // dans ce cas elle est fiable, pas la peine de requeter en base
1015
+    $path_parts = pathinfo($source);
1016
+    if (!isset($path_parts['extension'])) {
1017
+        $path_parts['extension'] = '';
1018
+    }
1019
+    $ext = $path_parts ? $path_parts['extension'] : '';
1020
+    if ($ext
1021
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1022
+        and $f = nom_fichier_copie_locale($source, $ext)
1023
+        and file_exists(_DIR_RACINE . $f)
1024
+    ) {
1025
+        return $f;
1026
+    }
1027
+
1028
+
1029
+    // Si c'est deja dans la table des documents,
1030
+    // ramener le nom de sa copie potentielle
1031
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1032
+
1033
+    if ($ext) {
1034
+        return nom_fichier_copie_locale($source, $ext);
1035
+    }
1036
+
1037
+    // voir si l'extension indiquee dans le nom du fichier est ok
1038
+    // et si il n'aurait pas deja ete rapatrie
1039
+
1040
+    $ext = $path_parts ? $path_parts['extension'] : '';
1041
+
1042
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1043
+        $f = nom_fichier_copie_locale($source, $ext);
1044
+        if (file_exists(_DIR_RACINE . $f)) {
1045
+            return $f;
1046
+        }
1047
+    }
1048
+
1049
+    // Ping  pour voir si son extension est connue et autorisee
1050
+    // avec mise en cache du resultat du ping
1051
+
1052
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1053
+    if (!@file_exists($cache)
1054
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
1055
+        or _request('var_mode') == 'recalcul'
1056
+    ) {
1057
+        $path_parts = recuperer_infos_distantes($source, 0, false);
1058
+        ecrire_fichier($cache, serialize($path_parts));
1059
+    }
1060
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1061
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1062
+        return nom_fichier_copie_locale($source, $ext);
1063
+    }
1064
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1065 1065
 }
1066 1066
 
1067 1067
 
@@ -1089,144 +1089,144 @@  discard block
 block discarded – undo
1089 1089
  **/
1090 1090
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
1091 1091
 
1092
-	// pas la peine de perdre son temps
1093
-	if (!tester_url_absolue($source)) {
1094
-		return false;
1095
-	}
1096
-
1097
-	# charger les alias des types mime
1098
-	include_spip('base/typedoc');
1099
-
1100
-	$a = array();
1101
-	$mime_type = '';
1102
-	// On va directement charger le debut des images et des fichiers html,
1103
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1104
-	// ca echoue l'utilisateur devra les entrer...
1105
-	if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1106
-		list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1107
-
1108
-		if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1109
-			$mime_type = (trim($regs[1]));
1110
-		} else {
1111
-			$mime_type = '';
1112
-		} // inconnu
1113
-
1114
-		// Appliquer les alias
1115
-		while (isset($GLOBALS['mime_alias'][$mime_type])) {
1116
-			$mime_type = $GLOBALS['mime_alias'][$mime_type];
1117
-		}
1118
-
1119
-		// Si on a un mime-type insignifiant
1120
-		// text/plain,application/octet-stream ou vide
1121
-		// c'est peut-etre que le serveur ne sait pas
1122
-		// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1123
-		// ou le Content-Disposition: attachment; filename=...
1124
-		$t = null;
1125
-		if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1126
-			if (!$t
1127
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1128
-			) {
1129
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1130
-			}
1131
-			if (!$t
1132
-				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1133
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1134
-			) {
1135
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1136
-			}
1137
-		}
1138
-
1139
-		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1140
-		if (!$t) {
1141
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1142
-		}
1143
-
1144
-		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1145
-		// On essaie de nouveau avec l'extension
1146
-		if (!$t
1147
-			and $mime_type != 'text/plain'
1148
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1149
-		) {
1150
-			# eviter xxx.3 => 3gp (> SPIP 3)
1151
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1152
-		}
1153
-
1154
-		if ($t) {
1155
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1156
-			$a['extension'] = $t['extension'];
1157
-		} else {
1158
-			# par defaut on retombe sur '.bin' si c'est autorise
1159
-			spip_log("mime-type $mime_type inconnu", 'distant');
1160
-			$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1161
-			if (!$t) {
1162
-				return false;
1163
-			}
1164
-			$a['extension'] = $t['extension'];
1165
-		}
1166
-
1167
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1168
-			$a['taille'] = intval($regs[1]);
1169
-		}
1170
-	}
1171
-
1172
-	// Echec avec HEAD, on tente avec GET
1173
-	if (!$a and !$max) {
1174
-		spip_log("tenter GET $source", 'distant');
1175
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1176
-	}
1177
-
1178
-	// si on a rien trouve pas la peine d'insister
1179
-	if (!$a) {
1180
-		return false;
1181
-	}
1182
-
1183
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1184
-	// recharger le document en GET et recuperer des donnees supplementaires...
1185
-	include_spip('inc/filtres_images_lib_mini');
1186
-	if (strpos($mime_type, "image/") === 0
1187
-	  and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1188
-		if ($max == 0
1189
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1190
-			and in_array($extension, formats_image_acceptables())
1191
-			and $charger_si_petite_image
1192
-		) {
1193
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1194
-		} else {
1195
-			if ($a['body']) {
1196
-				$a['extension'] = $extension;
1197
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1198
-				ecrire_fichier($a['fichier'], $a['body']);
1199
-				$size_image = @spip_getimagesize($a['fichier']);
1200
-				$a['largeur'] = intval($size_image[0]);
1201
-				$a['hauteur'] = intval($size_image[1]);
1202
-				$a['type_image'] = true;
1203
-			}
1204
-		}
1205
-	}
1206
-
1207
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1208
-	// ce sera mieux que 0x0
1209
-	// Flash is dead!
1210
-	if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1211
-		and empty($a['largeur'])
1212
-	) {
1213
-		$a['largeur'] = 425;
1214
-		$a['hauteur'] = 350;
1215
-	}
1216
-
1217
-	if ($mime_type == 'text/html') {
1218
-		include_spip('inc/filtres');
1219
-		$page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1220
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1221
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1222
-		}
1223
-		if (!isset($a['taille']) or !$a['taille']) {
1224
-			$a['taille'] = strlen($page); # a peu pres
1225
-		}
1226
-	}
1227
-	$a['mime_type'] = $mime_type;
1228
-
1229
-	return $a;
1092
+    // pas la peine de perdre son temps
1093
+    if (!tester_url_absolue($source)) {
1094
+        return false;
1095
+    }
1096
+
1097
+    # charger les alias des types mime
1098
+    include_spip('base/typedoc');
1099
+
1100
+    $a = array();
1101
+    $mime_type = '';
1102
+    // On va directement charger le debut des images et des fichiers html,
1103
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1104
+    // ca echoue l'utilisateur devra les entrer...
1105
+    if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1106
+        list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1107
+
1108
+        if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1109
+            $mime_type = (trim($regs[1]));
1110
+        } else {
1111
+            $mime_type = '';
1112
+        } // inconnu
1113
+
1114
+        // Appliquer les alias
1115
+        while (isset($GLOBALS['mime_alias'][$mime_type])) {
1116
+            $mime_type = $GLOBALS['mime_alias'][$mime_type];
1117
+        }
1118
+
1119
+        // Si on a un mime-type insignifiant
1120
+        // text/plain,application/octet-stream ou vide
1121
+        // c'est peut-etre que le serveur ne sait pas
1122
+        // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1123
+        // ou le Content-Disposition: attachment; filename=...
1124
+        $t = null;
1125
+        if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1126
+            if (!$t
1127
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1128
+            ) {
1129
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1130
+            }
1131
+            if (!$t
1132
+                and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1133
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1134
+            ) {
1135
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1136
+            }
1137
+        }
1138
+
1139
+        // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1140
+        if (!$t) {
1141
+            $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1142
+        }
1143
+
1144
+        // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1145
+        // On essaie de nouveau avec l'extension
1146
+        if (!$t
1147
+            and $mime_type != 'text/plain'
1148
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1149
+        ) {
1150
+            # eviter xxx.3 => 3gp (> SPIP 3)
1151
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1152
+        }
1153
+
1154
+        if ($t) {
1155
+            spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1156
+            $a['extension'] = $t['extension'];
1157
+        } else {
1158
+            # par defaut on retombe sur '.bin' si c'est autorise
1159
+            spip_log("mime-type $mime_type inconnu", 'distant');
1160
+            $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1161
+            if (!$t) {
1162
+                return false;
1163
+            }
1164
+            $a['extension'] = $t['extension'];
1165
+        }
1166
+
1167
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1168
+            $a['taille'] = intval($regs[1]);
1169
+        }
1170
+    }
1171
+
1172
+    // Echec avec HEAD, on tente avec GET
1173
+    if (!$a and !$max) {
1174
+        spip_log("tenter GET $source", 'distant');
1175
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1176
+    }
1177
+
1178
+    // si on a rien trouve pas la peine d'insister
1179
+    if (!$a) {
1180
+        return false;
1181
+    }
1182
+
1183
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1184
+    // recharger le document en GET et recuperer des donnees supplementaires...
1185
+    include_spip('inc/filtres_images_lib_mini');
1186
+    if (strpos($mime_type, "image/") === 0
1187
+      and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1188
+        if ($max == 0
1189
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1190
+            and in_array($extension, formats_image_acceptables())
1191
+            and $charger_si_petite_image
1192
+        ) {
1193
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1194
+        } else {
1195
+            if ($a['body']) {
1196
+                $a['extension'] = $extension;
1197
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1198
+                ecrire_fichier($a['fichier'], $a['body']);
1199
+                $size_image = @spip_getimagesize($a['fichier']);
1200
+                $a['largeur'] = intval($size_image[0]);
1201
+                $a['hauteur'] = intval($size_image[1]);
1202
+                $a['type_image'] = true;
1203
+            }
1204
+        }
1205
+    }
1206
+
1207
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1208
+    // ce sera mieux que 0x0
1209
+    // Flash is dead!
1210
+    if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1211
+        and empty($a['largeur'])
1212
+    ) {
1213
+        $a['largeur'] = 425;
1214
+        $a['hauteur'] = 350;
1215
+    }
1216
+
1217
+    if ($mime_type == 'text/html') {
1218
+        include_spip('inc/filtres');
1219
+        $page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1220
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1221
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1222
+        }
1223
+        if (!isset($a['taille']) or !$a['taille']) {
1224
+            $a['taille'] = strlen($page); # a peu pres
1225
+        }
1226
+    }
1227
+    $a['mime_type'] = $mime_type;
1228
+
1229
+    return $a;
1230 1230
 }
1231 1231
 
1232 1232
 
@@ -1242,45 +1242,45 @@  discard block
 block discarded – undo
1242 1242
  * @return string
1243 1243
  */
1244 1244
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1245
-	if (is_null($http_proxy)) {
1246
-		$http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1247
-	}
1248
-	// rien a faire si pas de proxy :)
1249
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1250
-		return '';
1251
-	}
1252
-
1253
-	if (is_null($http_noproxy)) {
1254
-		$http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1255
-	}
1256
-	// si pas d'exception, on retourne le proxy
1257
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1258
-		return $http_proxy;
1259
-	}
1260
-
1261
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1262
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1263
-	$http_noproxy = str_replace("\n", " ", $http_noproxy);
1264
-	$http_noproxy = str_replace("\r", " ", $http_noproxy);
1265
-	$http_noproxy = " $http_noproxy ";
1266
-	$domain = $host;
1267
-	// si le domaine exact www.example.org est dans les exceptions
1268
-	if (strpos($http_noproxy, " $domain ") !== false)
1269
-		return '';
1270
-
1271
-	while (strpos($domain, '.') !== false) {
1272
-		$domain = explode('.', $domain);
1273
-		array_shift($domain);
1274
-		$domain = implode('.', $domain);
1275
-
1276
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1277
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1278
-			return '';
1279
-		}
1280
-	}
1281
-
1282
-	// ok c'est pas une exception
1283
-	return $http_proxy;
1245
+    if (is_null($http_proxy)) {
1246
+        $http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1247
+    }
1248
+    // rien a faire si pas de proxy :)
1249
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1250
+        return '';
1251
+    }
1252
+
1253
+    if (is_null($http_noproxy)) {
1254
+        $http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1255
+    }
1256
+    // si pas d'exception, on retourne le proxy
1257
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1258
+        return $http_proxy;
1259
+    }
1260
+
1261
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1262
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1263
+    $http_noproxy = str_replace("\n", " ", $http_noproxy);
1264
+    $http_noproxy = str_replace("\r", " ", $http_noproxy);
1265
+    $http_noproxy = " $http_noproxy ";
1266
+    $domain = $host;
1267
+    // si le domaine exact www.example.org est dans les exceptions
1268
+    if (strpos($http_noproxy, " $domain ") !== false)
1269
+        return '';
1270
+
1271
+    while (strpos($domain, '.') !== false) {
1272
+        $domain = explode('.', $domain);
1273
+        array_shift($domain);
1274
+        $domain = implode('.', $domain);
1275
+
1276
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1277
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1278
+            return '';
1279
+        }
1280
+    }
1281
+
1282
+    // ok c'est pas une exception
1283
+    return $http_proxy;
1284 1284
 }
1285 1285
 
1286 1286
 
@@ -1303,58 +1303,58 @@  discard block
 block discarded – undo
1303 1303
  * @return array
1304 1304
  */
1305 1305
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1306
-	$user = $via_proxy = $proxy_user = '';
1307
-	$fopen = false;
1308
-
1309
-	$t = @parse_url($url);
1310
-	$host = $t['host'];
1311
-	if ($t['scheme'] == 'http') {
1312
-		$scheme = 'http';
1313
-		$noproxy = '';
1314
-	} elseif ($t['scheme'] == 'https') {
1315
-		$scheme = 'ssl';
1316
-		$noproxy = 'ssl://';
1317
-		if (!isset($t['port']) || !($port = $t['port'])) {
1318
-			$t['port'] = 443;
1319
-		}
1320
-	} else {
1321
-		$scheme = $t['scheme'];
1322
-		$noproxy = $scheme . '://';
1323
-	}
1324
-	if (isset($t['user'])) {
1325
-		$user = array($t['user'], $t['pass']);
1326
-	}
1327
-
1328
-	if (!isset($t['port']) || !($port = $t['port'])) {
1329
-		$port = 80;
1330
-	}
1331
-	if (!isset($t['path']) || !($path = $t['path'])) {
1332
-		$path = '/';
1333
-	}
1334
-
1335
-	if (!empty($t['query'])) {
1336
-		$path .= '?' . $t['query'];
1337
-	}
1338
-
1339
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1340
-	if (!$f or !is_resource($f)) {
1341
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1342
-		// ce qui correspond a $f===110
1343
-		if ($f !== 110
1344
-			and !need_proxy($host)
1345
-			and !_request('tester_proxy')
1346
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1347
-		) {
1348
-			$f = @fopen($url, 'rb');
1349
-			spip_log("connexion vers $url par simple fopen", 'distant');
1350
-			$fopen = true;
1351
-		} else {
1352
-			// echec total
1353
-			$f = false;
1354
-		}
1355
-	}
1356
-
1357
-	return array($f, $fopen);
1306
+    $user = $via_proxy = $proxy_user = '';
1307
+    $fopen = false;
1308
+
1309
+    $t = @parse_url($url);
1310
+    $host = $t['host'];
1311
+    if ($t['scheme'] == 'http') {
1312
+        $scheme = 'http';
1313
+        $noproxy = '';
1314
+    } elseif ($t['scheme'] == 'https') {
1315
+        $scheme = 'ssl';
1316
+        $noproxy = 'ssl://';
1317
+        if (!isset($t['port']) || !($port = $t['port'])) {
1318
+            $t['port'] = 443;
1319
+        }
1320
+    } else {
1321
+        $scheme = $t['scheme'];
1322
+        $noproxy = $scheme . '://';
1323
+    }
1324
+    if (isset($t['user'])) {
1325
+        $user = array($t['user'], $t['pass']);
1326
+    }
1327
+
1328
+    if (!isset($t['port']) || !($port = $t['port'])) {
1329
+        $port = 80;
1330
+    }
1331
+    if (!isset($t['path']) || !($path = $t['path'])) {
1332
+        $path = '/';
1333
+    }
1334
+
1335
+    if (!empty($t['query'])) {
1336
+        $path .= '?' . $t['query'];
1337
+    }
1338
+
1339
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1340
+    if (!$f or !is_resource($f)) {
1341
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1342
+        // ce qui correspond a $f===110
1343
+        if ($f !== 110
1344
+            and !need_proxy($host)
1345
+            and !_request('tester_proxy')
1346
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1347
+        ) {
1348
+            $f = @fopen($url, 'rb');
1349
+            spip_log("connexion vers $url par simple fopen", 'distant');
1350
+            $fopen = true;
1351
+        } else {
1352
+            // echec total
1353
+            $f = false;
1354
+        }
1355
+    }
1356
+
1357
+    return array($f, $fopen);
1358 1358
 }
1359 1359
 
1360 1360
 /**
@@ -1389,127 +1389,127 @@  discard block
 block discarded – undo
1389 1389
  *   resource socket vers l'url demandee
1390 1390
  */
1391 1391
 function lance_requete(
1392
-	$method,
1393
-	$scheme,
1394
-	$user,
1395
-	$host,
1396
-	$path,
1397
-	$port,
1398
-	$noproxy,
1399
-	$refuse_gz = false,
1400
-	$referer = '',
1401
-	$datas = '',
1402
-	$vers = 'HTTP/1.0',
1403
-	$date = ''
1392
+    $method,
1393
+    $scheme,
1394
+    $user,
1395
+    $host,
1396
+    $path,
1397
+    $port,
1398
+    $noproxy,
1399
+    $refuse_gz = false,
1400
+    $referer = '',
1401
+    $datas = '',
1402
+    $vers = 'HTTP/1.0',
1403
+    $date = ''
1404 1404
 ) {
1405 1405
 
1406
-	$proxy_user = '';
1407
-	$http_proxy = need_proxy($host);
1408
-	if ($user) {
1409
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1410
-	}
1411
-
1412
-	$connect = '';
1413
-	if ($http_proxy) {
1414
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1415
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1416
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1417
-				. "Host: $path_host\r\n"
1418
-				. "Proxy-Connection: Keep-Alive\r\n";
1419
-		} else {
1420
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1421
-				. (!$user ? '' : "$user@")
1422
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1423
-		}
1424
-		$t2 = @parse_url($http_proxy);
1425
-		$first_host = $t2['host'];
1426
-		if (!($port = $t2['port'])) {
1427
-			$port = 80;
1428
-		}
1429
-		if ($t2['user']) {
1430
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1431
-		}
1432
-	} else {
1433
-		$first_host = $noproxy . $host;
1434
-	}
1435
-
1436
-	if ($connect) {
1437
-		$streamContext = stream_context_create(array(
1438
-			'ssl' => array(
1439
-				'verify_peer' => false,
1440
-				'allow_self_signed' => true,
1441
-				'SNI_enabled' => true,
1442
-				'peer_name' => $host,
1443
-			)
1444
-		));
1445
-		if (version_compare(phpversion(), '5.6', '<')) {
1446
-			stream_context_set_option($streamContext, 'ssl', 'SNI_server_name', $host);
1447
-		}
1448
-		$f = @stream_socket_client(
1449
-			"tcp://$first_host:$port",
1450
-			$errno,
1451
-			$errstr,
1452
-			_INC_DISTANT_CONNECT_TIMEOUT,
1453
-			STREAM_CLIENT_CONNECT,
1454
-			$streamContext
1455
-		);
1456
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1457
-		if (!$f) {
1458
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1459
-			return $errno;
1460
-		}
1461
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1462
-
1463
-		fputs($f, $connect);
1464
-		fputs($f, "\r\n");
1465
-		$res = fread($f, 1024);
1466
-		if (!$res
1467
-			or !count($res = explode(' ', $res))
1468
-			or $res[1] !== '200'
1469
-		) {
1470
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1471
-			fclose($f);
1472
-
1473
-			return false;
1474
-		}
1475
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1476
-		stream_set_blocking($f, true);
1477
-		// envoyer le handshake
1478
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1479
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1480
-	} else {
1481
-		$ntry = 3;
1482
-		do {
1483
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1484
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1485
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1486
-		if (!$f) {
1487
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1488
-
1489
-			return $errno;
1490
-		}
1491
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1492
-	}
1493
-
1494
-	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1495
-
1496
-	$host_port = $host;
1497
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1498
-		$host_port .= ":$port";
1499
-	}
1500
-	$req = "$method $path $vers\r\n"
1501
-		. "Host: $host_port\r\n"
1502
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1503
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1504
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1505
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1506
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1507
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1508
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1406
+    $proxy_user = '';
1407
+    $http_proxy = need_proxy($host);
1408
+    if ($user) {
1409
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1410
+    }
1411
+
1412
+    $connect = '';
1413
+    if ($http_proxy) {
1414
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1415
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1416
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1417
+                . "Host: $path_host\r\n"
1418
+                . "Proxy-Connection: Keep-Alive\r\n";
1419
+        } else {
1420
+            $path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1421
+                . (!$user ? '' : "$user@")
1422
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1423
+        }
1424
+        $t2 = @parse_url($http_proxy);
1425
+        $first_host = $t2['host'];
1426
+        if (!($port = $t2['port'])) {
1427
+            $port = 80;
1428
+        }
1429
+        if ($t2['user']) {
1430
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1431
+        }
1432
+    } else {
1433
+        $first_host = $noproxy . $host;
1434
+    }
1435
+
1436
+    if ($connect) {
1437
+        $streamContext = stream_context_create(array(
1438
+            'ssl' => array(
1439
+                'verify_peer' => false,
1440
+                'allow_self_signed' => true,
1441
+                'SNI_enabled' => true,
1442
+                'peer_name' => $host,
1443
+            )
1444
+        ));
1445
+        if (version_compare(phpversion(), '5.6', '<')) {
1446
+            stream_context_set_option($streamContext, 'ssl', 'SNI_server_name', $host);
1447
+        }
1448
+        $f = @stream_socket_client(
1449
+            "tcp://$first_host:$port",
1450
+            $errno,
1451
+            $errstr,
1452
+            _INC_DISTANT_CONNECT_TIMEOUT,
1453
+            STREAM_CLIENT_CONNECT,
1454
+            $streamContext
1455
+        );
1456
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1457
+        if (!$f) {
1458
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1459
+            return $errno;
1460
+        }
1461
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1462
+
1463
+        fputs($f, $connect);
1464
+        fputs($f, "\r\n");
1465
+        $res = fread($f, 1024);
1466
+        if (!$res
1467
+            or !count($res = explode(' ', $res))
1468
+            or $res[1] !== '200'
1469
+        ) {
1470
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1471
+            fclose($f);
1472
+
1473
+            return false;
1474
+        }
1475
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1476
+        stream_set_blocking($f, true);
1477
+        // envoyer le handshake
1478
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1479
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1480
+    } else {
1481
+        $ntry = 3;
1482
+        do {
1483
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1484
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1485
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1486
+        if (!$f) {
1487
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1488
+
1489
+            return $errno;
1490
+        }
1491
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1492
+    }
1493
+
1494
+    $site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1495
+
1496
+    $host_port = $host;
1497
+    if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1498
+        $host_port .= ":$port";
1499
+    }
1500
+    $req = "$method $path $vers\r\n"
1501
+        . "Host: $host_port\r\n"
1502
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1503
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1504
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1505
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1506
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1507
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1508
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1509 1509
 
1510 1510
 #	spip_log("Requete\n$req", 'distant');
1511
-	fputs($f, $req);
1512
-	fputs($f, $datas ? $datas : "\r\n");
1511
+    fputs($f, $req);
1512
+    fputs($f, $datas ? $datas : "\r\n");
1513 1513
 
1514
-	return $f;
1514
+    return $f;
1515 1515
 }
Please login to merge, or discard this patch.