Completed
Push — master ( 0ba822...452720 )
by cam
02:09
created
ecrire/inc/distant.php 1 patch
Indentation   +1131 added lines, -1131 removed lines patch added patch discarded remove patch
@@ -17,32 +17,32 @@  discard block
 block discarded – undo
17 17
  * @package SPIP\Core\Distant
18 18
  **/
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
24
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
25 25
 }
26 26
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
27
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28 28
 }
29 29
 if (!defined('_INC_DISTANT_USER_AGENT')) {
30
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31 31
 }
32 32
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
33
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
33
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
34 34
 }
35 35
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
36
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37 37
 }
38 38
 
39 39
 define('_REGEXP_COPIE_LOCALE', ',' 	.
40
-	preg_replace(
41
-		'@^https?:@',
42
-		'https?:',
43
-		($GLOBALS['meta']['adresse_site'] ?? '')
44
-	)
45
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
40
+    preg_replace(
41
+        '@^https?:@',
42
+        'https?:',
43
+        ($GLOBALS['meta']['adresse_site'] ?? '')
44
+    )
45
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
46 46
 
47 47
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
48 48
 
@@ -71,105 +71,105 @@  discard block
 block discarded – undo
71 71
  */
72 72
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
73 73
 
74
-	// si c'est la protection de soi-meme, retourner le path
75
-	if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
-		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
-
78
-		return @file_exists($source) ? $source : false;
79
-	}
80
-
81
-	if (is_null($local)) {
82
-		$local = fichier_copie_locale($source);
83
-	} else {
84
-		if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
-			$local = substr($local, strlen((string) _DIR_RACINE));
86
-		}
87
-	}
88
-
89
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
-	// par exemple un fichier qui ne figure pas dans nos documents ;
91
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
-	if (!$local) {
93
-		return false;
94
-	}
95
-
96
-	$localrac = _DIR_RACINE . $local;
97
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
98
-
99
-	// test d'existence du fichier
100
-	if ($mode === 'test') {
101
-		return $t ? $local : '';
102
-	}
103
-
104
-	// sinon voir si on doit/peut le telecharger
105
-	if ($local === $source || !tester_url_absolue($source)) {
106
-		return $t ? $local : '';
107
-	}
108
-
109
-	if ($mode === 'modif' || !$t) {
110
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
-		// et des eventuelles recuperations concurantes
112
-		include_spip('inc/acces');
113
-		if (!$taille_max) {
114
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
115
-		}
116
-		$localrac_tmp = $localrac . '.tmp';
117
-		$res = recuperer_url(
118
-			$source,
119
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
-		);
121
-
122
-		if (!$res || !$res['length'] && $res['status'] != 304) {
123
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
-			@unlink($localrac_tmp);
125
-		} else {
126
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
-		}
128
-		if (!$res || !$res['length']) {
129
-			// si $t c'est sans doute juste un not-modified-since
130
-			return $t ? $local : false;
131
-		}
132
-
133
-		// si option valider url, verifions que l'URL finale est acceptable
134
-		if (
135
-			$callback_valider_url
136
-			&& is_callable($callback_valider_url)
137
-			&& !$callback_valider_url($res['url'])
138
-		) {
139
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
-			@unlink($localrac_tmp);
141
-			return $t ? $local : false;
142
-		}
143
-
144
-		// on peut renommer le fichier tmp
145
-		@rename($localrac_tmp, $localrac);
146
-
147
-		// si on retrouve l'extension
148
-		if (
149
-			!empty($res['headers'])
150
-			&& ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
151
-			&& ($sanitizer = charger_fonction($extension, 'sanitizer', true))
152
-		) {
153
-			$sanitizer($localrac);
154
-		}
155
-
156
-		// pour une eventuelle indexation
157
-		pipeline(
158
-			'post_edition',
159
-			[
160
-				'args' => [
161
-					'operation' => 'copie_locale',
162
-					'source' => $source,
163
-					'fichier' => $local,
164
-					'http_res' => $res['length'],
165
-					'url' => $res['url'],
166
-				],
167
-				'data' => null
168
-			]
169
-		);
170
-	}
171
-
172
-	return $local;
74
+    // si c'est la protection de soi-meme, retourner le path
75
+    if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
+        $source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
+
78
+        return @file_exists($source) ? $source : false;
79
+    }
80
+
81
+    if (is_null($local)) {
82
+        $local = fichier_copie_locale($source);
83
+    } else {
84
+        if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
+            $local = substr($local, strlen((string) _DIR_RACINE));
86
+        }
87
+    }
88
+
89
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
+    // par exemple un fichier qui ne figure pas dans nos documents ;
91
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
+    if (!$local) {
93
+        return false;
94
+    }
95
+
96
+    $localrac = _DIR_RACINE . $local;
97
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
98
+
99
+    // test d'existence du fichier
100
+    if ($mode === 'test') {
101
+        return $t ? $local : '';
102
+    }
103
+
104
+    // sinon voir si on doit/peut le telecharger
105
+    if ($local === $source || !tester_url_absolue($source)) {
106
+        return $t ? $local : '';
107
+    }
108
+
109
+    if ($mode === 'modif' || !$t) {
110
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
+        // et des eventuelles recuperations concurantes
112
+        include_spip('inc/acces');
113
+        if (!$taille_max) {
114
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
115
+        }
116
+        $localrac_tmp = $localrac . '.tmp';
117
+        $res = recuperer_url(
118
+            $source,
119
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
+        );
121
+
122
+        if (!$res || !$res['length'] && $res['status'] != 304) {
123
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
+            @unlink($localrac_tmp);
125
+        } else {
126
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
+        }
128
+        if (!$res || !$res['length']) {
129
+            // si $t c'est sans doute juste un not-modified-since
130
+            return $t ? $local : false;
131
+        }
132
+
133
+        // si option valider url, verifions que l'URL finale est acceptable
134
+        if (
135
+            $callback_valider_url
136
+            && is_callable($callback_valider_url)
137
+            && !$callback_valider_url($res['url'])
138
+        ) {
139
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
+            @unlink($localrac_tmp);
141
+            return $t ? $local : false;
142
+        }
143
+
144
+        // on peut renommer le fichier tmp
145
+        @rename($localrac_tmp, $localrac);
146
+
147
+        // si on retrouve l'extension
148
+        if (
149
+            !empty($res['headers'])
150
+            && ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
151
+            && ($sanitizer = charger_fonction($extension, 'sanitizer', true))
152
+        ) {
153
+            $sanitizer($localrac);
154
+        }
155
+
156
+        // pour une eventuelle indexation
157
+        pipeline(
158
+            'post_edition',
159
+            [
160
+                'args' => [
161
+                    'operation' => 'copie_locale',
162
+                    'source' => $source,
163
+                    'fichier' => $local,
164
+                    'http_res' => $res['length'],
165
+                    'url' => $res['url'],
166
+                ],
167
+                'data' => null
168
+            ]
169
+        );
170
+    }
171
+
172
+    return $local;
173 173
 }
174 174
 
175 175
 /**
@@ -184,97 +184,97 @@  discard block
 block discarded – undo
184 184
  *   url ou false en cas d'echec
185 185
  */
