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