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