186 186
 function valider_url_distante($url, $known_hosts = []) {
187
-	if (!function_exists('protocole_verifier')) {
188
-		include_spip('inc/filtres_mini');
189
-	}
190
-
191
-	if (!protocole_verifier($url, ['http', 'https'])) {
192
-		return false;
193
-	}
194
-
195
-	$parsed_url = parse_url($url);
196
-	if (!$parsed_url || empty($parsed_url['host'])) {
197
-		return false;
198
-	}
199
-
200
-	if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
201
-		return false;
202
-	}
203
-
204
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
205
-		return false;
206
-	}
207
-
208
-	if (!is_array($known_hosts)) {
209
-		$known_hosts = [$known_hosts];
210
-	}
211
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
212
-	$known_hosts[] = url_de_base();
213
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
214
-
215
-	$is_known_host = false;
216
-	foreach ($known_hosts as $known_host) {
217
-		$parse_known = parse_url((string) $known_host);
218
-		if (
219
-			$parse_known
220
-			&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
221
-		) {
222
-			$is_known_host = true;
223
-			break;
224
-		}
225
-	}
226
-
227
-	if (!$is_known_host) {
228
-		$host = trim($parsed_url['host'], '.');
229
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
230
-			$ip = gethostbyname($host);
231
-			if ($ip === $host) {
232
-				// Error condition for gethostbyname()
233
-				$ip = false;
234
-			}
235
-			if ($records = dns_get_record($host)) {
236
-				foreach ($records as $record) {
237
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
238
-					// se fasse sur la meme IP
239
-					if ($record['ttl'] < 10) {
240
-						$ip = false;
241
-						break;
242
-					}
243
-				}
244
-			}
245
-			else {
246
-				$ip = false;
247
-			}
248
-		}
249
-		if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250
-			return false;
251
-		}
252
-	}
253
-
254
-	if (empty($parsed_url['port'])) {
255
-		return $url;
256
-	}
257
-
258
-	$port = $parsed_url['port'];
259
-	if ($port === 80 || $port === 443 || $port === 8080) {
260
-		return $url;
261
-	}
262
-
263
-	if ($is_known_host) {
264
-		foreach ($known_hosts as $known_host) {
265
-			$parse_known = parse_url((string) $known_host);
266
-			if (
267
-				$parse_known
268
-				&& !empty($parse_known['port'])
269
-				&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
270
-				&& $parse_known['port'] == $port
271
-			) {
272
-				return $url;
273
-			}
274
-		}
275
-	}
276
-
277
-	return false;
187
+    if (!function_exists('protocole_verifier')) {
188
+        include_spip('inc/filtres_mini');
189
+    }
190
+
191
+    if (!protocole_verifier($url, ['http', 'https'])) {
192
+        return false;
193
+    }
194
+
195
+    $parsed_url = parse_url($url);
196
+    if (!$parsed_url || empty($parsed_url['host'])) {
197
+        return false;
198
+    }
199
+
200
+    if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
201
+        return false;
202
+    }
203
+
204
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
205
+        return false;
206
+    }
207
+
208
+    if (!is_array($known_hosts)) {
209
+        $known_hosts = [$known_hosts];
210
+    }
211
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
212
+    $known_hosts[] = url_de_base();
213
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
214
+
215
+    $is_known_host = false;
216
+    foreach ($known_hosts as $known_host) {
217
+        $parse_known = parse_url((string) $known_host);
218
+        if (
219
+            $parse_known
220
+            && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
221
+        ) {
222
+            $is_known_host = true;
223
+            break;
224
+        }
225
+    }
226
+
227
+    if (!$is_known_host) {
228
+        $host = trim($parsed_url['host'], '.');
229
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
230
+            $ip = gethostbyname($host);
231
+            if ($ip === $host) {
232
+                // Error condition for gethostbyname()
233
+                $ip = false;
234
+            }
235
+            if ($records = dns_get_record($host)) {
236
+                foreach ($records as $record) {
237
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
238
+                    // se fasse sur la meme IP
239
+                    if ($record['ttl'] < 10) {
240
+                        $ip = false;
241
+                        break;
242
+                    }
243
+                }
244
+            }
245
+            else {
246
+                $ip = false;
247
+            }
248
+        }
249
+        if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250
+            return false;
251
+        }
252
+    }
253
+
254
+    if (empty($parsed_url['port'])) {
255
+        return $url;
256
+    }
257
+
258
+    $port = $parsed_url['port'];
259
+    if ($port === 80 || $port === 443 || $port === 8080) {
260
+        return $url;
261
+    }
262
+
263
+    if ($is_known_host) {
264
+        foreach ($known_hosts as $known_host) {
265
+            $parse_known = parse_url((string) $known_host);
266
+            if (
267
+                $parse_known
268
+                && !empty($parse_known['port'])
269
+                && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
270
+                && $parse_known['port'] == $port
271
+            ) {
272
+                return $url;
273
+            }
274
+        }
275
+    }
276
+
277
+    return false;
278 278
 }
279 279
 
280 280
 /**
@@ -294,87 +294,87 @@  discard block
 block discarded – undo
294 294
  */
