Completed
Push — master ( 0df2ac...a4a09d )
by cam
01:04
created
ecrire/inc/distant.php 1 patch
Indentation   +1041 added lines, -1041 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,87 +68,87 @@  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
-			['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
-		// si on retrouve l'extension
127
-		if (
128
-			!empty($res['headers'])
129
-			and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
130
-		) {
131
-			if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
132
-				$sanitizer($localrac);
133
-			}
134
-		}
135
-
136
-		// pour une eventuelle indexation
137
-		pipeline(
138
-			'post_edition',
139
-			[
140
-				'args' => [
141
-					'operation' => 'copie_locale',
142
-					'source' => $source,
143
-					'fichier' => $local,
144
-					'http_res' => $res['length'],
145
-				],
146
-				'data' => null
147
-			]
148
-		);
149
-	}
150
-
151
-	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
+            ['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
+        // si on retrouve l'extension
127
+        if (
128
+            !empty($res['headers'])
129
+            and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
130
+        ) {
131
+            if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
132
+                $sanitizer($localrac);
133
+            }
134
+        }
135
+
136
+        // pour une eventuelle indexation
137
+        pipeline(
138
+            'post_edition',
139
+            [
140
+                'args' => [
141
+                    'operation' => 'copie_locale',
142
+                    'source' => $source,
143
+                    'fichier' => $local,
144
+                    'http_res' => $res['length'],
145
+                ],
146
+                'data' => null
147
+            ]
148
+        );
149
+    }
150
+
151
+    return $local;
152 152
 }
153 153
 
154 154
 /**
@@ -163,99 +163,99 @@  discard block
 block discarded – undo
163 163
  *   url ou false en cas d'echec
164 164
  */
165 165
 function valider_url_distante($url, $known_hosts = []) {
166
-	if (!function_exists('protocole_verifier')) {
167
-		include_spip('inc/filtres_mini');
168
-	}
169
-
170
-	if (!protocole_verifier($url, ['http', 'https'])) {
171
-		return false;
172
-	}
173
-
174
-	$parsed_url = parse_url($url);
175
-	if (!$parsed_url or empty($parsed_url['host'])) {
176
-		return false;
177
-	}
178
-
179
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
180
-		return false;
181
-	}
182
-
183
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
184
-		return false;
185
-	}
186
-
187
-	if (!is_array($known_hosts)) {
188
-		$known_hosts = [$known_hosts];
189
-	}
190
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
191
-	$known_hosts[] = url_de_base();
192
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
193
-
194
-	$is_known_host = false;
195
-	foreach ($known_hosts as $known_host) {
196
-		$parse_known = parse_url($known_host);
197
-		if (
198
-			$parse_known
199
-			and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
200
-		) {
201
-			$is_known_host = true;
202
-			break;
203
-		}
204
-	}
205
-
206
-	if (!$is_known_host) {
207
-		$host = trim($parsed_url['host'], '.');
208
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
209
-			$ip = gethostbyname($host);
210
-			if ($ip === $host) {
211
-				// Error condition for gethostbyname()
212
-				$ip = false;
213
-			}
214
-			if ($records = dns_get_record($host)) {
215
-				foreach ($records as $record) {
216
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
217
-					// se fasse sur la meme IP
218
-					if ($record['ttl']<10) {
219
-						$ip = false;
220
-						break;
221
-					}
222
-				}
223
-			}
224
-			else {
225
-				$ip = false;
226
-			}
227
-		}
228
-		if ($ip) {
229
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
230
-				return false;
231
-			}
232
-		}
233
-	}
234
-
235
-	if (empty($parsed_url['port'])) {
236
-		return $url;
237
-	}
238
-
239
-	$port = $parsed_url['port'];
240
-	if ($port === 80  or $port === 443  or $port === 8080) {
241
-		return $url;
242
-	}
243
-
244
-	if ($is_known_host) {
245
-		foreach ($known_hosts as $known_host) {
246
-			$parse_known = parse_url($known_host);
247
-			if (
248
-				$parse_known
249
-				and !empty($parse_known['port'])
250
-				and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
251
-				and $parse_known['port'] == $port
252
-			) {
253
-				return $url;
254
-			}
255
-		}
256
-	}
257
-
258
-	return false;
166
+    if (!function_exists('protocole_verifier')) {
167
+        include_spip('inc/filtres_mini');
168
+    }
169
+
170
+    if (!protocole_verifier($url, ['http', 'https'])) {
171
+        return false;
172
+    }
173
+
174
+    $parsed_url = parse_url($url);
175
+    if (!$parsed_url or empty($parsed_url['host'])) {
176
+        return false;
177
+    }
178
+
179
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
180
+        return false;
181
+    }
182
+
183
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
184
+        return false;
185
+    }
186
+
187
+    if (!is_array($known_hosts)) {
188
+        $known_hosts = [$known_hosts];
189
+    }
190
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
191
+    $known_hosts[] = url_de_base();
192
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
193
+
194
+    $is_known_host = false;
195
+    foreach ($known_hosts as $known_host) {
196
+        $parse_known = parse_url($known_host);
197
+        if (
198
+            $parse_known
199
+            and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
200
+        ) {
201
+            $is_known_host = true;
202
+            break;
203
+        }
204
+    }
205
+
206
+    if (!$is_known_host) {
207
+        $host = trim($parsed_url['host'], '.');
208
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
209
+            $ip = gethostbyname($host);
210
+            if ($ip === $host) {
211
+                // Error condition for gethostbyname()
212
+                $ip = false;
213
+            }
214
+            if ($records = dns_get_record($host)) {
215
+                foreach ($records as $record) {
216
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
217
+                    // se fasse sur la meme IP
218
+                    if ($record['ttl']<10) {
219
+                        $ip = false;
220
+                        break;
221
+                    }
222
+                }
223
+            }
224
+            else {
225
+                $ip = false;
226
+            }
227
+        }
228
+        if ($ip) {
229
+            if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
230
+                return false;
231
+            }
232
+        }
233
+    }
234
+
235
+    if (empty($parsed_url['port'])) {
236
+        return $url;
237
+    }
238
+
239
+    $port = $parsed_url['port'];
240
+    if ($port === 80  or $port === 443  or $port === 8080) {
241
+        return $url;
242
+    }
243
+
244
+    if ($is_known_host) {
245
+        foreach ($known_hosts as $known_host) {
246
+            $parse_known = parse_url($known_host);
247
+            if (
248
+                $parse_known
249
+                and !empty($parse_known['port'])
250
+                and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
251
+                and $parse_known['port'] == $port
252
+            ) {
253
+                return $url;
254
+            }
255
+        }
256
+    }
257
+
258
+    return false;
259 259
 }
260 260
 
261 261
 /**
@@ -275,86 +275,86 @@  discard block
 block discarded – undo
275 275
  */
