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