295 295
 function prepare_donnees_post($donnees, $boundary = '') {
296 296
 
297
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
298
-	// pour un appel soap par exemple
299
-	// l'entete est separe des donnees par un double retour a la ligne
300
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
301
-	$chaine = '';
302
-	if (is_string($donnees) && strlen($donnees)) {
303
-		$entete = '';
304
-		// on repasse tous les \r\n et \r en simples \n
305
-		$donnees = str_replace("\r\n", "\n", $donnees);
306
-		$donnees = str_replace("\r", "\n", $donnees);
307
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
308
-		$p = strpos($donnees, "\n\n");
309
-		if ($p !== false) {
310
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
311
-			$donnees = substr($donnees, $p + 2);
312
-		}
313
-		$chaine = str_replace("\n", "\r\n", $donnees);
314
-	} else {
315
-		/* boundary automatique */
316
-		// Si on a plus de 500 octects de donnees, on "boundarise"
317
-		if ($boundary === '') {
318
-			$taille = 0;
319
-			foreach ($donnees as $cle => $valeur) {
320
-				if (is_array($valeur)) {
321
-					foreach ($valeur as $val2) {
322
-						$taille += strlen((string) $val2);
323
-					}
324
-				} else {
325
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
326
-					$taille += strlen((string) $valeur);
327
-				}
328
-			}
329
-			if ($taille > 500) {
330
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
331
-			}
332
-		}
333
-
334
-		if (is_string($boundary) && strlen($boundary)) {
335
-			// fabrique une chaine HTTP pour un POST avec boundary
336
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
337
-			if (is_array($donnees)) {
338
-				foreach ($donnees as $cle => $valeur) {
339
-					if (is_array($valeur)) {
340
-						foreach ($valeur as $val2) {
341
-							$chaine .= "\r\n--$boundary\r\n";
342
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
343
-							$chaine .= "\r\n";
344
-							$chaine .= $val2;
345
-						}
346
-					} else {
347
-						$chaine .= "\r\n--$boundary\r\n";
348
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
349
-						$chaine .= "\r\n";
350
-						$chaine .= $valeur;
351
-					}
352
-				}
353
-				$chaine .= "\r\n--$boundary\r\n";
354
-			}
355
-		} else {
356
-			// fabrique une chaine HTTP simple pour un POST
357
-			$entete = "Content-Type: application/x-www-form-urlencoded\r\n";
358
-			if (is_array($donnees)) {
359
-				$chaines = [];
360
-				foreach ($donnees as $cle => $valeur) {
361
-					if (is_array($valeur)) {
362
-						foreach ($valeur as $val2) {
363
-							$chaines[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
364
-						}
365
-					} else {
366
-						$chaines[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
367
-					}
368
-				}
369
-				$chaine = implode('&', $chaines);
370
-				unset($chaines);
371
-			} else {
372
-				$chaine = $donnees;
373
-			}
374
-		}
375
-	}
376
-
377
-	return [$entete, $chaine];
297
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
298
+    // pour un appel soap par exemple
299
+    // l'entete est separe des donnees par un double retour a la ligne
300
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
301
+    $chaine = '';
302
+    if (is_string($donnees) && strlen($donnees)) {
303
+        $entete = '';
304
+        // on repasse tous les \r\n et \r en simples \n
305
+        $donnees = str_replace("\r\n", "\n", $donnees);
306
+        $donnees = str_replace("\r", "\n", $donnees);
307
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
308
+        $p = strpos($donnees, "\n\n");
309
+        if ($p !== false) {
310
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
311
+            $donnees = substr($donnees, $p + 2);
312
+        }
313
+        $chaine = str_replace("\n", "\r\n", $donnees);
314
+    } else {
315
+        /* boundary automatique */
316
+        // Si on a plus de 500 octects de donnees, on "boundarise"
317
+        if ($boundary === '') {
318
+            $taille = 0;
319
+            foreach ($donnees as $cle => $valeur) {
320
+                if (is_array($valeur)) {
321
+                    foreach ($valeur as $val2) {
322
+                        $taille += strlen((string) $val2);
323
+                    }
324
+                } else {
325
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
326
+                    $taille += strlen((string) $valeur);
327
+                }
328
+            }
329
+            if ($taille > 500) {
330
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
331
+            }
332
+        }
333
+
334
+        if (is_string($boundary) && strlen($boundary)) {
335
+            // fabrique une chaine HTTP pour un POST avec boundary
336
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
337
+            if (is_array($donnees)) {
338
+                foreach ($donnees as $cle => $valeur) {
339
+                    if (is_array($valeur)) {
340
+                        foreach ($valeur as $val2) {
341
+                            $chaine .= "\r\n--$boundary\r\n";
342
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
343
+                            $chaine .= "\r\n";
344
+                            $chaine .= $val2;
345
+                        }
346
+                    } else {
347
+                        $chaine .= "\r\n--$boundary\r\n";
348
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
349
+                        $chaine .= "\r\n";
350
+                        $chaine .= $valeur;
351
+                    }
352
+                }
353
+                $chaine .= "\r\n--$boundary\r\n";
354
+            }
355
+        } else {
356
+            // fabrique une chaine HTTP simple pour un POST
357
+            $entete = "Content-Type: application/x-www-form-urlencoded\r\n";
358
+            if (is_array($donnees)) {
359
+                $chaines = [];
360
+                foreach ($donnees as $cle => $valeur) {
361
+                    if (is_array($valeur)) {
362
+                        foreach ($valeur as $val2) {
363
+                            $chaines[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
364
+                        }
365
+                    } else {
366
+                        $chaines[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
367
+                    }
368
+                }
369
+                $chaine = implode('&', $chaines);
370
+                unset($chaines);
371
+            } else {
372
+                $chaine = $donnees;
373
+            }
374
+        }
375
+    }
376
+
377
+    return [$entete, $chaine];
378 378
 }
379 379
 
380 380
 /**
@@ -385,19 +385,19 @@  discard block
 block discarded – undo
385 385
  */
386 386
 function url_to_ascii($url_idn) {
387 387
 
388
-	if ($parts = parse_url($url_idn)) {
389
-		$host = $parts['host'];
390
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
-			$converter = new ToIdn();
392
-			$host_ascii = $converter->convert($host);
393
-			$url_idn = explode($host, $url_idn, 2);
394
-			$url_idn = implode($host_ascii, $url_idn);
395
-		}
396
-		// et on urlencode les char utf si besoin dans le path
397
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
-	}
399
-
400
-	return $url_idn;
388
+    if ($parts = parse_url($url_idn)) {
389
+        $host = $parts['host'];
390
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
+            $converter = new ToIdn();
392
+            $host_ascii = $converter->convert($host);
393
+            $url_idn = explode($host, $url_idn, 2);
394
+            $url_idn = implode($host_ascii, $url_idn);
395
+        }
396
+        // et on urlencode les char utf si besoin dans le path
397
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
+    }
399
+
400
+    return $url_idn;
401 401
 }
402 402
 
403 403
 /**
@@ -439,228 +439,228 @@  discard block
 block discarded – undo
439 439
  *     string file : nom du fichier si enregistre dans un fichier
440 440
  */
441 441
 function recuperer_url($url, $options = []) {
442
-	// Conserve la mémoire de la méthode fournit éventuellement
443
-	$methode_demandee = $options['methode'] ?? '';
444
-	$default = [
445
-		'transcoder' => false,
446
-		'methode' => 'GET',
447
-		'taille_max' => null,
448
-		'headers' => [],
449
-		'datas' => '',
450
-		'boundary' => '',
451
-		'refuser_gz' => false,
452
-		'if_modified_since' => '',
453
-		'uri_referer' => '',
454
-		'file' => '',
455
-		'follow_location' => 10,
456
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
457
-	];
458
-	$options = array_merge($default, $options);
459
-	// copier directement dans un fichier ?
460
-	$copy = $options['file'];
461
-
462
-	if ($options['methode'] == 'HEAD') {
463
-		$options['taille_max'] = 0;
464
-	}
465
-	if (is_null($options['taille_max'])) {
466
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
467
-	}
468
-
469
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
470
-
471
-	// Ajout des en-têtes spécifiques si besoin
472
-	$formatted_data = '';
473
-	if (!empty($options['headers'])) {
474
-		foreach ($options['headers'] as $champ => $valeur) {
475
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
476
-		}
477
-	}
478
-
479
-	if (!empty($options['datas'])) {
480
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
481
-		$head .= $formatted_data;
482
-		if (stripos($head, 'Content-Length:') === false) {
483
-			$head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
484
-		}
485
-		$formatted_data = $head . "\r\n" . $postdata;
486
-		if (
487
-			strlen((string) $postdata) && !$methode_demandee
488
-		) {
489
-			$options['methode'] = 'POST';
490
-		}
491
-	} elseif ($formatted_data) {
492
-		$formatted_data .= "\r\n";
493
-	}
494
-
495
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
496
-	$url = preg_replace(',^feed://,i', 'http://', $url);
497
-	if (!tester_url_absolue($url)) {
498
-		$url = 'http://' . $url;
499
-	} elseif (str_starts_with($url, '//')) {
500
-		$url = 'http:' . $url;
501
-	}
502
-
503
-	$url = url_to_ascii($url);
504
-
505
-	$result = [
506
-		'status' => 0,
507
-		'headers' => '',
508
-		'page' => '',
509
-		'length' => 0,
510
-		'last_modified' => '',
511
-		'location' => '',
512
-		'url' => $url
513
-	];
514
-
515
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
516
-	$refuser_gz = ($options['refuser_gz'] || $copy);
517
-
518
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
519
-	[$handle, $fopen] = init_http(
520
-		$options['methode'],
521
-		$url,
522
-		$refuser_gz,
523
-		$options['uri_referer'],
524
-		$formatted_data,
525
-		$options['version_http'],
526
-		$options['if_modified_since']
527
-	);
528
-	if (!$handle) {
529
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
530
-
531
-		return false;
532
-	}
533
-
534
-	// Sauf en fopen, envoyer le flux d'entree
535
-	// et recuperer les en-tetes de reponses
536
-	if (!$fopen) {
537
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
538
-		if (!$res) {
539
-			fclose($handle);
540
-			$t = @parse_url($url);
541
-			$host = $t['host'];
542
-			// Chinoisierie inexplicable pour contrer
543
-			// les actions liberticides de l'empire du milieu
544
-			if (
545
-				!need_proxy($host)
546
-				&& ($res = @file_get_contents($url))
547
-			) {
548
-				$result['length'] = strlen($res);
549
-				if ($copy) {
550
-					ecrire_fichier($copy, $res);
551
-					$result['file'] = $copy;
552
-				} else {
553
-					$result['page'] = $res;
554
-				}
555
-				$res = [
556
-					'status' => 200,
557
-				];
558
-			} else {
559
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
560
-				return false;
561
-			}
562
-		} elseif ($res['location'] && $options['follow_location']) {
563
-			$options['follow_location']--;
564
-			fclose($handle);
565
-			include_spip('inc/filtres');
566
-			$url = suivre_lien($url, $res['location']);
567
-
568
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
569
-			if (
570
-				$options['methode'] !== 'GET'
571
-				&& (empty($res['status']) || !in_array($res['status'], [307, 308]))
572
-			) {
573
-				$options['methode'] = 'GET';
574
-				$options['datas'] = '';
575
-			}
576
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
577
-
578
-			return recuperer_url($url, $options);
579
-		} elseif ($res['status'] !== 200) {
580
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
581
-		}
582
-		$result['status'] = $res['status'];
583
-		if (isset($res['headers'])) {
584
-			$result['headers'] = $res['headers'];
585
-		}
586
-		if (isset($res['last_modified'])) {
587
-			$result['last_modified'] = $res['last_modified'];
588
-		}
589
-		if (isset($res['location'])) {
590
-			$result['location'] = $res['location'];
591
-		}
592
-		if (isset($res['content_length'])) {
593
-			$result['content_length'] = $res['content_length'];
594
-		}
595
-	}
596
-
597
-	// on ne veut que les entetes
598
-	if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
600
-		return $result;
601
-	}
602
-
603
-
604
-	// s'il faut deballer, le faire via un fichier temporaire
605
-	// sinon la memoire explose pour les gros flux
606
-
607
-	$gz = false;
608
-	if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
609
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
-	}
611
-
612
-	// si on n'a pas deja récupéré le contenu par une methode detournée
613
-	if (!$result['length']) {
614
-		$taille_max = $options['taille_max'];
615
-		if (isset($result['content_length'])
616
-		  && !empty($result['content_length'])
617
-		  && ($result['content_length'] < $taille_max)) {
618
-			$taille_max = $result['content_length'];
619
-		}
620
-		$res = recuperer_body($handle, $taille_max, $gz ?: $copy);
621
-		fclose($handle);
622
-		if ($copy) {
623
-			$result['length'] = $res;
624
-			$result['file'] = $copy;
625
-		} elseif ($res) {
626
-			$result['page'] = &$res;
627
-			$result['length'] = strlen($result['page']);
628
-		}
629
-		if (!$result['status']) {
630
-			$result['status'] = 200; // on a reussi, donc !
631
-		}
632
-	}
633
-	if (!$result['page']) {
634
-		return $result;
635
-	}
636
-
637
-	// Decompresser au besoin
638
-	if ($gz) {
639
-		$result['page'] = implode('', gzfile($gz));
640
-		$result['length'] = strlen($result['page']);
641
-		// et annuler le content-length qui correspond à la version gzip
642
-		if (isset($result['content_length'])) {
643
-			unset($result['content_length']);
644
-		}
645
-		supprimer_fichier($gz);
646
-	}
647
-
648
-	// Faut-il l'importer dans notre charset local ?
649
-	if ($options['transcoder']) {
650
-		include_spip('inc/charsets');
651
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
652
-	}
653
-
654
-	try {
655
-		$trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
656
-	} catch (JsonException $e) {
657
-		$trace = [];
658
-		spip_log('Failed to parse Json data : ' . $e->getMessage(), _LOG_ERREUR);
659
-	}
660
-	$trace['page'] = '...';
661
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
662
-
663
-	return $result;
442
+    // Conserve la mémoire de la méthode fournit éventuellement
443
+    $methode_demandee = $options['methode'] ?? '';
444
+    $default = [
445
+        'transcoder' => false,
446
+        'methode' => 'GET',
447
+        'taille_max' => null,
448
+        'headers' => [],
449
+        'datas' => '',
450
+        'boundary' => '',
451
+        'refuser_gz' => false,
452
+        'if_modified_since' => '',
453
+        'uri_referer' => '',
454
+        'file' => '',
455
+        'follow_location' => 10,
456
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
457
+    ];
458
+    $options = array_merge($default, $options);
459
+    // copier directement dans un fichier ?
460
+    $copy = $options['file'];
461
+
462
+    if ($options['methode'] == 'HEAD') {
463
+        $options['taille_max'] = 0;
464
+    }
465
+    if (is_null($options['taille_max'])) {
466
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
467
+    }
468
+
469
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
470
+
471
+    // Ajout des en-têtes spécifiques si besoin
472
+    $formatted_data = '';
473
+    if (!empty($options['headers'])) {
474
+        foreach ($options['headers'] as $champ => $valeur) {
475
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
476
+        }
477
+    }
478
+
479
+    if (!empty($options['datas'])) {
480
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
481
+        $head .= $formatted_data;
482
+        if (stripos($head, 'Content-Length:') === false) {
483
+            $head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
484
+        }
485
+        $formatted_data = $head . "\r\n" . $postdata;
486
+        if (
487
+            strlen((string) $postdata) && !$methode_demandee
488
+        ) {
489
+            $options['methode'] = 'POST';
490
+        }
491
+    } elseif ($formatted_data) {
492
+        $formatted_data .= "\r\n";
493
+    }
494
+
495
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
496
+    $url = preg_replace(',^feed://,i', 'http://', $url);
497
+    if (!tester_url_absolue($url)) {
498
+        $url = 'http://' . $url;
499
+    } elseif (str_starts_with($url, '//')) {
500
+        $url = 'http:' . $url;
501
+    }
502
+
503
+    $url = url_to_ascii($url);
504
+
505
+    $result = [
506
+        'status' => 0,
507
+        'headers' => '',
508
+        'page' => '',
509
+        'length' => 0,
510
+        'last_modified' => '',
511
+        'location' => '',
512
+        'url' => $url
513
+    ];
514
+
515
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
516
+    $refuser_gz = ($options['refuser_gz'] || $copy);
517
+
518
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
519
+    [$handle, $fopen] = init_http(
520
+        $options['methode'],
521
+        $url,
522
+        $refuser_gz,
523
+        $options['uri_referer'],
524
+        $formatted_data,
525
+        $options['version_http'],
526
+        $options['if_modified_since']
527
+    );
528
+    if (!$handle) {
529
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
530
+
531
+        return false;
532
+    }
533
+
534
+    // Sauf en fopen, envoyer le flux d'entree
535
+    // et recuperer les en-tetes de reponses
536
+    if (!$fopen) {
537
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
538
+        if (!$res) {
539
+            fclose($handle);
540
+            $t = @parse_url($url);
541
+            $host = $t['host'];
542
+            // Chinoisierie inexplicable pour contrer
543
+            // les actions liberticides de l'empire du milieu
544
+            if (
545
+                !need_proxy($host)
546
+                && ($res = @file_get_contents($url))
547
+            ) {
548
+                $result['length'] = strlen($res);
549
+                if ($copy) {
550
+                    ecrire_fichier($copy, $res);
551
+                    $result['file'] = $copy;
552
+                } else {
553
+                    $result['page'] = $res;
554
+                }
555
+                $res = [
556
+                    'status' => 200,
557
+                ];
558
+            } else {
559
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
560
+                return false;
561
+            }
562
+        } elseif ($res['location'] && $options['follow_location']) {
563
+            $options['follow_location']--;
564
+            fclose($handle);
565
+            include_spip('inc/filtres');
566
+            $url = suivre_lien($url, $res['location']);
567
+
568
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
569
+            if (
570
+                $options['methode'] !== 'GET'
571
+                && (empty($res['status']) || !in_array($res['status'], [307, 308]))
572
+            ) {
573
+                $options['methode'] = 'GET';
574
+                $options['datas'] = '';
575
+            }
576
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
577
+
578
+            return recuperer_url($url, $options);
579
+        } elseif ($res['status'] !== 200) {
580
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
581
+        }
582
+        $result['status'] = $res['status'];
583
+        if (isset($res['headers'])) {
584
+            $result['headers'] = $res['headers'];
585
+        }
586
+        if (isset($res['last_modified'])) {
587
+            $result['last_modified'] = $res['last_modified'];
588
+        }
589
+        if (isset($res['location'])) {
590
+            $result['location'] = $res['location'];
591
+        }
592
+        if (isset($res['content_length'])) {
593
+            $result['content_length'] = $res['content_length'];
594
+        }
595
+    }
596
+
597
+    // on ne veut que les entetes
598
+    if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
599
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
600
+        return $result;
601
+    }
602
+
603
+
604
+    // s'il faut deballer, le faire via un fichier temporaire
605
+    // sinon la memoire explose pour les gros flux
606
+
607
+    $gz = false;
608
+    if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
609
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
+    }
611
+
612
+    // si on n'a pas deja récupéré le contenu par une methode detournée
613
+    if (!$result['length']) {
614
+        $taille_max = $options['taille_max'];
615
+        if (isset($result['content_length'])
616
+          && !empty($result['content_length'])
617
+          && ($result['content_length'] < $taille_max)) {
618
+            $taille_max = $result['content_length'];
619
+        }
620
+        $res = recuperer_body($handle, $taille_max, $gz ?: $copy);
621
+        fclose($handle);
622
+        if ($copy) {
623
+            $result['length'] = $res;
624
+            $result['file'] = $copy;
625
+        } elseif ($res) {
626
+            $result['page'] = &$res;
627
+            $result['length'] = strlen($result['page']);
628
+        }
629
+        if (!$result['status']) {
630
+            $result['status'] = 200; // on a reussi, donc !
631
+        }
632
+    }
633
+    if (!$result['page']) {
634
+        return $result;
635
+    }
636
+
637
+    // Decompresser au besoin
638
+    if ($gz) {
639
+        $result['page'] = implode('', gzfile($gz));
640
+        $result['length'] = strlen($result['page']);
641
+        // et annuler le content-length qui correspond à la version gzip
642
+        if (isset($result['content_length'])) {
643
+            unset($result['content_length']);
644
+        }
645
+        supprimer_fichier($gz);
646
+    }
647
+
648
+    // Faut-il l'importer dans notre charset local ?
649
+    if ($options['transcoder']) {
650
+        include_spip('inc/charsets');
651
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
652
+    }
653
+
654
+    try {
655
+        $trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
656
+    } catch (JsonException $e) {
657
+        $trace = [];
658
+        spip_log('Failed to parse Json data : ' . $e->getMessage(), _LOG_ERREUR);
659
+    }
660
+    $trace['page'] = '...';
661
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
662
+
663
+    return $result;
664 664
 }