276 276
 function prepare_donnees_post($donnees, $boundary = '') {
277 277
 
278
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
279
-	// pour un appel soap par exemple
280
-	// l'entete est separe des donnees par un double retour a la ligne
281
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
282
-	if (is_string($donnees) && strlen($donnees)) {
283
-		$entete = '';
284
-		// on repasse tous les \r\n et \r en simples \n
285
-		$donnees = str_replace("\r\n", "\n", $donnees);
286
-		$donnees = str_replace("\r", "\n", $donnees);
287
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
288
-		$p = strpos($donnees, "\n\n");
289
-		if ($p !== false) {
290
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
291
-			$donnees = substr($donnees, $p + 2);
292
-		}
293
-		$chaine = str_replace("\n", "\r\n", $donnees);
294
-	} else {
295
-		/* boundary automatique */
296
-		// Si on a plus de 500 octects de donnees, on "boundarise"
297
-		if ($boundary === '') {
298
-			$taille = 0;
299
-			foreach ($donnees as $cle => $valeur) {
300
-				if (is_array($valeur)) {
301
-					foreach ($valeur as $val2) {
302
-						$taille += strlen($val2);
303
-					}
304
-				} else {
305
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
306
-					$taille += strlen($valeur);
307
-				}
308
-			}
309
-			if ($taille > 500) {
310
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
311
-			}
312
-		}
313
-
314
-		if (is_string($boundary) and strlen($boundary)) {
315
-			// fabrique une chaine HTTP pour un POST avec boundary
316
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
317
-			$chaine = '';
318
-			if (is_array($donnees)) {
319
-				foreach ($donnees as $cle => $valeur) {
320
-					if (is_array($valeur)) {
321
-						foreach ($valeur as $val2) {
322
-							$chaine .= "\r\n--$boundary\r\n";
323
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
324
-							$chaine .= "\r\n";
325
-							$chaine .= $val2;
326
-						}
327
-					} else {
328
-						$chaine .= "\r\n--$boundary\r\n";
329
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
330
-						$chaine .= "\r\n";
331
-						$chaine .= $valeur;
332
-					}
333
-				}
334
-				$chaine .= "\r\n--$boundary\r\n";
335
-			}
336
-		} else {
337
-			// fabrique une chaine HTTP simple pour un POST
338
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
339
-			$chaine = [];
340
-			if (is_array($donnees)) {
341
-				foreach ($donnees as $cle => $valeur) {
342
-					if (is_array($valeur)) {
343
-						foreach ($valeur as $val2) {
344
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
345
-						}
346
-					} else {
347
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
348
-					}
349
-				}
350
-				$chaine = implode('&', $chaine);
351
-			} else {
352
-				$chaine = $donnees;
353
-			}
354
-		}
355
-	}
356
-
357
-	return [$entete, $chaine];
278
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
279
+    // pour un appel soap par exemple
280
+    // l'entete est separe des donnees par un double retour a la ligne
281
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
282
+    if (is_string($donnees) && strlen($donnees)) {
283
+        $entete = '';
284
+        // on repasse tous les \r\n et \r en simples \n
285
+        $donnees = str_replace("\r\n", "\n", $donnees);
286
+        $donnees = str_replace("\r", "\n", $donnees);
287
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
288
+        $p = strpos($donnees, "\n\n");
289
+        if ($p !== false) {
290
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
291
+            $donnees = substr($donnees, $p + 2);
292
+        }
293
+        $chaine = str_replace("\n", "\r\n", $donnees);
294
+    } else {
295
+        /* boundary automatique */
296
+        // Si on a plus de 500 octects de donnees, on "boundarise"
297
+        if ($boundary === '') {
298
+            $taille = 0;
299
+            foreach ($donnees as $cle => $valeur) {
300
+                if (is_array($valeur)) {
301
+                    foreach ($valeur as $val2) {
302
+                        $taille += strlen($val2);
303
+                    }
304
+                } else {
305
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
306
+                    $taille += strlen($valeur);
307
+                }
308
+            }
309
+            if ($taille > 500) {
310
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
311
+            }
312
+        }
313
+
314
+        if (is_string($boundary) and strlen($boundary)) {
315
+            // fabrique une chaine HTTP pour un POST avec boundary
316
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
317
+            $chaine = '';
318
+            if (is_array($donnees)) {
319
+                foreach ($donnees as $cle => $valeur) {
320
+                    if (is_array($valeur)) {
321
+                        foreach ($valeur as $val2) {
322
+                            $chaine .= "\r\n--$boundary\r\n";
323
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
324
+                            $chaine .= "\r\n";
325
+                            $chaine .= $val2;
326
+                        }
327
+                    } else {
328
+                        $chaine .= "\r\n--$boundary\r\n";
329
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
330
+                        $chaine .= "\r\n";
331
+                        $chaine .= $valeur;
332
+                    }
333
+                }
334
+                $chaine .= "\r\n--$boundary\r\n";
335
+            }
336
+        } else {
337
+            // fabrique une chaine HTTP simple pour un POST
338
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
339
+            $chaine = [];
340
+            if (is_array($donnees)) {
341
+                foreach ($donnees as $cle => $valeur) {
342
+                    if (is_array($valeur)) {
343
+                        foreach ($valeur as $val2) {
344
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
345
+                        }
346
+                    } else {
347
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
348
+                    }
349
+                }
350
+                $chaine = implode('&', $chaine);
351
+            } else {
352
+                $chaine = $donnees;
353
+            }
354
+        }
355
+    }
356
+
357
+    return [$entete, $chaine];
358 358
 }
359 359
 
360 360
 /**
@@ -368,22 +368,22 @@  discard block
 block discarded – undo
368 368
  */
369 369
 function url_to_ascii($url_idn) {
370 370
 
371
-	if ($parts = parse_url($url_idn)) {
372
-		$host = $parts['host'];
373
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
374
-			include_spip('inc/idna_convert.class');
375
-			$IDN = new idna_convert();
376
-			$host_ascii = $IDN->encode($host);
377
-			$url_idn = explode($host, $url_idn, 2);
378
-			$url_idn = implode($host_ascii, $url_idn);
379
-		}
380
-		// et on urlencode les char utf si besoin dans le path
381
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function ($match) {
382
- return urlencode($match[0]);
383
-		}, $url_idn);
384
-	}
385
-
386
-	return $url_idn;
371
+    if ($parts = parse_url($url_idn)) {
372
+        $host = $parts['host'];
373
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
374
+            include_spip('inc/idna_convert.class');
375
+            $IDN = new idna_convert();
376
+            $host_ascii = $IDN->encode($host);
377
+            $url_idn = explode($host, $url_idn, 2);
378
+            $url_idn = implode($host_ascii, $url_idn);
379
+        }
380
+        // et on urlencode les char utf si besoin dans le path
381
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', function ($match) {
382
+    return urlencode($match[0]);
383
+        }, $url_idn);
384
+    }
385
+
386
+    return $url_idn;
387 387
 }
388 388
 
389 389
 /**
@@ -424,197 +424,197 @@  discard block
 block discarded – undo
424 424
  *     string file : nom du fichier si enregistre dans un fichier
425 425
  */
