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