665 665
 
666 666
 /**
@@ -676,73 +676,73 @@  discard block
 block discarded – undo
676 676
  * @return array|bool|mixed
677 677
  */
678 678
 function recuperer_url_cache($url, $options = []) {
679
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
680
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
681
-	}
682
-	$default = [
683
-		'transcoder' => false,
684
-		'methode' => 'GET',
685
-		'taille_max' => null,
686
-		'datas' => '',
687
-		'boundary' => '',
688
-		'refuser_gz' => false,
689
-		'if_modified_since' => '',
690
-		'uri_referer' => '',
691
-		'file' => '',
692
-		'follow_location' => 10,
693
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
694
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
695
-	];
696
-	$options = array_merge($default, $options);
697
-
698
-	// cas ou il n'est pas possible de cacher
699
-	if (!empty($options['data']) || $options['methode'] == 'POST') {
700
-		return recuperer_url($url, $options);
701
-	}
702
-
703
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
704
-	static $errors = [];
705
-	if (isset($errors[$url])) {
706
-		return $errors[$url];
707
-	}
708
-
709
-	$sig = $options;
710
-	unset($sig['if_modified_since']);
711
-	unset($sig['delai_cache']);
712
-	$sig['url'] = $url;
713
-
714
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
715
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
716
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
717
-	$cache = "$sub$cache";
718
-
719
-	$res = false;
720
-	$is_cached = file_exists($cache);
721
-	if (
722
-		$is_cached
723
-		&& filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
724
-	) {
725
-		lire_fichier($cache, $res);
726
-		if ($res = unserialize($res)) {
727
-			// mettre le last_modified et le status=304 ?
728
-		}
729
-	}
730
-	if (!$res) {
731
-		$res = recuperer_url($url, $options);
732
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
733
-		if (!$res) {
734
-			if ($is_cached) {
735
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
736
-				lire_fichier($cache, $res);
737
-				$res = unserialize($res);
738
-			}
739
-
740
-			return $errors[$url] = $res;
741
-		}
742
-		ecrire_fichier($cache, serialize($res));
743
-	}
744
-
745
-	return $res;
679
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
680
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
681
+    }
682
+    $default = [
683
+        'transcoder' => false,
684
+        'methode' => 'GET',
685
+        'taille_max' => null,
686
+        'datas' => '',
687
+        'boundary' => '',
688
+        'refuser_gz' => false,
689
+        'if_modified_since' => '',
690
+        'uri_referer' => '',
691
+        'file' => '',
692
+        'follow_location' => 10,
693
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
694
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
695
+    ];
696
+    $options = array_merge($default, $options);
697
+
698
+    // cas ou il n'est pas possible de cacher
699
+    if (!empty($options['data']) || $options['methode'] == 'POST') {
700
+        return recuperer_url($url, $options);
701
+    }
702
+
703
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
704
+    static $errors = [];
705
+    if (isset($errors[$url])) {
706
+        return $errors[$url];
707
+    }
708
+
709
+    $sig = $options;
710
+    unset($sig['if_modified_since']);
711
+    unset($sig['delai_cache']);
712
+    $sig['url'] = $url;
713
+
714
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
715
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
716
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
717
+    $cache = "$sub$cache";
718
+
719
+    $res = false;
720
+    $is_cached = file_exists($cache);
721
+    if (
722
+        $is_cached
723
+        && filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
724
+    ) {
725
+        lire_fichier($cache, $res);
726
+        if ($res = unserialize($res)) {
727
+            // mettre le last_modified et le status=304 ?
728
+        }
729
+    }
730
+    if (!$res) {
731
+        $res = recuperer_url($url, $options);
732
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
733
+        if (!$res) {
734
+            if ($is_cached) {
735
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
736
+                lire_fichier($cache, $res);
737
+                $res = unserialize($res);
738
+            }
739
+
740
+            return $errors[$url] = $res;
741
+        }
742
+        ecrire_fichier($cache, serialize($res));
743
+    }
744
+
745
+    return $res;
746 746
 }
747 747
 
748 748
 /**
@@ -760,56 +760,56 @@  discard block
 block discarded – undo
760 760
  *   string contenu de la resource
761 761
  */