426 426
 function recuperer_url($url, $options = []) {
427
-	// Conserve la mémoire de la méthode fournit éventuellement
428
-	$methode_demandee = $options['methode'] ?? '';
429
-	$default = [
430
-		'transcoder' => false,
431
-		'methode' => 'GET',
432
-		'taille_max' => null,
433
-		'headers' => [],
434
-		'datas' => '',
435
-		'boundary' => '',
436
-		'refuser_gz' => false,
437
-		'if_modified_since' => '',
438
-		'uri_referer' => '',
439
-		'file' => '',
440
-		'follow_location' => 10,
441
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
442
-	];
443
-	$options = array_merge($default, $options);
444
-	// copier directement dans un fichier ?
445
-	$copy = $options['file'];
446
-
447
-	if ($options['methode'] == 'HEAD') {
448
-		$options['taille_max'] = 0;
449
-	}
450
-	if (is_null($options['taille_max'])) {
451
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
452
-	}
453
-
454
-
455
-	// Ajout des en-têtes spécifiques si besoin
456
-	$head_add = '';
457
-	if (!empty($options['headers'])) {
458
-		foreach ($options['headers'] as $champ => $valeur) {
459
-			$head_add .= $champ . ': ' . $valeur . "\r\n";
460
-		}
461
-		// ne pas le repasser a recuperer_url si on follow un location, car ils seront dans datas
462
-		unset($options['headers']);
463
-	}
464
-
465
-	if (!empty($options['datas'])) {
466
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
467
-		$head .= $head_add;
468
-		if (stripos($head, 'Content-Length:') === false) {
469
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
470
-		}
471
-		$options['datas'] = $head . "\r\n" . $postdata;
472
-		if (
473
-			strlen($postdata)
474
-			and !$methode_demandee
475
-		) {
476
-			$options['methode'] = 'POST';
477
-		}
478
-	} elseif ($head_add) {
479
-		$options['datas'] = $head_add . "\r\n";
480
-	}
481
-
482
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
483
-	$url = preg_replace(',^feed://,i', 'http://', $url);
484
-	if (!tester_url_absolue($url)) {
485
-		$url = 'http://' . $url;
486
-	} elseif (strncmp($url, '//', 2) == 0) {
487
-		$url = 'http:' . $url;
488
-	}
489
-
490
-	$url = url_to_ascii($url);
491
-
492
-	$result = [
493
-		'status' => 0,
494
-		'headers' => '',
495
-		'page' => '',
496
-		'length' => 0,
497
-		'last_modified' => '',
498
-		'location' => '',
499
-		'url' => $url
500
-	];
501
-
502
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
503
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
504
-
505
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
506
-	list($handle, $fopen) = init_http(
507
-		$options['methode'],
508
-		$url,
509
-		$refuser_gz,
510
-		$options['uri_referer'],
511
-		$options['datas'],
512
-		$options['version_http'],
513
-		$options['if_modified_since']
514
-	);
515
-	if (!$handle) {
516
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
517
-
518
-		return false;
519
-	}
520
-
521
-	// Sauf en fopen, envoyer le flux d'entree
522
-	// et recuperer les en-tetes de reponses
523
-	if (!$fopen) {
524
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
525
-		if (!$res) {
526
-			fclose($handle);
527
-			$t = @parse_url($url);
528
-			$host = $t['host'];
529
-			// Chinoisierie inexplicable pour contrer
530
-			// les actions liberticides de l'empire du milieu
531
-			if (
532
-				!need_proxy($host)
533
-				and $res = @file_get_contents($url)
534
-			) {
535
-				$result['length'] = strlen($res);
536
-				if ($copy) {
537
-					ecrire_fichier($copy, $res);
538
-					$result['file'] = $copy;
539
-				} else {
540
-					$result['page'] = $res;
541
-				}
542
-				$res = [
543
-					'status' => 200,
544
-				];
545
-			} else {
546
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
547
-				return false;
548
-			}
549
-		} elseif ($res['location'] and $options['follow_location']) {
550
-			$options['follow_location']--;
551
-			fclose($handle);
552
-			include_spip('inc/filtres');
553
-			$url = suivre_lien($url, $res['location']);
554
-			spip_log("recuperer_url recommence sur $url", 'distant');
555
-
556
-			return recuperer_url($url, $options);
557
-		} elseif ($res['status'] !== 200) {
558
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
559
-		}
560
-		$result['status'] = $res['status'];
561
-		if (isset($res['headers'])) {
562
-			$result['headers'] = $res['headers'];
563
-		}
564
-		if (isset($res['last_modified'])) {
565
-			$result['last_modified'] = $res['last_modified'];
566
-		}
567
-		if (isset($res['location'])) {
568
-			$result['location'] = $res['location'];
569
-		}
570
-	}
571
-
572
-	// on ne veut que les entetes
573
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
574
-		return $result;
575
-	}
576
-
577
-
578
-	// s'il faut deballer, le faire via un fichier temporaire
579
-	// sinon la memoire explose pour les gros flux
580
-
581
-	$gz = false;
582
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
583
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
584
-	}
585
-
586
-	// si on a pas deja recuperer le contenu par une methode detournee
587
-	if (!$result['length']) {
588
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
589
-		fclose($handle);
590
-		if ($copy) {
591
-			$result['length'] = $res;
592
-			$result['file'] = $copy;
593
-		} elseif ($res) {
594
-			$result['page'] = &$res;
595
-			$result['length'] = strlen($result['page']);
596
-		}
597
-		if (!$result['status']) {
598
-			$result['status'] = 200; // on a reussi, donc !
599
-		}
600
-	}
601
-	if (!$result['page']) {
602
-		return $result;
603
-	}
604
-
605
-	// Decompresser au besoin
606
-	if ($gz) {
607
-		$result['page'] = implode('', gzfile($gz));
608
-		supprimer_fichier($gz);
609
-	}
610
-
611
-	// Faut-il l'importer dans notre charset local ?
612
-	if ($options['transcoder']) {
613
-		include_spip('inc/charsets');
614
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
615
-	}
616
-
617
-	return $result;
427
+    // Conserve la mémoire de la méthode fournit éventuellement
428
+    $methode_demandee = $options['methode'] ?? '';
429
+    $default = [
430
+        'transcoder' => false,
431
+        'methode' => 'GET',
432
+        'taille_max' => null,
433
+        'headers' => [],
434
+        'datas' => '',
435
+        'boundary' => '',
436
+        'refuser_gz' => false,
437
+        'if_modified_since' => '',
438
+        'uri_referer' => '',
439
+        'file' => '',
440
+        'follow_location' => 10,
441
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
442
+    ];
443
+    $options = array_merge($default, $options);
444
+    // copier directement dans un fichier ?
445
+    $copy = $options['file'];
446
+
447
+    if ($options['methode'] == 'HEAD') {
448
+        $options['taille_max'] = 0;
449
+    }
450
+    if (is_null($options['taille_max'])) {
451
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
452
+    }
453
+
454
+
455
+    // Ajout des en-têtes spécifiques si besoin
456
+    $head_add = '';
457
+    if (!empty($options['headers'])) {
458
+        foreach ($options['headers'] as $champ => $valeur) {
459
+            $head_add .= $champ . ': ' . $valeur . "\r\n";
460
+        }
461
+        // ne pas le repasser a recuperer_url si on follow un location, car ils seront dans datas
462
+        unset($options['headers']);
463
+    }
464
+
465
+    if (!empty($options['datas'])) {
466
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
467
+        $head .= $head_add;
468
+        if (stripos($head, 'Content-Length:') === false) {
469
+            $head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
470
+        }
471
+        $options['datas'] = $head . "\r\n" . $postdata;
472
+        if (
473
+            strlen($postdata)
474
+            and !$methode_demandee
475
+        ) {
476
+            $options['methode'] = 'POST';
477
+        }
478
+    } elseif ($head_add) {
479
+        $options['datas'] = $head_add . "\r\n";
480
+    }
481
+
482
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
483
+    $url = preg_replace(',^feed://,i', 'http://', $url);
484
+    if (!tester_url_absolue($url)) {
485
+        $url = 'http://' . $url;
486
+    } elseif (strncmp($url, '//', 2) == 0) {
487
+        $url = 'http:' . $url;
488
+    }
489
+
490
+    $url = url_to_ascii($url);
491
+
492
+    $result = [
493
+        'status' => 0,
494
+        'headers' => '',
495
+        'page' => '',
496
+        'length' => 0,
497
+        'last_modified' => '',
498
+        'location' => '',
499
+        'url' => $url
500
+    ];
501
+
502
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
503
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
504
+
505
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
506
+    list($handle, $fopen) = init_http(
507
+        $options['methode'],
508
+        $url,
509
+        $refuser_gz,
510
+        $options['uri_referer'],
511
+        $options['datas'],
512
+        $options['version_http'],
513
+        $options['if_modified_since']
514
+    );
515
+    if (!$handle) {
516
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
517
+
518
+        return false;
519
+    }
520
+
521
+    // Sauf en fopen, envoyer le flux d'entree
522
+    // et recuperer les en-tetes de reponses
523
+    if (!$fopen) {
524
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
525
+        if (!$res) {
526
+            fclose($handle);
527
+            $t = @parse_url($url);
528
+            $host = $t['host'];
529
+            // Chinoisierie inexplicable pour contrer
530
+            // les actions liberticides de l'empire du milieu
531
+            if (
532
+                !need_proxy($host)
533
+                and $res = @file_get_contents($url)
534
+            ) {
535
+                $result['length'] = strlen($res);
536
+                if ($copy) {
537
+                    ecrire_fichier($copy, $res);
538
+                    $result['file'] = $copy;
539
+                } else {
540
+                    $result['page'] = $res;
541
+                }
542
+                $res = [
543
+                    'status' => 200,
544
+                ];
545
+            } else {
546
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
547
+                return false;
548
+            }
549
+        } elseif ($res['location'] and $options['follow_location']) {
550
+            $options['follow_location']--;
551
+            fclose($handle);
552
+            include_spip('inc/filtres');
553
+            $url = suivre_lien($url, $res['location']);
554
+            spip_log("recuperer_url recommence sur $url", 'distant');
555
+
556
+            return recuperer_url($url, $options);
557
+        } elseif ($res['status'] !== 200) {
558
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
559
+        }
560
+        $result['status'] = $res['status'];
561
+        if (isset($res['headers'])) {
562
+            $result['headers'] = $res['headers'];
563
+        }
564
+        if (isset($res['last_modified'])) {
565
+            $result['last_modified'] = $res['last_modified'];
566
+        }
567
+        if (isset($res['location'])) {
568
+            $result['location'] = $res['location'];
569
+        }
570
+    }
571
+
572
+    // on ne veut que les entetes
573
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
574
+        return $result;
575
+    }
576
+
577
+
578
+    // s'il faut deballer, le faire via un fichier temporaire
579
+    // sinon la memoire explose pour les gros flux
580
+
581
+    $gz = false;
582
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
583
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
584
+    }
585
+
586
+    // si on a pas deja recuperer le contenu par une methode detournee
587
+    if (!$result['length']) {
588
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
589
+        fclose($handle);
590
+        if ($copy) {
591
+            $result['length'] = $res;
592
+            $result['file'] = $copy;
593
+        } elseif ($res) {
594
+            $result['page'] = &$res;
595
+            $result['length'] = strlen($result['page']);
596
+        }
597
+        if (!$result['status']) {
598
+            $result['status'] = 200; // on a reussi, donc !
599
+        }
600
+    }
601
+    if (!$result['page']) {
602
+        return $result;
603
+    }
604
+
605
+    // Decompresser au besoin
606
+    if ($gz) {
607
+        $result['page'] = implode('', gzfile($gz));
608
+        supprimer_fichier($gz);
609
+    }
610
+
611
+    // Faut-il l'importer dans notre charset local ?
612
+    if ($options['transcoder']) {
613
+        include_spip('inc/charsets');
614
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
615
+    }
616
+
617
+    return $result;
618 618
 }