762 762
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
763
-	$tmpfile = null;
764
-	$taille = 0;
765
-	$result = '';
766
-	$fp = false;
767
-	if ($fichier) {
768
-		include_spip('inc/acces');
769
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
770
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
771
-		if (!$fp && file_exists($fichier)) {
772
-			return filesize($fichier);
773
-		}
774
-		if (!$fp) {
775
-			return false;
776
-		}
777
-		$result = 0; // on renvoie la taille du fichier
778
-	}
779
-
780
-	$max_longueur_morceaux = 8192;
781
-	while (!feof($handle) && $taille < $taille_max) {
782
-		// ne pas lire plus que ce qu'on a besoin (ou que la longueur annoncée du document)
783
-		$max_longueur_morceaux = min($max_longueur_morceaux, $taille_max - $taille);
784
-		$res = fread($handle, $max_longueur_morceaux);
785
-
786
-		// si feof ne trig pas mais on est à la fin, fread retourne false
787
-		if ($res === false) {
788
-			break;
789
-		}
790
-
791
-		$taille_morceau = strlen($res);
792
-		$taille += $taille_morceau;
793
-
794
-		if ($fp) {
795
-			fwrite($fp, $res);
796
-			$result = $taille;
797
-		} else {
798
-			$result .= $res;
799
-		}
800
-
801
-	}
802
-
803
-	if ($fp) {
804
-		spip_fclose_unlock($fp);
805
-		spip_unlink($fichier);
806
-		@rename($tmpfile, $fichier);
807
-		if (!file_exists($fichier)) {
808
-			return false;
809
-		}
810
-	}
811
-
812
-	return $result;
763
+    $tmpfile = null;
764
+    $taille = 0;
765
+    $result = '';
766
+    $fp = false;
767
+    if ($fichier) {
768
+        include_spip('inc/acces');
769
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
770
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
771
+        if (!$fp && file_exists($fichier)) {
772
+            return filesize($fichier);
773
+        }
774
+        if (!$fp) {
775
+            return false;
776
+        }
777
+        $result = 0; // on renvoie la taille du fichier
778
+    }
779
+
780
+    $max_longueur_morceaux = 8192;
781
+    while (!feof($handle) && $taille < $taille_max) {
782
+        // ne pas lire plus que ce qu'on a besoin (ou que la longueur annoncée du document)
783
+        $max_longueur_morceaux = min($max_longueur_morceaux, $taille_max - $taille);
784
+        $res = fread($handle, $max_longueur_morceaux);
785
+
786
+        // si feof ne trig pas mais on est à la fin, fread retourne false
787
+        if ($res === false) {
788
+            break;
789
+        }
790
+
791
+        $taille_morceau = strlen($res);
792
+        $taille += $taille_morceau;
793
+
794
+        if ($fp) {
795
+            fwrite($fp, $res);
796
+            $result = $taille;
797
+        } else {
798
+            $result .= $res;
799
+        }
800
+
801
+    }
802
+
803
+    if ($fp) {
804
+        spip_fclose_unlock($fp);
805
+        spip_unlink($fichier);
806
+        @rename($tmpfile, $fichier);
807
+        if (!file_exists($fichier)) {
808
+            return false;
809
+        }
810
+    }
811
+
812
+    return $result;
813 813
 }
814 814
 
815 815
 /**
@@ -831,38 +831,38 @@  discard block
 block discarded – undo
831 831
  *   string location
832 832
  */
833 833
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
834
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
835
-
836
-	$s = @trim(fgets($handle, 16384));
837
-	if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
838
-		return false;
839
-	}
840
-	$result['status'] = (int) $r[1];
841
-	while ($s = trim(fgets($handle, 16384))) {
842
-		$result['headers'][] = $s . "\n";
843
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
844
-		[, $d, $v] = $r;
845
-		$d = strtolower(trim($d));
846
-		if ( $d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
847
-			$result['location'] = $v;
848
-		} elseif ($d === 'last-modified') {
849
-			$result['last_modified'] = strtotime($v);
850
-		} elseif ($d === 'content-length' and strlen(trim($v))) {
851
-			$result['content_length'] = intval($v);
852
-		}
853
-	}
854
-	if (
855
-		$if_modified_since
856
-		&& $result['last_modified']
857
-		&& $if_modified_since > $result['last_modified']
858
-		&& $result['status'] == 200
859
-	) {
860
-		$result['status'] = 304;
861
-	}
862
-
863
-	$result['headers'] = implode('', $result['headers']);
864
-
865
-	return $result;
834
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
835
+
836
+    $s = @trim(fgets($handle, 16384));
837
+    if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
838
+        return false;
839
+    }
840
+    $result['status'] = (int) $r[1];
841
+    while ($s = trim(fgets($handle, 16384))) {
842
+        $result['headers'][] = $s . "\n";
843
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
844
+        [, $d, $v] = $r;
845
+        $d = strtolower(trim($d));
846
+        if ( $d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
847
+            $result['location'] = $v;
848
+        } elseif ($d === 'last-modified') {
849
+            $result['last_modified'] = strtotime($v);
850
+        } elseif ($d === 'content-length' and strlen(trim($v))) {
851
+            $result['content_length'] = intval($v);
852
+        }
853
+    }
854
+    if (
855
+        $if_modified_since
856
+        && $result['last_modified']
857
+        && $if_modified_since > $result['last_modified']
858
+        && $result['status'] == 200
859
+    ) {
860
+        $result['status'] = 304;
861
+    }
862
+
863
+    $result['headers'] = implode('', $result['headers']);
864
+
865
+    return $result;
866 866
 }
867 867
 
868 868
 /**
@@ -884,36 +884,36 @@  discard block
 block discarded – undo
884 884
  *     Nom du fichier pour copie locale
885 885
  **/
886 886
 function nom_fichier_copie_locale($source, $extension) {
887
-	include_spip('inc/documents');
887
+    include_spip('inc/documents');
888 888
 
889
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
890
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
889
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
890
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
891 891
 
892
-	// on se place tout le temps comme si on était a la racine
893
-	if (_DIR_RACINE) {
894
-		$d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
895
-	}
892
+    // on se place tout le temps comme si on était a la racine
893
+    if (_DIR_RACINE) {
894
+        $d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
895
+    }
896 896
 
897
-	$m = md5($source);
897
+    $m = md5($source);
898 898
 
899
-	$filename =
900
-		$d
901
-		. substr(preg_replace(',[^\w-],', '', basename($source, $extension)), 0, 16)
902
-		. '-' . substr($m, 0, 8)
903
-		. ".$extension";
899
+    $filename =
900
+        $d
901
+        . substr(preg_replace(',[^\w-],', '', basename($source, $extension)), 0, 16)
902
+        . '-' . substr($m, 0, 8)
903
+        . ".$extension";
904 904
 
905
-	// ancien nommage des fichiers distants : renommer le fichier a la volee si besoin pour eviter de dupliquer les caches
906
-	$legacy_filename =
907
-		$d
908
-		. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
909
-		. substr($m, 0, 4)
910
-		. ".$extension";
905
+    // ancien nommage des fichiers distants : renommer le fichier a la volee si besoin pour eviter de dupliquer les caches
906
+    $legacy_filename =
907
+        $d
908
+        . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
909
+        . substr($m, 0, 4)
910
+        . ".$extension";
911 911
 
912
-	if (file_exists(_DIR_RACINE . $legacy_filename)) {
913
-		@rename(_DIR_RACINE . $legacy_filename, $filename);
914
-	}
912
+    if (file_exists(_DIR_RACINE . $legacy_filename)) {
913
+        @rename(_DIR_RACINE . $legacy_filename, $filename);
914
+    }
915 915
 
916
-	return $filename;
916
+    return $filename;
917 917
 }
918 918
 
919 919
 /**
@@ -932,72 +932,72 @@  discard block
 block discarded – undo
932 932
  *      - null: Copie locale impossible
933 933
  **/
934 934
 function fichier_copie_locale($source) {
935
-	// Si c'est deja local pas de souci
936
-	if (!tester_url_absolue($source)) {
937
-		if (_DIR_RACINE) {
938
-			$source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
939
-		}
940
-
941
-		return $source;
942
-	}
943
-
944
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
945
-	// a deja ete copie en local avec cette extension
946
-	// dans ce cas elle est fiable, pas la peine de requeter en base
947
-	$path_parts = pathinfo($source);
948
-	if (!isset($path_parts['extension'])) {
949
-		$path_parts['extension'] = '';
950
-	}
951
-	$ext = $path_parts ? $path_parts['extension'] : '';
952
-	if (
953
-		$ext
954
-		&& preg_match(',^\w+$,', $ext)
955
-		&& ($f = nom_fichier_copie_locale($source, $ext))
956
-		&& file_exists(_DIR_RACINE . $f)
957
-	) {
958
-		return $f;
959
-	}
960
-
961
-
962
-	// Si c'est deja dans la table des documents,
963
-	// ramener le nom de sa copie potentielle
964
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
965
-
966
-	if ($ext) {
967
-		return nom_fichier_copie_locale($source, $ext);
968
-	}
969
-
970
-	// voir si l'extension indiquee dans le nom du fichier est ok
971
-	// et si il n'aurait pas deja ete rapatrie
972
-
973
-	$ext = $path_parts ? $path_parts['extension'] : '';
974
-
975
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
976
-		$f = nom_fichier_copie_locale($source, $ext);
977
-		if (file_exists(_DIR_RACINE . $f)) {
978
-			return $f;
979
-		}
980
-	}
981
-
982
-	// Ping  pour voir si son extension est connue et autorisee
983
-	// avec mise en cache du resultat du ping
984
-
985
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
986
-	if (
987
-		!@file_exists($cache)
988
-		|| !($path_parts = @unserialize(spip_file_get_contents($cache)))
989
-		|| _request('var_mode') === 'recalcul'
990
-	) {
991
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
992
-		ecrire_fichier($cache, serialize($path_parts));
993
-	}
994
-	$ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
995
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
996
-		return nom_fichier_copie_locale($source, $ext);
997
-	}
998
-
999
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1000
-	return null;
935
+    // Si c'est deja local pas de souci
936
+    if (!tester_url_absolue($source)) {
937
+        if (_DIR_RACINE) {
938
+            $source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
939
+        }
940
+
941
+        return $source;
942
+    }
943
+
944
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
945
+    // a deja ete copie en local avec cette extension
946
+    // dans ce cas elle est fiable, pas la peine de requeter en base
947
+    $path_parts = pathinfo($source);
948
+    if (!isset($path_parts['extension'])) {
949
+        $path_parts['extension'] = '';
950
+    }
951
+    $ext = $path_parts ? $path_parts['extension'] : '';
952
+    if (
953
+        $ext
954
+        && preg_match(',^\w+$,', $ext)
955
+        && ($f = nom_fichier_copie_locale($source, $ext))
956
+        && file_exists(_DIR_RACINE . $f)
957
+    ) {
958
+        return $f;
959
+    }
960
+
961
+
962
+    // Si c'est deja dans la table des documents,
963
+    // ramener le nom de sa copie potentielle
964
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
965
+
966
+    if ($ext) {
967
+        return nom_fichier_copie_locale($source, $ext);
968
+    }
969
+
970
+    // voir si l'extension indiquee dans le nom du fichier est ok
971
+    // et si il n'aurait pas deja ete rapatrie
972
+
973
+    $ext = $path_parts ? $path_parts['extension'] : '';
974
+
975
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
976
+        $f = nom_fichier_copie_locale($source, $ext);
977
+        if (file_exists(_DIR_RACINE . $f)) {
978
+            return $f;
979
+        }
980
+    }
981
+
982
+    // Ping  pour voir si son extension est connue et autorisee
983
+    // avec mise en cache du resultat du ping
984
+
985
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
986
+    if (
987
+        !@file_exists($cache)
988
+        || !($path_parts = @unserialize(spip_file_get_contents($cache)))
989
+        || _request('var_mode') === 'recalcul'
990
+    ) {
991
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
992
+        ecrire_fichier($cache, serialize($path_parts));
993
+    }
994
+    $ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
995
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
996
+        return nom_fichier_copie_locale($source, $ext);
997
+    }
998
+
999
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1000
+    return null;
1001 1001
 }
1002 1002
 
1003 1003
 
@@ -1026,129 +1026,129 @@  discard block
 block discarded – undo
1026 1026
  **/
1027 1027
 function recuperer_infos_distantes($source, $options = []) {
1028 1028
 
1029
-	// pas la peine de perdre son temps
1030
-	if (!tester_url_absolue($source)) {
1031
-		return false;
1032
-	}
1033
-
1034
-	$taille_max = $options['taille_max'] ?? 0;
1035
-	$charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
1036
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
1037
-
1038
-	# charger les alias des types mime
1039
-	include_spip('base/typedoc');
1040
-
1041
-	$a = [];
1042
-	$mime_type = '';
1043
-	// On va directement charger le debut des images et des fichiers html,
1044
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1045
-	// ca echoue l'utilisateur devra les entrer...
1046
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1047
-	if (
1048
-		$callback_valider_url
1049
-		&& is_callable($callback_valider_url)
1050
-		&& !$callback_valider_url($reponse['url'])
1051
-	) {
1052
-		return false;
1053
-	}
1054
-	$headers = $reponse['headers'] ?? '';
1055
-	$a['body'] = $reponse['page'] ?? '';
1056
-	if ($headers) {
1057
-		$mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1058
-
1059
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1060
-			return false;
1061
-		}
1062
-
1063
-		$a['extension'] = $extension;
1064
-
1065
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1066
-			$a['taille'] = (int) $regs[1];
1067
-		}
1068
-	}
1069
-
1070
-	// Echec avec HEAD, on tente avec GET
1071
-	if (!$a && !$taille_max) {
1072
-		spip_log("tenter GET $source", 'distant');
1073
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1074
-		$a = recuperer_infos_distantes($source, $options);
1075
-	}
1076
-
1077
-	// si on a rien trouve pas la peine d'insister
1078
-	if (!$a) {
1079
-		return false;
1080
-	}
1081
-
1082
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1083
-	// recharger le document en GET et recuperer des donnees supplementaires...
1084
-	include_spip('inc/filtres_images_lib_mini');
1085
-	include_spip('inc/documents');
1086
-	if (
1087
-		str_starts_with($mime_type, 'image/')
1088
-		&& ($extension = _image_trouver_extension_depuis_mime($mime_type))
1089
-	) {
1090
-		if (
1091
-			$taille_max == 0
1092
-			&& (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1093
-			&& in_array($extension, formats_image_acceptables())
1094
-			&& $charger_si_petite_image
1095
-		) {
1096
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1097
-			$a = recuperer_infos_distantes($source, $options);
1098
-		} else {
1099
-			if ($a['body']) {
1100
-				$a['extension'] = corriger_extension($extension);
1101
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1102
-				ecrire_fichier($a['fichier'], $a['body']);
1103
-				$size_image = @spip_getimagesize($a['fichier']);
1104
-				$a['largeur'] = (int) $size_image[0];
1105
-				$a['hauteur'] = (int) $size_image[1];
1106
-				$a['type_image'] = true;
1107
-			}
1108
-		}
1109
-	}
1110
-
1111
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1112
-	// ce sera mieux que 0x0
1113
-	// Flash is dead!
1114
-	if (
1115
-		$a
1116
-		&& isset($a['extension'])
1117
-		&& $a['extension'] == 'swf'
1118
-		&& empty($a['largeur'])
1119
-	) {
1120
-		$a['largeur'] = 425;
1121
-		$a['hauteur'] = 350;
1122
-	}
1123
-
1124
-	if ($mime_type == 'text/html') {
1125
-		include_spip('inc/filtres');
1126
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1127
-		$page = $page['page'] ?? '';
1128
-		if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1129
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1130
-		}
1131
-		if (!isset($a['taille']) || !$a['taille']) {
1132
-			$a['taille'] = strlen((string) $page); # a peu pres
1133
-		}
1134
-	}
1135
-	$a['mime_type'] = $mime_type;
1136
-
1137
-	return $a;
1029
+    // pas la peine de perdre son temps
1030
+    if (!tester_url_absolue($source)) {
1031
+        return false;
1032
+    }
1033
+
1034
+    $taille_max = $options['taille_max'] ?? 0;
1035
+    $charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
1036
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
1037
+
1038
+    # charger les alias des types mime
1039
+    include_spip('base/typedoc');
1040
+
1041
+    $a = [];
1042
+    $mime_type = '';
1043
+    // On va directement charger le debut des images et des fichiers html,
1044
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1045
+    // ca echoue l'utilisateur devra les entrer...
1046
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1047
+    if (
1048
+        $callback_valider_url
1049
+        && is_callable($callback_valider_url)
1050
+        && !$callback_valider_url($reponse['url'])
1051
+    ) {
1052
+        return false;
1053
+    }
1054
+    $headers = $reponse['headers'] ?? '';
1055
+    $a['body'] = $reponse['page'] ?? '';
1056
+    if ($headers) {
1057
+        $mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1058
+
1059
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1060
+            return false;
1061
+        }
1062
+
1063
+        $a['extension'] = $extension;
1064
+
1065
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1066
+            $a['taille'] = (int) $regs[1];
1067
+        }
1068
+    }
1069
+
1070
+    // Echec avec HEAD, on tente avec GET
1071
+    if (!$a && !$taille_max) {
1072
+        spip_log("tenter GET $source", 'distant');
1073
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1074
+        $a = recuperer_infos_distantes($source, $options);
1075
+    }
1076
+
1077
+    // si on a rien trouve pas la peine d'insister
1078
+    if (!$a) {
1079
+        return false;
1080
+    }
1081
+
1082
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1083
+    // recharger le document en GET et recuperer des donnees supplementaires...
1084
+    include_spip('inc/filtres_images_lib_mini');
1085
+    include_spip('inc/documents');
1086
+    if (
1087
+        str_starts_with($mime_type, 'image/')
1088
+        && ($extension = _image_trouver_extension_depuis_mime($mime_type))
1089
+    ) {
1090
+        if (
1091
+            $taille_max == 0
1092
+            && (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1093
+            && in_array($extension, formats_image_acceptables())
1094
+            && $charger_si_petite_image
1095
+        ) {
1096
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1097
+            $a = recuperer_infos_distantes($source, $options);
1098
+        } else {
1099
+            if ($a['body']) {
1100
+                $a['extension'] = corriger_extension($extension);
1101
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1102
+                ecrire_fichier($a['fichier'], $a['body']);
1103
+                $size_image = @spip_getimagesize($a['fichier']);
1104
+                $a['largeur'] = (int) $size_image[0];
1105
+                $a['hauteur'] = (int) $size_image[1];
1106
+                $a['type_image'] = true;
1107
+            }
1108
+        }
1109
+    }
1110
+
1111
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1112
+    // ce sera mieux que 0x0
1113
+    // Flash is dead!
1114
+    if (
1115
+        $a
1116
+        && isset($a['extension'])
1117
+        && $a['extension'] == 'swf'
1118
+        && empty($a['largeur'])
1119
+    ) {
1120
+        $a['largeur'] = 425;
1121
+        $a['hauteur'] = 350;
1122
+    }
1123
+
1124
+    if ($mime_type == 'text/html') {
1125
+        include_spip('inc/filtres');
1126
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1127
+        $page = $page['page'] ?? '';
1128
+        if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1129
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1130
+        }
1131
+        if (!isset($a['taille']) || !$a['taille']) {
1132
+            $a['taille'] = strlen((string) $page); # a peu pres
1133
+        }
1134
+    }
1135
+    $a['mime_type'] = $mime_type;
1136
+
1137
+    return $a;
1138 1138
 }