619 619
 
620 620
 /**
@@ -630,73 +630,73 @@  discard block
 block discarded – undo
630 630
  * @return array|bool|mixed
631 631
  */
632 632
 function recuperer_url_cache($url, $options = []) {
633
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
634
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
635
-	}
636
-	$default = [
637
-		'transcoder' => false,
638
-		'methode' => 'GET',
639
-		'taille_max' => null,
640
-		'datas' => '',
641
-		'boundary' => '',
642
-		'refuser_gz' => false,
643
-		'if_modified_since' => '',
644
-		'uri_referer' => '',
645
-		'file' => '',
646
-		'follow_location' => 10,
647
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
648
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
649
-	];
650
-	$options = array_merge($default, $options);
651
-
652
-	// cas ou il n'est pas possible de cacher
653
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
654
-		return recuperer_url($url, $options);
655
-	}
656
-
657
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
658
-	static $errors = [];
659
-	if (isset($errors[$url])) {
660
-		return $errors[$url];
661
-	}
662
-
663
-	$sig = $options;
664
-	unset($sig['if_modified_since']);
665
-	unset($sig['delai_cache']);
666
-	$sig['url'] = $url;
667
-
668
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
669
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
670
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
671
-	$cache = "$sub$cache";
672
-
673
-	$res = false;
674
-	$is_cached = file_exists($cache);
675
-	if (
676
-		$is_cached
677
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
678
-	) {
679
-		lire_fichier($cache, $res);
680
-		if ($res = unserialize($res)) {
681
-			// mettre le last_modified et le status=304 ?
682
-		}
683
-	}
684
-	if (!$res) {
685
-		$res = recuperer_url($url, $options);
686
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
687
-		if (!$res) {
688
-			if ($is_cached) {
689
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
690
-				lire_fichier($cache, $res);
691
-				$res = unserialize($res);
692
-			}
693
-
694
-			return $errors[$url] = $res;
695
-		}
696
-		ecrire_fichier($cache, serialize($res));
697
-	}
698
-
699
-	return $res;
633
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
634
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
635
+    }
636
+    $default = [
637
+        'transcoder' => false,
638
+        'methode' => 'GET',
639
+        'taille_max' => null,
640
+        'datas' => '',
641
+        'boundary' => '',
642
+        'refuser_gz' => false,
643
+        'if_modified_since' => '',
644
+        'uri_referer' => '',
645
+        'file' => '',
646
+        'follow_location' => 10,
647
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
648
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
649
+    ];
650
+    $options = array_merge($default, $options);
651
+
652
+    // cas ou il n'est pas possible de cacher
653
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
654
+        return recuperer_url($url, $options);
655
+    }
656
+
657
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
658
+    static $errors = [];
659
+    if (isset($errors[$url])) {
660
+        return $errors[$url];
661
+    }
662
+
663
+    $sig = $options;
664
+    unset($sig['if_modified_since']);
665
+    unset($sig['delai_cache']);
666
+    $sig['url'] = $url;
667
+
668
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
669
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
670
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
671
+    $cache = "$sub$cache";
672
+
673
+    $res = false;
674
+    $is_cached = file_exists($cache);
675
+    if (
676
+        $is_cached
677
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
678
+    ) {
679
+        lire_fichier($cache, $res);
680
+        if ($res = unserialize($res)) {
681
+            // mettre le last_modified et le status=304 ?
682
+        }
683
+    }
684
+    if (!$res) {
685
+        $res = recuperer_url($url, $options);
686
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
687
+        if (!$res) {
688
+            if ($is_cached) {
689
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
690
+                lire_fichier($cache, $res);
691
+                $res = unserialize($res);
692
+            }
693
+
694
+            return $errors[$url] = $res;
695
+        }
696
+        ecrire_fichier($cache, serialize($res));
697
+    }
698
+
699
+    return $res;
700 700
 }
701 701
 
702 702
 /**
@@ -714,41 +714,41 @@  discard block
 block discarded – undo
714 714
  *   string contenu de la resource
715 715
  */