1139 1139
 
1140 1140
 /**
1141 1141
  * Retrouver un mime type depuis les headers
1142 1142
  */
1143 1143
 function distant_trouver_mime_type_selon_headers(string $source, string $headers): string {
1144
-	$mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1144
+    $mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1145 1145
 
1146
-	// Appliquer les alias
1147
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1148
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1149
-	}
1146
+    // Appliquer les alias
1147
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1148
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1149
+    }
1150 1150
 
1151
-	return $mime_type;
1151
+    return $mime_type;
1152 1152
 }
1153 1153
 
1154 1154
 /**
@@ -1157,58 +1157,58 @@  discard block
 block discarded – undo
1157 1157
  * @return false|string
1158 1158
  */
1159 1159
 function distant_trouver_extension_selon_headers(string $source, string $headers) {
1160
-	$mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1161
-
1162
-	// pour corriger_extension()
1163
-	include_spip('inc/documents');
1164
-
1165
-	// Si on a un mime-type insignifiant
1166
-	// text/plain,application/octet-stream ou vide
1167
-	// c'est peut-etre que le serveur ne sait pas
1168
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1169
-	// ou le Content-Disposition: attachment; filename=...
1170
-	$t = null;
1171
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1172
-		if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1173
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1174
-		}
1175
-		if (
1176
-			!$t
1177
-			&& preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1178
-			&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1179
-		) {
1180
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1181
-		}
1182
-	}
1183
-
1184
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1185
-	if (!$t) {
1186
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1187
-	}
1188
-
1189
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1190
-	// On essaie de nouveau avec l'extension
1191
-	if (
1192
-		!$t
1193
-		&& $mime_type != 'text/plain'
1194
-		&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1195
-	) {
1196
-		# eviter xxx.3 => 3gp (> SPIP 3)
1197
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1198
-	}
1199
-
1200
-	if ($t) {
1201
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1202
-		return $t['extension'];
1203
-	} else {
1204
-		# par defaut on retombe sur '.bin' si c'est autorise
1205
-		spip_log("mime-type $mime_type inconnu", 'distant');
1206
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1207
-		if (!$t) {
1208
-			return false;
1209
-		}
1210
-		return $t['extension'];
1211
-	}
1160
+    $mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1161
+
1162
+    // pour corriger_extension()
1163
+    include_spip('inc/documents');
1164
+
1165
+    // Si on a un mime-type insignifiant
1166
+    // text/plain,application/octet-stream ou vide
1167
+    // c'est peut-etre que le serveur ne sait pas
1168
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1169
+    // ou le Content-Disposition: attachment; filename=...
1170
+    $t = null;
1171
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1172
+        if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1173
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1174
+        }
1175
+        if (
1176
+            !$t
1177
+            && preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1178
+            && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1179
+        ) {
1180
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1181
+        }
1182
+    }
1183
+
1184
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1185
+    if (!$t) {
1186
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1187
+    }
1188
+
1189
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1190
+    // On essaie de nouveau avec l'extension
1191
+    if (
1192
+        !$t
1193
+        && $mime_type != 'text/plain'
1194
+        && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1195
+    ) {
1196
+        # eviter xxx.3 => 3gp (> SPIP 3)
1197
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1198
+    }
1199
+
1200
+    if ($t) {
1201
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1202
+        return $t['extension'];
1203
+    } else {
1204
+        # par defaut on retombe sur '.bin' si c'est autorise
1205
+        spip_log("mime-type $mime_type inconnu", 'distant');
1206
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1207
+        if (!$t) {
1208
+            return false;
1209
+        }
1210
+        return $t['extension'];
1211
+    }
1212 1212
 }
1213 1213
 
1214 1214
 /**
@@ -1224,45 +1224,45 @@  discard block
 block discarded – undo
1224 1224
  */
1225 1225
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1226 1226
 
1227
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1228
-
1229
-	// rien a faire si pas de proxy :)
1230
-	if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1231
-		return '';
1232
-	}
1233
-
1234
-	if (is_null($http_noproxy)) {
1235
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1236
-	}
1237
-	// si pas d'exception, on retourne le proxy
1238
-	if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1239
-		return $http_proxy;
1240
-	}
1241
-
1242
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1243
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1244
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1245
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1246
-	$http_noproxy = " $http_noproxy ";
1247
-	$domain = $host;
1248
-	// si le domaine exact www.example.org est dans les exceptions
1249
-	if (str_contains($http_noproxy, (string) " $domain ")) {
1250
-		return '';
1251
-	}
1252
-
1253
-	while (str_contains($domain, '.')) {
1254
-		$domain = explode('.', $domain);
1255
-		array_shift($domain);
1256
-		$domain = implode('.', $domain);
1257
-
1258
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1259
-		if (str_contains($http_noproxy, (string) " .$domain ")) {
1260
-			return '';
1261
-		}
1262
-	}
1263
-
1264
-	// ok c'est pas une exception
1265
-	return $http_proxy;
1227
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1228
+
1229
+    // rien a faire si pas de proxy :)
1230
+    if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1231
+        return '';
1232
+    }
1233
+
1234
+    if (is_null($http_noproxy)) {
1235
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1236
+    }
1237
+    // si pas d'exception, on retourne le proxy
1238
+    if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1239
+        return $http_proxy;
1240
+    }
1241
+
1242
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1243
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1244
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1245
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1246
+    $http_noproxy = " $http_noproxy ";
1247
+    $domain = $host;
1248
+    // si le domaine exact www.example.org est dans les exceptions
1249
+    if (str_contains($http_noproxy, (string) " $domain ")) {
1250
+        return '';
1251
+    }
1252
+
1253
+    while (str_contains($domain, '.')) {
1254
+        $domain = explode('.', $domain);
1255
+        array_shift($domain);
1256
+        $domain = implode('.', $domain);
1257
+
1258
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1259
+        if (str_contains($http_noproxy, (string) " .$domain ")) {
1260
+            return '';
1261
+        }
1262
+    }
1263
+
1264
+    // ok c'est pas une exception
1265
+    return $http_proxy;
1266 1266
 }
1267 1267
 
1268 1268
 
@@ -1285,60 +1285,60 @@  discard block
 block discarded – undo
1285 1285
  * @return array
1286 1286
  */