716 716
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
717
-	$taille = 0;
718
-	$result = '';
719
-	$fp = false;
720
-	if ($fichier) {
721
-		include_spip('inc/acces');
722
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
723
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
724
-		if (!$fp and file_exists($fichier)) {
725
-			return filesize($fichier);
726
-		}
727
-		if (!$fp) {
728
-			return false;
729
-		}
730
-		$result = 0; // on renvoie la taille du fichier
731
-	}
732
-	while (!feof($handle) and $taille < $taille_max) {
733
-		$res = fread($handle, 16384);
734
-		$taille += strlen($res);
735
-		if ($fp) {
736
-			fwrite($fp, $res);
737
-			$result = $taille;
738
-		} else {
739
-			$result .= $res;
740
-		}
741
-	}
742
-	if ($fp) {
743
-		spip_fclose_unlock($fp);
744
-		spip_unlink($fichier);
745
-		@rename($tmpfile, $fichier);
746
-		if (!file_exists($fichier)) {
747
-			return false;
748
-		}
749
-	}
750
-
751
-	return $result;
717
+    $taille = 0;
718
+    $result = '';
719
+    $fp = false;
720
+    if ($fichier) {
721
+        include_spip('inc/acces');
722
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
723
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
724
+        if (!$fp and file_exists($fichier)) {
725
+            return filesize($fichier);
726
+        }
727
+        if (!$fp) {
728
+            return false;
729
+        }
730
+        $result = 0; // on renvoie la taille du fichier
731
+    }
732
+    while (!feof($handle) and $taille < $taille_max) {
733
+        $res = fread($handle, 16384);
734
+        $taille += strlen($res);
735
+        if ($fp) {
736
+            fwrite($fp, $res);
737
+            $result = $taille;
738
+        } else {
739
+            $result .= $res;
740
+        }
741
+    }
742
+    if ($fp) {
743
+        spip_fclose_unlock($fp);
744
+        spip_unlink($fichier);
745
+        @rename($tmpfile, $fichier);
746
+        if (!file_exists($fichier)) {
747
+            return false;
748
+        }
749
+    }
750
+
751
+    return $result;
752 752
 }
753 753
 
754 754
 /**
@@ -770,35 +770,35 @@  discard block
 block discarded – undo
770 770
  *   string location
771 771
  */
772 772
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
773
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
774
-
775
-	$s = @trim(fgets($handle, 16384));
776
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
777
-		return false;
778
-	}
779
-	$result['status'] = intval($r[1]);
780
-	while ($s = trim(fgets($handle, 16384))) {
781
-		$result['headers'][] = $s . "\n";
782
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
783
-		list(, $d, $v) = $r;
784
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
785
-			$result['location'] = $v;
786
-		} elseif ($d == 'Last-Modified') {
787
-			$result['last_modified'] = strtotime($v);
788
-		}
789
-	}
790
-	if (
791
-		$if_modified_since
792
-		and $result['last_modified']
793
-		and $if_modified_since > $result['last_modified']
794
-		and $result['status'] == 200
795
-	) {
796
-		$result['status'] = 304;
797
-	}
798
-
799
-	$result['headers'] = implode('', $result['headers']);
800
-
801
-	return $result;
773
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
774
+
775
+    $s = @trim(fgets($handle, 16384));
776
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
777
+        return false;
778
+    }
779
+    $result['status'] = intval($r[1]);
780
+    while ($s = trim(fgets($handle, 16384))) {
781
+        $result['headers'][] = $s . "\n";
782
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
783
+        list(, $d, $v) = $r;
784
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
785
+            $result['location'] = $v;
786
+        } elseif ($d == 'Last-Modified') {
787
+            $result['last_modified'] = strtotime($v);
788
+        }
789
+    }
790
+    if (
791
+        $if_modified_since
792
+        and $result['last_modified']
793
+        and $if_modified_since > $result['last_modified']
794
+        and $result['status'] == 200
795
+    ) {
796
+        $result['status'] = 304;
797
+    }
798
+
799
+    $result['headers'] = implode('', $result['headers']);
800
+
801
+    return $result;
802 802
 }
803 803
 
804 804
 /**
@@ -820,22 +820,22 @@  discard block
 block discarded – undo
820 820
  *     Nom du fichier pour copie locale
821 821
  **/
822 822
 function nom_fichier_copie_locale($source, $extension) {
823
-	include_spip('inc/documents');
823
+    include_spip('inc/documents');
824 824
 
825
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
826
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
825
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
826
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
827 827
 
828
-	// on se place tout le temps comme si on etait a la racine
829
-	if (_DIR_RACINE) {
830
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
831
-	}
828
+    // on se place tout le temps comme si on etait a la racine
829
+    if (_DIR_RACINE) {
830
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
831
+    }
832 832
 
833
-	$m = md5($source);
833
+    $m = md5($source);
834 834
 
835
-	return $d
836
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
837
-	. substr($m, 0, 4)
838
-	. ".$extension";
835
+    return $d
836
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
837
+    . substr($m, 0, 4)
838
+    . ".$extension";
839 839
 }
840 840
 
841 841
 /**
@@ -853,70 +853,70 @@  discard block
 block discarded – undo
853 853
  *      Nom du fichier calculé
854 854
  **/
855 855
 function fichier_copie_locale($source) {
856
-	// Si c'est deja local pas de souci
857
-	if (!tester_url_absolue($source)) {
858
-		if (_DIR_RACINE) {
859
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
860
-		}
861
-
862
-		return $source;
863
-	}
864
-
865
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
866
-	// a deja ete copie en local avec cette extension
867
-	// dans ce cas elle est fiable, pas la peine de requeter en base
868
-	$path_parts = pathinfo($source);
869
-	if (!isset($path_parts['extension'])) {
870
-		$path_parts['extension'] = '';
871
-	}
872
-	$ext = $path_parts ? $path_parts['extension'] : '';
873
-	if (
874
-		$ext
875
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
876
-		and $f = nom_fichier_copie_locale($source, $ext)
877
-		and file_exists(_DIR_RACINE . $f)
878
-	) {
879
-		return $f;
880
-	}
881
-
882
-
883
-	// Si c'est deja dans la table des documents,
884
-	// ramener le nom de sa copie potentielle
885
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
886
-
887
-	if ($ext) {
888
-		return nom_fichier_copie_locale($source, $ext);
889
-	}
890
-
891
-	// voir si l'extension indiquee dans le nom du fichier est ok
892
-	// et si il n'aurait pas deja ete rapatrie
893
-
894
-	$ext = $path_parts ? $path_parts['extension'] : '';
895
-
896
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
897
-		$f = nom_fichier_copie_locale($source, $ext);
898
-		if (file_exists(_DIR_RACINE . $f)) {
899
-			return $f;
900
-		}
901
-	}
902
-
903
-	// Ping  pour voir si son extension est connue et autorisee
904
-	// avec mise en cache du resultat du ping
905
-
906
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
907
-	if (
908
-		!@file_exists($cache)
909
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
910
-		or _request('var_mode') == 'recalcul'
911
-	) {
912
-		$path_parts = recuperer_infos_distantes($source, 0, false);
913
-		ecrire_fichier($cache, serialize($path_parts));
914
-	}
915
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
916
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
917
-		return nom_fichier_copie_locale($source, $ext);
918
-	}
919
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
856
+    // Si c'est deja local pas de souci
857
+    if (!tester_url_absolue($source)) {
858
+        if (_DIR_RACINE) {
859
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
860
+        }
861
+
862
+        return $source;
863
+    }
864
+
865
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
866
+    // a deja ete copie en local avec cette extension
867
+    // dans ce cas elle est fiable, pas la peine de requeter en base
868
+    $path_parts = pathinfo($source);
869
+    if (!isset($path_parts['extension'])) {
870
+        $path_parts['extension'] = '';
871
+    }
872
+    $ext = $path_parts ? $path_parts['extension'] : '';
873
+    if (
874
+        $ext
875
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
876
+        and $f = nom_fichier_copie_locale($source, $ext)
877
+        and file_exists(_DIR_RACINE . $f)
878
+    ) {
879
+        return $f;
880
+    }
881
+
882
+
883
+    // Si c'est deja dans la table des documents,
884
+    // ramener le nom de sa copie potentielle
885
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
886
+
887
+    if ($ext) {
888
+        return nom_fichier_copie_locale($source, $ext);
889
+    }
890
+
891
+    // voir si l'extension indiquee dans le nom du fichier est ok
892
+    // et si il n'aurait pas deja ete rapatrie
893
+
894
+    $ext = $path_parts ? $path_parts['extension'] : '';
895
+
896
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
897
+        $f = nom_fichier_copie_locale($source, $ext);
898
+        if (file_exists(_DIR_RACINE . $f)) {
899
+            return $f;
900
+        }
901
+    }
902
+
903
+    // Ping  pour voir si son extension est connue et autorisee
904
+    // avec mise en cache du resultat du ping
905
+
906
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
907
+    if (
908
+        !@file_exists($cache)
909
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
910
+        or _request('var_mode') == 'recalcul'
911
+    ) {
912
+        $path_parts = recuperer_infos_distantes($source, 0, false);
913
+        ecrire_fichier($cache, serialize($path_parts));
914
+    }
915
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
916
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
917
+        return nom_fichier_copie_locale($source, $ext);
918
+    }
919
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
920 920
 }
921 921
 
922 922
 
@@ -944,97 +944,97 @@  discard block
 block discarded – undo
944 944
  **/
945 945
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
946 946
 
947
-	// pas la peine de perdre son temps
948
-	if (!tester_url_absolue($source)) {
949
-		return false;
950
-	}
951
-
952
-	# charger les alias des types mime
953
-	include_spip('base/typedoc');
954
-
955
-	$a = [];
956
-	$mime_type = '';
957
-	// On va directement charger le debut des images et des fichiers html,
958
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
959
-	// ca echoue l'utilisateur devra les entrer...
960
-	$reponse = recuperer_url($source, ['taille_max' => $max, 'refuser_gz' => true]);
961
-	$headers = $reponse['headers'] ?? '';
962
-	$a['body'] = $reponse['page'] ?? '';
963
-	if ($headers) {
964
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
965
-			return false;
966
-		}
967
-
968
-		$a['extension'] = $extension;
969
-
970
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
971
-			$a['taille'] = intval($regs[1]);
972
-		}
973
-	}
974
-
975
-	// Echec avec HEAD, on tente avec GET
976
-	if (!$a and !$max) {
977
-		spip_log("tenter GET $source", 'distant');
978
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
979
-	}
980
-
981
-	// si on a rien trouve pas la peine d'insister
982
-	if (!$a) {
983
-		return false;
984
-	}
985
-
986
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
987
-	// recharger le document en GET et recuperer des donnees supplementaires...
988
-	include_spip('inc/filtres_images_lib_mini');
989
-	if (
990
-		strpos($mime_type, 'image/') === 0
991
-		and $extension = _image_trouver_extension_depuis_mime($mime_type)
992
-	) {
993
-		if (
994
-			$max == 0
995
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
996
-			and in_array($extension, formats_image_acceptables())
997
-			and $charger_si_petite_image
998
-		) {
999
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1000
-		} else {
1001
-			if ($a['body']) {
1002
-				$a['extension'] = $extension;
1003
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1004
-				ecrire_fichier($a['fichier'], $a['body']);
1005
-				$size_image = @spip_getimagesize($a['fichier']);
1006
-				$a['largeur'] = intval($size_image[0]);
1007
-				$a['hauteur'] = intval($size_image[1]);
1008
-				$a['type_image'] = true;
1009
-			}
1010
-		}
1011
-	}
1012
-
1013
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1014
-	// ce sera mieux que 0x0
1015
-	// Flash is dead!
1016
-	if (
1017
-		$a and isset($a['extension']) and $a['extension'] == 'swf'
1018
-		and empty($a['largeur'])
1019
-	) {
1020
-		$a['largeur'] = 425;
1021
-		$a['hauteur'] = 350;
1022
-	}
1023
-
1024
-	if ($mime_type == 'text/html') {
1025
-		include_spip('inc/filtres');
1026
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1027
-		$page = $page['page'] ?? '';
1028
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1029
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1030
-		}
1031
-		if (!isset($a['taille']) or !$a['taille']) {
1032
-			$a['taille'] = strlen($page); # a peu pres
1033
-		}
1034
-	}
1035
-	$a['mime_type'] = $mime_type;
1036
-
1037
-	return $a;
947
+    // pas la peine de perdre son temps
948
+    if (!tester_url_absolue($source)) {
949
+        return false;
950
+    }
951
+
952
+    # charger les alias des types mime
953
+    include_spip('base/typedoc');
954
+
955
+    $a = [];
956
+    $mime_type = '';
957
+    // On va directement charger le debut des images et des fichiers html,
958
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
959
+    // ca echoue l'utilisateur devra les entrer...
960
+    $reponse = recuperer_url($source, ['taille_max' => $max, 'refuser_gz' => true]);
961
+    $headers = $reponse['headers'] ?? '';
962
+    $a['body'] = $reponse['page'] ?? '';
963
+    if ($headers) {
964
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
965
+            return false;
966
+        }
967
+
968
+        $a['extension'] = $extension;
969
+
970
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
971
+            $a['taille'] = intval($regs[1]);
972
+        }
973
+    }
974
+
975
+    // Echec avec HEAD, on tente avec GET
976
+    if (!$a and !$max) {
977
+        spip_log("tenter GET $source", 'distant');
978
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
979
+    }
980
+
981
+    // si on a rien trouve pas la peine d'insister
982
+    if (!$a) {
983
+        return false;
984
+    }
985
+
986
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
987
+    // recharger le document en GET et recuperer des donnees supplementaires...
988
+    include_spip('inc/filtres_images_lib_mini');
989
+    if (
990
+        strpos($mime_type, 'image/') === 0
991
+        and $extension = _image_trouver_extension_depuis_mime($mime_type)
992
+    ) {
993
+        if (
994
+            $max == 0
995
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
996
+            and in_array($extension, formats_image_acceptables())
997
+            and $charger_si_petite_image
998
+        ) {
999
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1000
+        } else {
1001
+            if ($a['body']) {
1002
+                $a['extension'] = $extension;
1003
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1004
+                ecrire_fichier($a['fichier'], $a['body']);
1005
+                $size_image = @spip_getimagesize($a['fichier']);
1006
+                $a['largeur'] = intval($size_image[0]);
1007
+                $a['hauteur'] = intval($size_image[1]);
1008
+                $a['type_image'] = true;
1009
+            }
1010
+        }
1011
+    }
1012
+
1013
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1014
+    // ce sera mieux que 0x0
1015
+    // Flash is dead!
1016
+    if (
1017
+        $a and isset($a['extension']) and $a['extension'] == 'swf'
1018
+        and empty($a['largeur'])
1019
+    ) {
1020
+        $a['largeur'] = 425;
1021
+        $a['hauteur'] = 350;
1022
+    }
1023
+
1024
+    if ($mime_type == 'text/html') {
1025
+        include_spip('inc/filtres');
1026
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1027
+        $page = $page['page'] ?? '';
1028
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1029
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1030
+        }
1031
+        if (!isset($a['taille']) or !$a['taille']) {
1032
+            $a['taille'] = strlen($page); # a peu pres
1033
+        }
1034
+    }
1035
+    $a['mime_type'] = $mime_type;
1036
+
1037
+    return $a;
1038 1038
 }
1039 1039
 
1040 1040
 /**
@@ -1043,67 +1043,67 @@  discard block
 block discarded – undo
1043 1043
  * @return false|mixed
1044 1044
  */