1287 1287
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1288
-	$user = $via_proxy = $proxy_user = '';
1289
-	$fopen = false;
1290
-
1291
-	$t = @parse_url($url);
1292
-	$host = $t['host'];
1293
-	if ($t['scheme'] == 'http') {
1294
-		$scheme = 'http';
1295
-		$noproxy = '';
1296
-	} elseif ($t['scheme'] == 'https') {
1297
-		$scheme = 'ssl';
1298
-		$noproxy = 'ssl://';
1299
-		if (!isset($t['port']) || !($port = $t['port'])) {
1300
-			$t['port'] = 443;
1301
-		}
1302
-	} else {
1303
-		$scheme = $t['scheme'];
1304
-		$noproxy = $scheme . '://';
1305
-	}
1306
-	if (isset($t['user'])) {
1307
-		// user et pass doivent être passés en urlencodé dans l'URL, on redecode ici
1308
-		$user = [urldecode($t['user']), urldecode($t['pass'])];
1309
-	}
1310
-
1311
-	if (!isset($t['port']) || !($port = $t['port'])) {
1312
-		$port = 80;
1313
-	}
1314
-	if (!isset($t['path']) || !($path = $t['path'])) {
1315
-		$path = '/';
1316
-	}
1317
-
1318
-	if (!empty($t['query'])) {
1319
-		$path .= '?' . $t['query'];
1320
-	}
1321
-
1322
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1323
-	if (!$f || !is_resource($f)) {
1324
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1325
-		// ce qui correspond a $f===110
1326
-		if (
1327
-			$f !== 110
1328
-			&& !need_proxy($host)
1329
-			&& !_request('tester_proxy')
1330
-			&& (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1331
-		) {
1332
-			$f = @fopen($url, 'rb');
1333
-			spip_log("connexion vers $url par simple fopen", 'distant');
1334
-			$fopen = true;
1335
-		} else {
1336
-			// echec total
1337
-			$f = false;
1338
-		}
1339
-	}
1340
-
1341
-	return [$f, $fopen];
1288
+    $user = $via_proxy = $proxy_user = '';
1289
+    $fopen = false;
1290
+
1291
+    $t = @parse_url($url);
1292
+    $host = $t['host'];
1293
+    if ($t['scheme'] == 'http') {
1294
+        $scheme = 'http';
1295
+        $noproxy = '';
1296
+    } elseif ($t['scheme'] == 'https') {
1297
+        $scheme = 'ssl';
1298
+        $noproxy = 'ssl://';
1299
+        if (!isset($t['port']) || !($port = $t['port'])) {
1300
+            $t['port'] = 443;
1301
+        }
1302
+    } else {
1303
+        $scheme = $t['scheme'];
1304
+        $noproxy = $scheme . '://';
1305
+    }
1306
+    if (isset($t['user'])) {
1307
+        // user et pass doivent être passés en urlencodé dans l'URL, on redecode ici
1308
+        $user = [urldecode($t['user']), urldecode($t['pass'])];
1309
+    }
1310
+
1311
+    if (!isset($t['port']) || !($port = $t['port'])) {
1312
+        $port = 80;
1313
+    }
1314
+    if (!isset($t['path']) || !($path = $t['path'])) {
1315
+        $path = '/';
1316
+    }
1317
+
1318
+    if (!empty($t['query'])) {
1319
+        $path .= '?' . $t['query'];
1320
+    }
1321
+
1322
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1323
+    if (!$f || !is_resource($f)) {
1324
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1325
+        // ce qui correspond a $f===110
1326
+        if (
1327
+            $f !== 110
1328
+            && !need_proxy($host)
1329
+            && !_request('tester_proxy')
1330
+            && (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1331
+        ) {
1332
+            $f = @fopen($url, 'rb');
1333
+            spip_log("connexion vers $url par simple fopen", 'distant');
1334
+            $fopen = true;
1335
+        } else {
1336
+            // echec total
1337
+            $f = false;
1338
+        }
1339
+    }
1340
+
1341
+    return [$f, $fopen];
1342 1342
 }
1343 1343
 
1344 1344
 /**
@@ -1373,124 +1373,124 @@  discard block
 block discarded – undo
1373 1373
  *   resource socket vers l'url demandee
1374 1374
  */
1375 1375
 function lance_requete(
1376
-	$method,
1377
-	$scheme,
1378
-	$user,
1379
-	$host,
1380
-	$path,
1381
-	$port,
1382
-	$noproxy,
1383
-	$refuse_gz = false,
1384
-	$referer = '',
1385
-	$datas = '',
1386
-	$vers = 'HTTP/1.0',
1387
-	$date = ''
1376
+    $method,
1377
+    $scheme,
1378
+    $user,
1379
+    $host,
1380
+    $path,
1381
+    $port,
1382
+    $noproxy,
1383
+    $refuse_gz = false,
1384
+    $referer = '',
1385
+    $datas = '',
1386
+    $vers = 'HTTP/1.0',
1387
+    $date = ''
1388 1388
 ) {
1389 1389
 
1390
-	$proxy_user = '';
1391
-	$http_proxy = need_proxy($host);
1392
-	if ($user) {
1393
-		$user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1394
-	}
1395
-
1396
-	$connect = '';
1397
-	if ($http_proxy) {
1398
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1399
-			$path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1400
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1401
-				. "Host: $path_host\r\n"
1402
-				. "Proxy-Connection: Keep-Alive\r\n";
1403
-		} else {
1404
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1405
-				. ($user ? "$user@" : '')
1406
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1407
-		}
1408
-		$t2 = @parse_url($http_proxy);
1409
-		$first_host = $t2['host'];
1410
-		$first_port = ($t2['port'] ?? null) ?: 80;
1411
-		if ($t2['user'] ?? null) {
1412
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1413
-		}
1414
-	} else {
1415
-		$first_host = $noproxy . $host;
1416
-		$first_port = $port;
1417
-	}
1418
-
1419
-	if ($connect) {
1420
-		$streamContext = stream_context_create([
1421
-			'ssl' => [
1422
-				'verify_peer' => false,
1423
-				'allow_self_signed' => true,
1424
-				'SNI_enabled' => true,
1425
-				'peer_name' => $host,
1426
-			]
1427
-		]);
1428
-		$f = @stream_socket_client(
1429
-			"tcp://$first_host:$first_port",
1430
-			$errno,
1431
-			$errstr,
1432
-			_INC_DISTANT_CONNECT_TIMEOUT,
1433
-			STREAM_CLIENT_CONNECT,
1434
-			$streamContext
1435
-		);
1436
-		spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1437
-		if (!$f) {
1438
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1439
-			return $errno;
1440
-		}
1441
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1442
-
1443
-		fwrite($f, $connect);
1444
-		fwrite($f, "\r\n");
1445
-		$res = fread($f, 1024);
1446
-		if (
1447
-			!$res
1448
-			|| ($res = explode(' ', $res)) === []
1449
-			|| $res[1] !== '200'
1450
-		) {
1451
-			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1452
-			fclose($f);
1453
-
1454
-			return false;
1455
-		}
1456
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1457
-		stream_set_blocking($f, true);
1458
-		// envoyer le handshake
1459
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1460
-		spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1461
-	} else {
1462
-		$ntry = 3;
1463
-		do {
1464
-			$f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1465
-		} while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1466
-		spip_log("Recuperer $path sur $first_host:$first_port par $f");
1467
-		if (!$f) {
1468
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1469
-
1470
-			return $errno;
1471
-		}
1472
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1473
-	}
1474
-
1475
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1476
-
1477
-	$host_port = $host;
1478
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1479
-		$host_port .= ":$port";
1480
-	}
1481
-	$req = "$method $path $vers\r\n"
1482
-		. "Host: $host_port\r\n"
1483
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1484
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1485
-		. ($site ? "Referer: $site/$referer\r\n" : '')
1486
-		. ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1487
-		. ($user ? 'Authorization: Basic ' . base64_encode(urldecode($user)) . "\r\n" : '')
1488
-		. ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1489
-		. (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1390
+    $proxy_user = '';
1391
+    $http_proxy = need_proxy($host);
1392
+    if ($user) {
1393
+        $user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1394
+    }
1395
+
1396
+    $connect = '';
1397
+    if ($http_proxy) {
1398
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1399
+            $path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1400
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1401
+                . "Host: $path_host\r\n"
1402
+                . "Proxy-Connection: Keep-Alive\r\n";
1403
+        } else {
1404
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1405
+                . ($user ? "$user@" : '')
1406
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1407
+        }
1408
+        $t2 = @parse_url($http_proxy);
1409
+        $first_host = $t2['host'];
1410
+        $first_port = ($t2['port'] ?? null) ?: 80;
1411
+        if ($t2['user'] ?? null) {
1412
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1413
+        }
1414
+    } else {
1415
+        $first_host = $noproxy . $host;
1416
+        $first_port = $port;
1417
+    }
1418
+
1419
+    if ($connect) {
1420
+        $streamContext = stream_context_create([
1421
+            'ssl' => [
1422
+                'verify_peer' => false,
1423
+                'allow_self_signed' => true,
1424
+                'SNI_enabled' => true,
1425
+                'peer_name' => $host,
1426
+            ]
1427
+        ]);
1428
+        $f = @stream_socket_client(
1429
+            "tcp://$first_host:$first_port",
1430
+            $errno,
1431
+            $errstr,
1432
+            _INC_DISTANT_CONNECT_TIMEOUT,
1433
+            STREAM_CLIENT_CONNECT,
1434
+            $streamContext
1435
+        );
1436
+        spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1437
+        if (!$f) {
1438
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1439
+            return $errno;
1440
+        }
1441
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1442
+
1443
+        fwrite($f, $connect);
1444
+        fwrite($f, "\r\n");
1445
+        $res = fread($f, 1024);
1446
+        if (
1447
+            !$res
1448
+            || ($res = explode(' ', $res)) === []
1449
+            || $res[1] !== '200'
1450
+        ) {
1451
+            spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1452
+            fclose($f);
1453
+
1454
+            return false;
1455
+        }
1456
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1457
+        stream_set_blocking($f, true);
1458
+        // envoyer le handshake
1459
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1460
+        spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1461
+    } else {
1462
+        $ntry = 3;
1463
+        do {
1464
+            $f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1465
+        } while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1466
+        spip_log("Recuperer $path sur $first_host:$first_port par $f");
1467
+        if (!$f) {
1468
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1469
+
1470
+            return $errno;
1471
+        }
1472
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1473
+    }
1474
+
1475
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1476
+
1477
+    $host_port = $host;
1478
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1479
+        $host_port .= ":$port";
1480
+    }
1481
+    $req = "$method $path $vers\r\n"
1482
+        . "Host: $host_port\r\n"
1483
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1484
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1485
+        . ($site ? "Referer: $site/$referer\r\n" : '')
1486
+        . ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1487
+        . ($user ? 'Authorization: Basic ' . base64_encode(urldecode($user)) . "\r\n" : '')
1488
+        . ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1489
+        . (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1490 1490
 
1491 1491
 #	spip_log("Requete\n$req", 'distant');
1492
-	fwrite($f, $req);
1493
-	fwrite($f, $datas ?: "\r\n");
1492
+    fwrite($f, $req);
1493
+    fwrite($f, $datas ?: "\r\n");
1494 1494
 
1495
-	return $f;
1495
+    return $f;
1496 1496
 }
Please login to merge, or discard this patch.