1045 1045
 function distant_trouver_extension_selon_headers($source, $headers) {
1046
-	if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1047
-		$mime_type = (trim($regs[1]));
1048
-	} else {
1049
-		$mime_type = '';
1050
-	} // inconnu
1051
-
1052
-	// Appliquer les alias
1053
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1054
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1055
-	}
1056
-
1057
-	// Si on a un mime-type insignifiant
1058
-	// text/plain,application/octet-stream ou vide
1059
-	// c'est peut-etre que le serveur ne sait pas
1060
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1061
-	// ou le Content-Disposition: attachment; filename=...
1062
-	$t = null;
1063
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1064
-		if (
1065
-			!$t
1066
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1067
-		) {
1068
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1069
-		}
1070
-		if (
1071
-			!$t
1072
-			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1073
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1074
-		) {
1075
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1076
-		}
1077
-	}
1078
-
1079
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1080
-	if (!$t) {
1081
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1082
-	}
1083
-
1084
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1085
-	// On essaie de nouveau avec l'extension
1086
-	if (
1087
-		!$t
1088
-		and $mime_type != 'text/plain'
1089
-		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1090
-	) {
1091
-		# eviter xxx.3 => 3gp (> SPIP 3)
1092
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1093
-	}
1094
-
1095
-	if ($t) {
1096
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1097
-		return $t['extension'];
1098
-	} else {
1099
-		# par defaut on retombe sur '.bin' si c'est autorise
1100
-		spip_log("mime-type $mime_type inconnu", 'distant');
1101
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1102
-		if (!$t) {
1103
-			return false;
1104
-		}
1105
-		return $t['extension'];
1106
-	}
1046
+    if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1047
+        $mime_type = (trim($regs[1]));
1048
+    } else {
1049
+        $mime_type = '';
1050
+    } // inconnu
1051
+
1052
+    // Appliquer les alias
1053
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1054
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1055
+    }
1056
+
1057
+    // Si on a un mime-type insignifiant
1058
+    // text/plain,application/octet-stream ou vide
1059
+    // c'est peut-etre que le serveur ne sait pas
1060
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1061
+    // ou le Content-Disposition: attachment; filename=...
1062
+    $t = null;
1063
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1064
+        if (
1065
+            !$t
1066
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1067
+        ) {
1068
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1069
+        }
1070
+        if (
1071
+            !$t
1072
+            and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1073
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1074
+        ) {
1075
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1076
+        }
1077
+    }
1078
+
1079
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1080
+    if (!$t) {
1081
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1082
+    }
1083
+
1084
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1085
+    // On essaie de nouveau avec l'extension
1086
+    if (
1087
+        !$t
1088
+        and $mime_type != 'text/plain'
1089
+        and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1090
+    ) {
1091
+        # eviter xxx.3 => 3gp (> SPIP 3)
1092
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1093
+    }
1094
+
1095
+    if ($t) {
1096
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1097
+        return $t['extension'];
1098
+    } else {
1099
+        # par defaut on retombe sur '.bin' si c'est autorise
1100
+        spip_log("mime-type $mime_type inconnu", 'distant');
1101
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1102
+        if (!$t) {
1103
+            return false;
1104
+        }
1105
+        return $t['extension'];
1106
+    }
1107 1107
 }
1108 1108
 
1109 1109
 /**
@@ -1118,46 +1118,46 @@  discard block
 block discarded – undo
1118 1118
  * @return string
1119 1119
  */
1120 1120
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1121
-	if (is_null($http_proxy)) {
1122
-		$http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1123
-	}
1124
-	// rien a faire si pas de proxy :)
1125
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1126
-		return '';
1127
-	}
1128
-
1129
-	if (is_null($http_noproxy)) {
1130
-		$http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1131
-	}
1132
-	// si pas d'exception, on retourne le proxy
1133
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1134
-		return $http_proxy;
1135
-	}
1136
-
1137
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1138
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1139
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1140
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1141
-	$http_noproxy = " $http_noproxy ";
1142
-	$domain = $host;
1143
-	// si le domaine exact www.example.org est dans les exceptions
1144
-	if (strpos($http_noproxy, " $domain ") !== false) {
1145
-		return '';
1146
-	}
1147
-
1148
-	while (strpos($domain, '.') !== false) {
1149
-		$domain = explode('.', $domain);
1150
-		array_shift($domain);
1151
-		$domain = implode('.', $domain);
1152
-
1153
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1154
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1155
-			return '';
1156
-		}
1157
-	}
1158
-
1159
-	// ok c'est pas une exception
1160
-	return $http_proxy;
1121
+    if (is_null($http_proxy)) {
1122
+        $http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1123
+    }
1124
+    // rien a faire si pas de proxy :)
1125
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1126
+        return '';
1127
+    }
1128
+
1129
+    if (is_null($http_noproxy)) {
1130
+        $http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1131
+    }
1132
+    // si pas d'exception, on retourne le proxy
1133
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1134
+        return $http_proxy;
1135
+    }
1136
+
1137
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1138
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1139
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1140
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1141
+    $http_noproxy = " $http_noproxy ";
1142
+    $domain = $host;
1143
+    // si le domaine exact www.example.org est dans les exceptions
1144
+    if (strpos($http_noproxy, " $domain ") !== false) {
1145
+        return '';
1146
+    }
1147
+
1148
+    while (strpos($domain, '.') !== false) {
1149
+        $domain = explode('.', $domain);
1150
+        array_shift($domain);
1151
+        $domain = implode('.', $domain);
1152
+
1153
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1154
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1155
+            return '';
1156
+        }
1157
+    }
1158
+
1159
+    // ok c'est pas une exception
1160
+    return $http_proxy;
1161 1161
 }
1162 1162
 
1163 1163
 
@@ -1180,59 +1180,59 @@  discard block
 block discarded – undo
1180 1180
  * @return array
1181 1181
  */
1182 1182
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1183
-	$user = $via_proxy = $proxy_user = '';
1184
-	$fopen = false;
1185
-
1186
-	$t = @parse_url($url);
1187
-	$host = $t['host'];
1188
-	if ($t['scheme'] == 'http') {
1189
-		$scheme = 'http';
1190
-		$noproxy = '';
1191
-	} elseif ($t['scheme'] == 'https') {
1192
-		$scheme = 'ssl';
1193
-		$noproxy = 'ssl://';
1194
-		if (!isset($t['port']) || !($port = $t['port'])) {
1195
-			$t['port'] = 443;
1196
-		}
1197
-	} else {
1198
-		$scheme = $t['scheme'];
1199
-		$noproxy = $scheme . '://';
1200
-	}
1201
-	if (isset($t['user'])) {
1202
-		$user = [$t['user'], $t['pass']];
1203
-	}
1204
-
1205
-	if (!isset($t['port']) || !($port = $t['port'])) {
1206
-		$port = 80;
1207
-	}
1208
-	if (!isset($t['path']) || !($path = $t['path'])) {
1209
-		$path = '/';
1210
-	}
1211
-
1212
-	if (!empty($t['query'])) {
1213
-		$path .= '?' . $t['query'];
1214
-	}
1215
-
1216
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1217
-	if (!$f or !is_resource($f)) {
1218
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1219
-		// ce qui correspond a $f===110
1220
-		if (
1221
-			$f !== 110
1222
-			and !need_proxy($host)
1223
-			and !_request('tester_proxy')
1224
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1225
-		) {
1226
-			$f = @fopen($url, 'rb');
1227
-			spip_log("connexion vers $url par simple fopen", 'distant');
1228
-			$fopen = true;
1229
-		} else {
1230
-			// echec total
1231
-			$f = false;
1232
-		}
1233
-	}
1234
-
1235
-	return [$f, $fopen];
1183
+    $user = $via_proxy = $proxy_user = '';
1184
+    $fopen = false;
1185
+
1186
+    $t = @parse_url($url);
1187
+    $host = $t['host'];
1188
+    if ($t['scheme'] == 'http') {
1189
+        $scheme = 'http';
1190
+        $noproxy = '';
1191
+    } elseif ($t['scheme'] == 'https') {
1192
+        $scheme = 'ssl';
1193
+        $noproxy = 'ssl://';
1194
+        if (!isset($t['port']) || !($port = $t['port'])) {
1195
+            $t['port'] = 443;
1196
+        }
1197
+    } else {
1198
+        $scheme = $t['scheme'];
1199
+        $noproxy = $scheme . '://';
1200
+    }
1201
+    if (isset($t['user'])) {
1202
+        $user = [$t['user'], $t['pass']];
1203
+    }
1204
+
1205
+    if (!isset($t['port']) || !($port = $t['port'])) {
1206
+        $port = 80;
1207
+    }
1208
+    if (!isset($t['path']) || !($path = $t['path'])) {
1209
+        $path = '/';
1210
+    }
1211
+
1212
+    if (!empty($t['query'])) {
1213
+        $path .= '?' . $t['query'];
1214
+    }
1215
+
1216
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1217
+    if (!$f or !is_resource($f)) {
1218
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1219
+        // ce qui correspond a $f===110
1220
+        if (
1221
+            $f !== 110
1222
+            and !need_proxy($host)
1223
+            and !_request('tester_proxy')
1224
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1225
+        ) {
1226
+            $f = @fopen($url, 'rb');
1227
+            spip_log("connexion vers $url par simple fopen", 'distant');
1228
+            $fopen = true;
1229
+        } else {
1230
+            // echec total
1231
+            $f = false;
1232
+        }
1233
+    }
1234
+
1235
+    return [$f, $fopen];
1236 1236
 }
1237 1237
 
1238 1238
 /**
@@ -1267,125 +1267,125 @@  discard block
 block discarded – undo
1267 1267
  *   resource socket vers l'url demandee
1268 1268
  */
1269 1269
 function lance_requete(
1270
-	$method,
1271
-	$scheme,
1272
-	$user,
1273
-	$host,
1274
-	$path,
1275
-	$port,
1276
-	$noproxy,
1277
-	$refuse_gz = false,
1278
-	$referer = '',
1279
-	$datas = '',
1280
-	$vers = 'HTTP/1.0',
1281
-	$date = ''
1270
+    $method,
1271
+    $scheme,
1272
+    $user,
1273
+    $host,
1274
+    $path,
1275
+    $port,
1276
+    $noproxy,
1277
+    $refuse_gz = false,
1278
+    $referer = '',
1279
+    $datas = '',
1280
+    $vers = 'HTTP/1.0',
1281
+    $date = ''
1282 1282
 ) {
1283 1283
 
1284
-	$proxy_user = '';
1285
-	$http_proxy = need_proxy($host);
1286
-	if ($user) {
1287
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1288
-	}
1289
-
1290
-	$connect = '';
1291
-	if ($http_proxy) {
1292
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1293
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1294
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1295
-				. "Host: $path_host\r\n"
1296
-				. "Proxy-Connection: Keep-Alive\r\n";
1297
-		} else {
1298
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1299
-				. (!$user ? '' : "$user@")
1300
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1301
-		}
1302
-		$t2 = @parse_url($http_proxy);
1303
-		$first_host = $t2['host'];
1304
-		if (!($port = $t2['port'])) {
1305
-			$port = 80;
1306
-		}
1307
-		if ($t2['user']) {
1308
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1309
-		}
1310
-	} else {
1311
-		$first_host = $noproxy . $host;
1312
-	}
1313
-
1314
-	if ($connect) {
1315
-		$streamContext = stream_context_create([
1316
-			'ssl' => [
1317
-				'verify_peer' => false,
1318
-				'allow_self_signed' => true,
1319
-				'SNI_enabled' => true,
1320
-				'peer_name' => $host,
1321
-			]
1322
-		]);
1323
-		$f = @stream_socket_client(
1324
-			"tcp://$first_host:$port",
1325
-			$errno,
1326
-			$errstr,
1327
-			_INC_DISTANT_CONNECT_TIMEOUT,
1328
-			STREAM_CLIENT_CONNECT,
1329
-			$streamContext
1330
-		);
1331
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1332
-		if (!$f) {
1333
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1334
-			return $errno;
1335
-		}
1336
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1337
-
1338
-		fputs($f, $connect);
1339
-		fputs($f, "\r\n");
1340
-		$res = fread($f, 1024);
1341
-		if (
1342
-			!$res
1343
-			or !count($res = explode(' ', $res))
1344
-			or $res[1] !== '200'
1345
-		) {
1346
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1347
-			fclose($f);
1348
-
1349
-			return false;
1350
-		}
1351
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1352
-		stream_set_blocking($f, true);
1353
-		// envoyer le handshake
1354
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1355
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1356
-	} else {
1357
-		$ntry = 3;
1358
-		do {
1359
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1360
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1361
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1362
-		if (!$f) {
1363
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1364
-
1365
-			return $errno;
1366
-		}
1367
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1368
-	}
1369
-
1370
-	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1371
-
1372
-	$host_port = $host;
1373
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1374
-		$host_port .= ":$port";
1375
-	}
1376
-	$req = "$method $path $vers\r\n"
1377
-		. "Host: $host_port\r\n"
1378
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1379
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1380
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1381
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1382
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1383
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1384
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1284
+    $proxy_user = '';
1285
+    $http_proxy = need_proxy($host);
1286
+    if ($user) {
1287
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1288
+    }
1289
+
1290
+    $connect = '';
1291
+    if ($http_proxy) {
1292
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1293
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1294
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1295
+                . "Host: $path_host\r\n"
1296
+                . "Proxy-Connection: Keep-Alive\r\n";
1297
+        } else {
1298
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1299
+                . (!$user ? '' : "$user@")
1300
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1301
+        }
1302
+        $t2 = @parse_url($http_proxy);
1303
+        $first_host = $t2['host'];
1304
+        if (!($port = $t2['port'])) {
1305
+            $port = 80;
1306
+        }
1307
+        if ($t2['user']) {
1308
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1309
+        }
1310
+    } else {
1311
+        $first_host = $noproxy . $host;
1312
+    }
1313
+
1314
+    if ($connect) {
1315
+        $streamContext = stream_context_create([
1316
+            'ssl' => [
1317
+                'verify_peer' => false,
1318
+                'allow_self_signed' => true,
1319
+                'SNI_enabled' => true,
1320
+                'peer_name' => $host,
1321
+            ]
1322
+        ]);
1323
+        $f = @stream_socket_client(
1324
+            "tcp://$first_host:$port",
1325
+            $errno,
1326
+            $errstr,
1327
+            _INC_DISTANT_CONNECT_TIMEOUT,
1328
+            STREAM_CLIENT_CONNECT,
1329
+            $streamContext
1330
+        );
1331
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1332
+        if (!$f) {
1333
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1334
+            return $errno;
1335
+        }
1336
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1337
+
1338
+        fputs($f, $connect);
1339
+        fputs($f, "\r\n");
1340
+        $res = fread($f, 1024);
1341
+        if (
1342
+            !$res
1343
+            or !count($res = explode(' ', $res))
1344
+            or $res[1] !== '200'
1345
+        ) {
1346
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1347
+            fclose($f);
1348
+
1349
+            return false;
1350
+        }
1351
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1352
+        stream_set_blocking($f, true);
1353
+        // envoyer le handshake
1354
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1355
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1356
+    } else {
1357
+        $ntry = 3;
1358
+        do {
1359
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1360
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1361
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1362
+        if (!$f) {
1363
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1364
+
1365
+            return $errno;
1366
+        }
1367
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1368
+    }
1369
+
1370
+    $site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1371
+
1372
+    $host_port = $host;
1373
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1374
+        $host_port .= ":$port";
1375
+    }
1376
+    $req = "$method $path $vers\r\n"
1377
+        . "Host: $host_port\r\n"
1378
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1379
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1380
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1381
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1382
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1383
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1384
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1385 1385
 
1386 1386
 #	spip_log("Requete\n$req", 'distant');
1387
-	fputs($f, $req);
1388
-	fputs($f, $datas ? $datas : "\r\n");
1387
+    fputs($f, $req);
1388
+    fputs($f, $datas ? $datas : "\r\n");
1389 1389
 
1390
-	return $f;
1390
+    return $f;
1391 1391
 }
Please login to merge, or discard this patch.