Completed
Push — master ( b0cbd6...fdca64 )
by cam
01:18
created
ecrire/inc/distant.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -220,8 +220,7 @@
 block discarded – undo
220 220
 						break;
221 221
 					}
222 222
 				}
223
-			}
224
-			else {
223
+			} else {
225 224
 				$ip = false;
226 225
 			}
227 226
 		}
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28 28
 }
29 29
 if (!defined('_INC_DISTANT_USER_AGENT')) {
30
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
31 31
 }
32 32
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
33 33
 	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37 37
 }
38 38
 
39
-define('_REGEXP_COPIE_LOCALE', ',' 	.
39
+define('_REGEXP_COPIE_LOCALE', ','.
40 40
 	preg_replace(
41 41
 		'@^https?:@',
42 42
 		'https?:',
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 
74 74
 	// si c'est la protection de soi-meme, retourner le path
75 75
 	if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
-		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
76
+		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)).urldecode($match[1]);
77 77
 
78 78
 		return @file_exists($source) ? $source : false;
79 79
 	}
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		return false;
94 94
 	}
95 95
 
96
-	$localrac = _DIR_RACINE . $local;
96
+	$localrac = _DIR_RACINE.$local;
97 97
 	$t = ($mode === 'force') ? false : @file_exists($localrac);
98 98
 
99 99
 	// test d'existence du fichier
@@ -113,17 +113,17 @@  discard block
 block discarded – undo
113 113
 		if (!$taille_max) {
114 114
 			$taille_max = _COPIE_LOCALE_MAX_SIZE;
115 115
 		}
116
-		$localrac_tmp = $localrac . '.tmp';
116
+		$localrac_tmp = $localrac.'.tmp';
117 117
 		$res = recuperer_url(
118 118
 			$source,
119 119
 			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120 120
 		);
121 121
 
122 122
 		if (!$res || !$res['length'] && $res['status'] != 304) {
123
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
123
+			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : ".($res ? $res['status'] : '-'), 'distant'._LOG_INFO_IMPORTANTE);
124 124
 			@unlink($localrac_tmp);
125 125
 		} 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 || !$res['length']) {
129 129
 			// si $t c'est sans doute juste un not-modified-since
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 			&& is_callable($callback_valider_url)
137 137
 			&& !$callback_valider_url($res['url'])
138 138
 		) {
139
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
139
+			spip_log('copie_locale : url finale '.$res['url']." non valide, on refuse le fichier $localrac_tmp", 'distant'._LOG_INFO_IMPORTANTE);
140 140
 			@unlink($localrac_tmp);
141 141
 			return $t ? $local : false;
142 142
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 	if (!$is_known_host) {
228 228
 		$host = trim($parsed_url['host'], '.');
229
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
229
+		if (!$ip = filter_var($host, FILTER_VALIDATE_IP)) {
230 230
 			$ip = gethostbyname($host);
231 231
 			if ($ip === $host) {
232 232
 				// Error condition for gethostbyname()
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 				$ip = false;
247 247
 			}
248 248
 		}
249
-		if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
249
+		if ($ip && !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250 250
 			return false;
251 251
 		}
252 252
 	}
@@ -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
 
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
 				foreach ($donnees as $cle => $valeur) {
361 361
 					if (is_array($valeur)) {
362 362
 						foreach ($valeur as $val2) {
363
-							$chaines[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
363
+							$chaines[] = rawurlencode($cle).'[]='.rawurlencode((string) $val2);
364 364
 						}
365 365
 					} else {
366
-						$chaines[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
366
+						$chaines[] = rawurlencode($cle).'='.rawurlencode((string) $valeur);
367 367
 					}
368 368
 				}
369 369
 				$chaine = implode('&', $chaines);
@@ -466,13 +466,13 @@  discard block
 block discarded – undo
466 466
 		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
467 467
 	}
468 468
 
469
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
469
+	spip_log('recuperer_url '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
470 470
 
471 471
 	// Ajout des en-têtes spécifiques si besoin
472 472
 	$formatted_data = '';
473 473
 	if (!empty($options['headers'])) {
474 474
 		foreach ($options['headers'] as $champ => $valeur) {
475
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
475
+			$formatted_data .= $champ.': '.$valeur."\r\n";
476 476
 		}
477 477
 	}
478 478
 
@@ -480,9 +480,9 @@  discard block
 block discarded – undo
480 480
 		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
481 481
 		$head .= $formatted_data;
482 482
 		if (stripos($head, 'Content-Length:') === false) {
483
-			$head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
483
+			$head .= 'Content-Length: '.strlen((string) $postdata)."\r\n";
484 484
 		}
485
-		$formatted_data = $head . "\r\n" . $postdata;
485
+		$formatted_data = $head."\r\n".$postdata;
486 486
 		if (
487 487
 			strlen((string) $postdata) && !$methode_demandee
488 488
 		) {
@@ -495,9 +495,9 @@  discard block
 block discarded – undo
495 495
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
496 496
 	$url = preg_replace(',^feed://,i', 'http://', $url);
497 497
 	if (!tester_url_absolue($url)) {
498
-		$url = 'http://' . $url;
498
+		$url = 'http://'.$url;
499 499
 	} elseif (str_starts_with($url, '//')) {
500
-		$url = 'http:' . $url;
500
+		$url = 'http:'.$url;
501 501
 	}
502 502
 
503 503
 	$url = url_to_ascii($url);
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 		$options['if_modified_since']
527 527
 	);
528 528
 	if (!$handle) {
529
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
529
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
530 530
 
531 531
 		return false;
532 532
 	}
@@ -556,7 +556,7 @@  discard block
 block discarded – undo
556 556
 					'status' => 200,
557 557
 				];
558 558
 			} else {
559
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
559
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
560 560
 				return false;
561 561
 			}
562 562
 		} elseif ($res['location'] && $options['follow_location']) {
@@ -573,11 +573,11 @@  discard block
 block discarded – undo
573 573
 				$options['methode'] = 'GET';
574 574
 				$options['datas'] = '';
575 575
 			}
576
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
576
+			spip_log('recuperer_url recommence '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
577 577
 
578 578
 			return recuperer_url($url, $options);
579 579
 		} elseif ($res['status'] !== 200) {
580
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
580
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
581 581
 		}
582 582
 		$result['status'] = $res['status'];
583 583
 		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'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
599
+		spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($result, JSON_THROW_ON_ERROR), '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", (string) $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 n'a pas deja récupéré le contenu par une methode detournée
@@ -650,10 +650,10 @@  discard block
 block discarded – undo
650 650
 		$trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
651 651
 	} catch (JsonException $e) {
652 652
 		$trace = [];
653
-		spip_log('Failed to parse Json data : ' . $e->getMessage(), _LOG_ERREUR);
653
+		spip_log('Failed to parse Json data : '.$e->getMessage(), _LOG_ERREUR);
654 654
 	}
655 655
 	$trace['page'] = '...';
656
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
656
+	spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($trace, JSON_THROW_ON_ERROR), 'distant'._LOG_DEBUG);
657 657
 
658 658
 	return $result;
659 659
 }
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 	$sig['url'] = $url;
708 708
 
709 709
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
710
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
710
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
711 711
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
712 712
 	$cache = "$sub$cache";
713 713
 
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 	$fp = false;
762 762
 	if ($fichier) {
763 763
 		include_spip('inc/acces');
764
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
764
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
765 765
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
766 766
 		if (!$fp && file_exists($fichier)) {
767 767
 			return filesize($fichier);
@@ -850,11 +850,11 @@  discard block
 block discarded – undo
850 850
 	}
851 851
 	$result['status'] = (int) $r[1];
852 852
 	while ($s = trim(fgets($handle, 16384))) {
853
-		$result['headers'][] = $s . "\n";
853
+		$result['headers'][] = $s."\n";
854 854
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
855 855
 		[, $d, $v] = $r;
856 856
 		$d = strtolower(trim($d));
857
-		if ( $d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
857
+		if ($d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
858 858
 			$result['location'] = $v;
859 859
 		} elseif ($d === 'last-modified') {
860 860
 			$result['last_modified'] = strtotime($v);
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 
903 903
 	// on se place tout le temps comme si on était a la racine
904 904
 	if (_DIR_RACINE) {
905
-		$d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
905
+		$d = preg_replace(',^'.preg_quote((string) _DIR_RACINE, ',').',', '', (string) $d);
906 906
 	}
907 907
 
908 908
 	$m = md5($source);
@@ -910,18 +910,18 @@  discard block
 block discarded – undo
910 910
 	$filename =
911 911
 		$d
912 912
 		. substr(preg_replace(',[^\w-],', '', basename($source, $extension)), 0, 16)
913
-		. '-' . substr($m, 0, 8)
913
+		. '-'.substr($m, 0, 8)
914 914
 		. ".$extension";
915 915
 
916 916
 	// ancien nommage des fichiers distants : renommer le fichier a la volee si besoin pour eviter de dupliquer les caches
917 917
 	$legacy_filename =
918 918
 		$d
919
-		. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
919
+		. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
920 920
 		. substr($m, 0, 4)
921 921
 		. ".$extension";
922 922
 
923
-	if (file_exists(_DIR_RACINE . $legacy_filename)) {
924
-		@rename(_DIR_RACINE . $legacy_filename, $filename);
923
+	if (file_exists(_DIR_RACINE.$legacy_filename)) {
924
+		@rename(_DIR_RACINE.$legacy_filename, $filename);
925 925
 	}
926 926
 
927 927
 	return $filename;
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
 	// Si c'est deja local pas de souci
947 947
 	if (!tester_url_absolue($source)) {
948 948
 		if (_DIR_RACINE) {
949
-			$source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
949
+			$source = preg_replace(',^'.preg_quote((string) _DIR_RACINE, ',').',', '', $source);
950 950
 		}
951 951
 
952 952
 		return $source;
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 		$ext
965 965
 		&& preg_match(',^\w+$,', $ext)
966 966
 		&& ($f = nom_fichier_copie_locale($source, $ext))
967
-		&& file_exists(_DIR_RACINE . $f)
967
+		&& file_exists(_DIR_RACINE.$f)
968 968
 	) {
969 969
 		return $f;
970 970
 	}
@@ -972,7 +972,7 @@  discard block
 block discarded – undo
972 972
 
973 973
 	// Si c'est deja dans la table des documents,
974 974
 	// ramener le nom de sa copie potentielle
975
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
975
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
976 976
 
977 977
 	if ($ext) {
978 978
 		return nom_fichier_copie_locale($source, $ext);
@@ -983,9 +983,9 @@  discard block
 block discarded – undo
983 983
 
984 984
 	$ext = $path_parts ? $path_parts['extension'] : '';
985 985
 
986
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
986
+	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
987 987
 		$f = nom_fichier_copie_locale($source, $ext);
988
-		if (file_exists(_DIR_RACINE . $f)) {
988
+		if (file_exists(_DIR_RACINE.$f)) {
989 989
 			return $f;
990 990
 		}
991 991
 	}
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
 	// Ping  pour voir si son extension est connue et autorisee
994 994
 	// avec mise en cache du resultat du ping
995 995
 
996
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
996
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
997 997
 	if (
998 998
 		!@file_exists($cache)
999 999
 		|| !($path_parts = @unserialize(spip_file_get_contents($cache)))
@@ -1003,11 +1003,11 @@  discard block
 block discarded – undo
1003 1003
 		ecrire_fichier($cache, serialize($path_parts));
1004 1004
 	}
1005 1005
 	$ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
1006
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1006
+	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
1007 1007
 		return nom_fichier_copie_locale($source, $ext);
1008 1008
 	}
1009 1009
 
1010
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1010
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
1011 1011
 	return null;
1012 1012
 }
1013 1013
 
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 		} else {
1110 1110
 			if ($a['body']) {
1111 1111
 				$a['extension'] = corriger_extension($extension);
1112
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1112
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1113 1113
 				ecrire_fichier($a['fichier'], $a['body']);
1114 1114
 				$size_image = @spip_getimagesize($a['fichier']);
1115 1115
 				$a['largeur'] = (int) $size_image[0];
@@ -1181,20 +1181,20 @@  discard block
 block discarded – undo
1181 1181
 	$t = null;
1182 1182
 	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1183 1183
 		if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1184
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1184
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1185 1185
 		}
1186 1186
 		if (
1187 1187
 			!$t
1188 1188
 			&& preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1189 1189
 			&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1190 1190
 		) {
1191
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1191
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1192 1192
 		}
1193 1193
 	}
1194 1194
 
1195 1195
 	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1196 1196
 	if (!$t) {
1197
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1197
+		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1198 1198
 	}
1199 1199
 
1200 1200
 	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1205,11 +1205,11 @@  discard block
 block discarded – undo
1205 1205
 		&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1206 1206
 	) {
1207 1207
 		# eviter xxx.3 => 3gp (> SPIP 3)
1208
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1208
+		$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1209 1209
 	}
1210 1210
 
1211 1211
 	if ($t) {
1212
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1212
+		spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1213 1213
 		return $t['extension'];
1214 1214
 	} else {
1215 1215
 		# par defaut on retombe sur '.bin' si c'est autorise
@@ -1312,7 +1312,7 @@  discard block
 block discarded – undo
1312 1312
 		}
1313 1313
 	} else {
1314 1314
 		$scheme = $t['scheme'];
1315
-		$noproxy = $scheme . '://';
1315
+		$noproxy = $scheme.'://';
1316 1316
 	}
1317 1317
 	if (isset($t['user'])) {
1318 1318
 		// user et pass doivent être passés en urlencodé dans l'URL, on redecode ici
@@ -1327,7 +1327,7 @@  discard block
 block discarded – undo
1327 1327
 	}
1328 1328
 
1329 1329
 	if (!empty($t['query'])) {
1330
-		$path .= '?' . $t['query'];
1330
+		$path .= '?'.$t['query'];
1331 1331
 	}
1332 1332
 
1333 1333
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1401,29 +1401,29 @@  discard block
 block discarded – undo
1401 1401
 	$proxy_user = '';
1402 1402
 	$http_proxy = need_proxy($host);
1403 1403
 	if ($user) {
1404
-		$user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1404
+		$user = urlencode((string) $user[0]).':'.urlencode((string) $user[1]);
1405 1405
 	}
1406 1406
 
1407 1407
 	$connect = '';
1408 1408
 	if ($http_proxy) {
1409
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1410
-			$path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1411
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1409
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls', 'ssl'])) {
1410
+			$path_host = ($user ? "$user@" : '').$host.(($port != 80) ? ":$port" : '');
1411
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1412 1412
 				. "Host: $path_host\r\n"
1413 1413
 				. "Proxy-Connection: Keep-Alive\r\n";
1414 1414
 		} else {
1415
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1415
+			$path = (in_array($scheme, ['tls', 'ssl']) ? 'https://' : "$scheme://")
1416 1416
 				. ($user ? "$user@" : '')
1417
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1417
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1418 1418
 		}
1419 1419
 		$t2 = @parse_url($http_proxy);
1420 1420
 		$first_host = $t2['host'];
1421 1421
 		$first_port = ($t2['port'] ?? null) ?: 80;
1422 1422
 		if ($t2['user'] ?? null) {
1423
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1423
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1424 1424
 		}
1425 1425
 	} else {
1426
-		$first_host = $noproxy . $host;
1426
+		$first_host = $noproxy.$host;
1427 1427
 		$first_port = $port;
1428 1428
 	}
1429 1429
 
@@ -1446,7 +1446,7 @@  discard block
 block discarded – undo
1446 1446
 		);
1447 1447
 		spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1448 1448
 		if (!$f) {
1449
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1449
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1450 1450
 			return $errno;
1451 1451
 		}
1452 1452
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
 			|| ($res = explode(' ', $res)) === []
1460 1460
 			|| $res[1] !== '200'
1461 1461
 		) {
1462
-			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1462
+			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect'._LOG_INFO_IMPORTANTE);
1463 1463
 			fclose($f);
1464 1464
 
1465 1465
 			return false;
@@ -1476,7 +1476,7 @@  discard block
 block discarded – undo
1476 1476
 		} while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1477 1477
 		spip_log("Recuperer $path sur $first_host:$first_port par $f");
1478 1478
 		if (!$f) {
1479
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1479
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1480 1480
 
1481 1481
 			return $errno;
1482 1482
 		}
@@ -1486,16 +1486,16 @@  discard block
 block discarded – undo
1486 1486
 	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1487 1487
 
1488 1488
 	$host_port = $host;
1489
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1489
+	if ($port != (in_array($scheme, ['tls', 'ssl']) ? 443 : 80)) {
1490 1490
 		$host_port .= ":$port";
1491 1491
 	}
1492 1492
 	$req = "$method $path $vers\r\n"
1493 1493
 		. "Host: $host_port\r\n"
1494
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1495
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1494
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1495
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1496 1496
 		. ($site ? "Referer: $site/$referer\r\n" : '')
1497
-		. ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1498
-		. ($user ? 'Authorization: Basic ' . base64_encode(urldecode($user)) . "\r\n" : '')
1497
+		. ($date ? 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n") : '')
1498
+		. ($user ? 'Authorization: Basic '.base64_encode(urldecode($user))."\r\n" : '')
1499 1499
 		. ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1500 1500
 		. (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1501 1501
 
Please login to merge, or discard this patch.
Indentation   +1131 added lines, -1131 removed lines patch added patch discarded remove patch
@@ -17,32 +17,32 @@  discard block
 block discarded – undo
17 17
  * @package SPIP\Core\Distant
18 18
  **/
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
24
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
25 25
 }
26 26
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
27
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28 28
 }
29 29
 if (!defined('_INC_DISTANT_USER_AGENT')) {
30
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31 31
 }
32 32
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
33
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
33
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
34 34
 }
35 35
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
36
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37 37
 }
38 38
 
39 39
 define('_REGEXP_COPIE_LOCALE', ',' 	.
40
-	preg_replace(
41
-		'@^https?:@',
42
-		'https?:',
43
-		($GLOBALS['meta']['adresse_site'] ?? '')
44
-	)
45
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
40
+    preg_replace(
41
+        '@^https?:@',
42
+        'https?:',
43
+        ($GLOBALS['meta']['adresse_site'] ?? '')
44
+    )
45
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
46 46
 
47 47
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
48 48
 
@@ -71,105 +71,105 @@  discard block
 block discarded – undo
71 71
  */
72 72
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
73 73
 
74
-	// si c'est la protection de soi-meme, retourner le path
75
-	if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
-		$source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
-
78
-		return @file_exists($source) ? $source : false;
79
-	}
80
-
81
-	if (is_null($local)) {
82
-		$local = fichier_copie_locale($source);
83
-	} else {
84
-		if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
-			$local = substr($local, strlen((string) _DIR_RACINE));
86
-		}
87
-	}
88
-
89
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
-	// par exemple un fichier qui ne figure pas dans nos documents ;
91
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
-	if (!$local) {
93
-		return false;
94
-	}
95
-
96
-	$localrac = _DIR_RACINE . $local;
97
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
98
-
99
-	// test d'existence du fichier
100
-	if ($mode === 'test') {
101
-		return $t ? $local : '';
102
-	}
103
-
104
-	// sinon voir si on doit/peut le telecharger
105
-	if ($local === $source || !tester_url_absolue($source)) {
106
-		return $t ? $local : '';
107
-	}
108
-
109
-	if ($mode === 'modif' || !$t) {
110
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
-		// et des eventuelles recuperations concurantes
112
-		include_spip('inc/acces');
113
-		if (!$taille_max) {
114
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
115
-		}
116
-		$localrac_tmp = $localrac . '.tmp';
117
-		$res = recuperer_url(
118
-			$source,
119
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
-		);
121
-
122
-		if (!$res || !$res['length'] && $res['status'] != 304) {
123
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
-			@unlink($localrac_tmp);
125
-		} else {
126
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
-		}
128
-		if (!$res || !$res['length']) {
129
-			// si $t c'est sans doute juste un not-modified-since
130
-			return $t ? $local : false;
131
-		}
132
-
133
-		// si option valider url, verifions que l'URL finale est acceptable
134
-		if (
135
-			$callback_valider_url
136
-			&& is_callable($callback_valider_url)
137
-			&& !$callback_valider_url($res['url'])
138
-		) {
139
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
-			@unlink($localrac_tmp);
141
-			return $t ? $local : false;
142
-		}
143
-
144
-		// on peut renommer le fichier tmp
145
-		@rename($localrac_tmp, $localrac);
146
-
147
-		// si on retrouve l'extension
148
-		if (
149
-			!empty($res['headers'])
150
-			&& ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
151
-			&& ($sanitizer = charger_fonction($extension, 'sanitizer', true))
152
-		) {
153
-			$sanitizer($localrac);
154
-		}
155
-
156
-		// pour une eventuelle indexation
157
-		pipeline(
158
-			'post_edition',
159
-			[
160
-				'args' => [
161
-					'operation' => 'copie_locale',
162
-					'source' => $source,
163
-					'fichier' => $local,
164
-					'http_res' => $res['length'],
165
-					'url' => $res['url'],
166
-				],
167
-				'data' => null
168
-			]
169
-		);
170
-	}
171
-
172
-	return $local;
74
+    // si c'est la protection de soi-meme, retourner le path
75
+    if ($mode !== 'force' && preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
76
+        $source = substr((string) _DIR_IMG, strlen((string) _DIR_RACINE)) . urldecode($match[1]);
77
+
78
+        return @file_exists($source) ? $source : false;
79
+    }
80
+
81
+    if (is_null($local)) {
82
+        $local = fichier_copie_locale($source);
83
+    } else {
84
+        if (_DIR_RACINE && strncmp((string) _DIR_RACINE, $local, strlen((string) _DIR_RACINE)) == 0) {
85
+            $local = substr($local, strlen((string) _DIR_RACINE));
86
+        }
87
+    }
88
+
89
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
90
+    // par exemple un fichier qui ne figure pas dans nos documents ;
91
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
92
+    if (!$local) {
93
+        return false;
94
+    }
95
+
96
+    $localrac = _DIR_RACINE . $local;
97
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
98
+
99
+    // test d'existence du fichier
100
+    if ($mode === 'test') {
101
+        return $t ? $local : '';
102
+    }
103
+
104
+    // sinon voir si on doit/peut le telecharger
105
+    if ($local === $source || !tester_url_absolue($source)) {
106
+        return $t ? $local : '';
107
+    }
108
+
109
+    if ($mode === 'modif' || !$t) {
110
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
111
+        // et des eventuelles recuperations concurantes
112
+        include_spip('inc/acces');
113
+        if (!$taille_max) {
114
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
115
+        }
116
+        $localrac_tmp = $localrac . '.tmp';
117
+        $res = recuperer_url(
118
+            $source,
119
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
120
+        );
121
+
122
+        if (!$res || !$res['length'] && $res['status'] != 304) {
123
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
+            @unlink($localrac_tmp);
125
+        } else {
126
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127
+        }
128
+        if (!$res || !$res['length']) {
129
+            // si $t c'est sans doute juste un not-modified-since
130
+            return $t ? $local : false;
131
+        }
132
+
133
+        // si option valider url, verifions que l'URL finale est acceptable
134
+        if (
135
+            $callback_valider_url
136
+            && is_callable($callback_valider_url)
137
+            && !$callback_valider_url($res['url'])
138
+        ) {
139
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
140
+            @unlink($localrac_tmp);
141
+            return $t ? $local : false;
142
+        }
143
+
144
+        // on peut renommer le fichier tmp
145
+        @rename($localrac_tmp, $localrac);
146
+
147
+        // si on retrouve l'extension
148
+        if (
149
+            !empty($res['headers'])
150
+            && ($extension = distant_trouver_extension_selon_headers($source, $res['headers']))
151
+            && ($sanitizer = charger_fonction($extension, 'sanitizer', true))
152
+        ) {
153
+            $sanitizer($localrac);
154
+        }
155
+
156
+        // pour une eventuelle indexation
157
+        pipeline(
158
+            'post_edition',
159
+            [
160
+                'args' => [
161
+                    'operation' => 'copie_locale',
162
+                    'source' => $source,
163
+                    'fichier' => $local,
164
+                    'http_res' => $res['length'],
165
+                    'url' => $res['url'],
166
+                ],
167
+                'data' => null
168
+            ]
169
+        );
170
+    }
171
+
172
+    return $local;
173 173
 }
174 174
 
175 175
 /**
@@ -184,97 +184,97 @@  discard block
 block discarded – undo
184 184
  *   url ou false en cas d'echec
185 185
  */
186 186
 function valider_url_distante($url, $known_hosts = []) {
187
-	if (!function_exists('protocole_verifier')) {
188
-		include_spip('inc/filtres_mini');
189
-	}
190
-
191
-	if (!protocole_verifier($url, ['http', 'https'])) {
192
-		return false;
193
-	}
194
-
195
-	$parsed_url = parse_url($url);
196
-	if (!$parsed_url || empty($parsed_url['host'])) {
197
-		return false;
198
-	}
199
-
200
-	if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
201
-		return false;
202
-	}
203
-
204
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
205
-		return false;
206
-	}
207
-
208
-	if (!is_array($known_hosts)) {
209
-		$known_hosts = [$known_hosts];
210
-	}
211
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
212
-	$known_hosts[] = url_de_base();
213
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
214
-
215
-	$is_known_host = false;
216
-	foreach ($known_hosts as $known_host) {
217
-		$parse_known = parse_url((string) $known_host);
218
-		if (
219
-			$parse_known
220
-			&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
221
-		) {
222
-			$is_known_host = true;
223
-			break;
224
-		}
225
-	}
226
-
227
-	if (!$is_known_host) {
228
-		$host = trim($parsed_url['host'], '.');
229
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
230
-			$ip = gethostbyname($host);
231
-			if ($ip === $host) {
232
-				// Error condition for gethostbyname()
233
-				$ip = false;
234
-			}
235
-			if ($records = dns_get_record($host)) {
236
-				foreach ($records as $record) {
237
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
238
-					// se fasse sur la meme IP
239
-					if ($record['ttl'] < 10) {
240
-						$ip = false;
241
-						break;
242
-					}
243
-				}
244
-			}
245
-			else {
246
-				$ip = false;
247
-			}
248
-		}
249
-		if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250
-			return false;
251
-		}
252
-	}
253
-
254
-	if (empty($parsed_url['port'])) {
255
-		return $url;
256
-	}
257
-
258
-	$port = $parsed_url['port'];
259
-	if ($port === 80 || $port === 443 || $port === 8080) {
260
-		return $url;
261
-	}
262
-
263
-	if ($is_known_host) {
264
-		foreach ($known_hosts as $known_host) {
265
-			$parse_known = parse_url((string) $known_host);
266
-			if (
267
-				$parse_known
268
-				&& !empty($parse_known['port'])
269
-				&& strtolower($parse_known['host']) === strtolower($parsed_url['host'])
270
-				&& $parse_known['port'] == $port
271
-			) {
272
-				return $url;
273
-			}
274
-		}
275
-	}
276
-
277
-	return false;
187
+    if (!function_exists('protocole_verifier')) {
188
+        include_spip('inc/filtres_mini');
189
+    }
190
+
191
+    if (!protocole_verifier($url, ['http', 'https'])) {
192
+        return false;
193
+    }
194
+
195
+    $parsed_url = parse_url($url);
196
+    if (!$parsed_url || empty($parsed_url['host'])) {
197
+        return false;
198
+    }
199
+
200
+    if (isset($parsed_url['user']) || isset($parsed_url['pass'])) {
201
+        return false;
202
+    }
203
+
204
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
205
+        return false;
206
+    }
207
+
208
+    if (!is_array($known_hosts)) {
209
+        $known_hosts = [$known_hosts];
210
+    }
211
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
212
+    $known_hosts[] = url_de_base();
213
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
214
+
215
+    $is_known_host = false;
216
+    foreach ($known_hosts as $known_host) {
217
+        $parse_known = parse_url((string) $known_host);
218
+        if (
219
+            $parse_known
220
+            && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
221
+        ) {
222
+            $is_known_host = true;
223
+            break;
224
+        }
225
+    }
226
+
227
+    if (!$is_known_host) {
228
+        $host = trim($parsed_url['host'], '.');
229
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
230
+            $ip = gethostbyname($host);
231
+            if ($ip === $host) {
232
+                // Error condition for gethostbyname()
233
+                $ip = false;
234
+            }
235
+            if ($records = dns_get_record($host)) {
236
+                foreach ($records as $record) {
237
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
238
+                    // se fasse sur la meme IP
239
+                    if ($record['ttl'] < 10) {
240
+                        $ip = false;
241
+                        break;
242
+                    }
243
+                }
244
+            }
245
+            else {
246
+                $ip = false;
247
+            }
248
+        }
249
+        if ($ip && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
250
+            return false;
251
+        }
252
+    }
253
+
254
+    if (empty($parsed_url['port'])) {
255
+        return $url;
256
+    }
257
+
258
+    $port = $parsed_url['port'];
259
+    if ($port === 80 || $port === 443 || $port === 8080) {
260
+        return $url;
261
+    }
262
+
263
+    if ($is_known_host) {
264
+        foreach ($known_hosts as $known_host) {
265
+            $parse_known = parse_url((string) $known_host);
266
+            if (
267
+                $parse_known
268
+                && !empty($parse_known['port'])
269
+                && strtolower($parse_known['host']) === strtolower($parsed_url['host'])
270
+                && $parse_known['port'] == $port
271
+            ) {
272
+                return $url;
273
+            }
274
+        }
275
+    }
276
+
277
+    return false;
278 278
 }
279 279
 
280 280
 /**
@@ -294,87 +294,87 @@  discard block
 block discarded – undo
294 294
  */
295 295
 function prepare_donnees_post($donnees, $boundary = '') {
296 296
 
297
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
298
-	// pour un appel soap par exemple
299
-	// l'entete est separe des donnees par un double retour a la ligne
300
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
301
-	$chaine = '';
302
-	if (is_string($donnees) && strlen($donnees)) {
303
-		$entete = '';
304
-		// on repasse tous les \r\n et \r en simples \n
305
-		$donnees = str_replace("\r\n", "\n", $donnees);
306
-		$donnees = str_replace("\r", "\n", $donnees);
307
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
308
-		$p = strpos($donnees, "\n\n");
309
-		if ($p !== false) {
310
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
311
-			$donnees = substr($donnees, $p + 2);
312
-		}
313
-		$chaine = str_replace("\n", "\r\n", $donnees);
314
-	} else {
315
-		/* boundary automatique */
316
-		// Si on a plus de 500 octects de donnees, on "boundarise"
317
-		if ($boundary === '') {
318
-			$taille = 0;
319
-			foreach ($donnees as $cle => $valeur) {
320
-				if (is_array($valeur)) {
321
-					foreach ($valeur as $val2) {
322
-						$taille += strlen((string) $val2);
323
-					}
324
-				} else {
325
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
326
-					$taille += strlen((string) $valeur);
327
-				}
328
-			}
329
-			if ($taille > 500) {
330
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
331
-			}
332
-		}
333
-
334
-		if (is_string($boundary) && strlen($boundary)) {
335
-			// fabrique une chaine HTTP pour un POST avec boundary
336
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
337
-			if (is_array($donnees)) {
338
-				foreach ($donnees as $cle => $valeur) {
339
-					if (is_array($valeur)) {
340
-						foreach ($valeur as $val2) {
341
-							$chaine .= "\r\n--$boundary\r\n";
342
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
343
-							$chaine .= "\r\n";
344
-							$chaine .= $val2;
345
-						}
346
-					} else {
347
-						$chaine .= "\r\n--$boundary\r\n";
348
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
349
-						$chaine .= "\r\n";
350
-						$chaine .= $valeur;
351
-					}
352
-				}
353
-				$chaine .= "\r\n--$boundary\r\n";
354
-			}
355
-		} else {
356
-			// fabrique une chaine HTTP simple pour un POST
357
-			$entete = "Content-Type: application/x-www-form-urlencoded\r\n";
358
-			if (is_array($donnees)) {
359
-				$chaines = [];
360
-				foreach ($donnees as $cle => $valeur) {
361
-					if (is_array($valeur)) {
362
-						foreach ($valeur as $val2) {
363
-							$chaines[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
364
-						}
365
-					} else {
366
-						$chaines[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
367
-					}
368
-				}
369
-				$chaine = implode('&', $chaines);
370
-				unset($chaines);
371
-			} else {
372
-				$chaine = $donnees;
373
-			}
374
-		}
375
-	}
376
-
377
-	return [$entete, $chaine];
297
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
298
+    // pour un appel soap par exemple
299
+    // l'entete est separe des donnees par un double retour a la ligne
300
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
301
+    $chaine = '';
302
+    if (is_string($donnees) && strlen($donnees)) {
303
+        $entete = '';
304
+        // on repasse tous les \r\n et \r en simples \n
305
+        $donnees = str_replace("\r\n", "\n", $donnees);
306
+        $donnees = str_replace("\r", "\n", $donnees);
307
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
308
+        $p = strpos($donnees, "\n\n");
309
+        if ($p !== false) {
310
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
311
+            $donnees = substr($donnees, $p + 2);
312
+        }
313
+        $chaine = str_replace("\n", "\r\n", $donnees);
314
+    } else {
315
+        /* boundary automatique */
316
+        // Si on a plus de 500 octects de donnees, on "boundarise"
317
+        if ($boundary === '') {
318
+            $taille = 0;
319
+            foreach ($donnees as $cle => $valeur) {
320
+                if (is_array($valeur)) {
321
+                    foreach ($valeur as $val2) {
322
+                        $taille += strlen((string) $val2);
323
+                    }
324
+                } else {
325
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
326
+                    $taille += strlen((string) $valeur);
327
+                }
328
+            }
329
+            if ($taille > 500) {
330
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
331
+            }
332
+        }
333
+
334
+        if (is_string($boundary) && strlen($boundary)) {
335
+            // fabrique une chaine HTTP pour un POST avec boundary
336
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
337
+            if (is_array($donnees)) {
338
+                foreach ($donnees as $cle => $valeur) {
339
+                    if (is_array($valeur)) {
340
+                        foreach ($valeur as $val2) {
341
+                            $chaine .= "\r\n--$boundary\r\n";
342
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
343
+                            $chaine .= "\r\n";
344
+                            $chaine .= $val2;
345
+                        }
346
+                    } else {
347
+                        $chaine .= "\r\n--$boundary\r\n";
348
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
349
+                        $chaine .= "\r\n";
350
+                        $chaine .= $valeur;
351
+                    }
352
+                }
353
+                $chaine .= "\r\n--$boundary\r\n";
354
+            }
355
+        } else {
356
+            // fabrique une chaine HTTP simple pour un POST
357
+            $entete = "Content-Type: application/x-www-form-urlencoded\r\n";
358
+            if (is_array($donnees)) {
359
+                $chaines = [];
360
+                foreach ($donnees as $cle => $valeur) {
361
+                    if (is_array($valeur)) {
362
+                        foreach ($valeur as $val2) {
363
+                            $chaines[] = rawurlencode($cle) . '[]=' . rawurlencode((string) $val2);
364
+                        }
365
+                    } else {
366
+                        $chaines[] = rawurlencode($cle) . '=' . rawurlencode((string) $valeur);
367
+                    }
368
+                }
369
+                $chaine = implode('&', $chaines);
370
+                unset($chaines);
371
+            } else {
372
+                $chaine = $donnees;
373
+            }
374
+        }
375
+    }
376
+
377
+    return [$entete, $chaine];
378 378
 }
379 379
 
380 380
 /**
@@ -385,19 +385,19 @@  discard block
 block discarded – undo
385 385
  */
386 386
 function url_to_ascii($url_idn) {
387 387
 
388
-	if ($parts = parse_url($url_idn)) {
389
-		$host = $parts['host'];
390
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
-			$converter = new ToIdn();
392
-			$host_ascii = $converter->convert($host);
393
-			$url_idn = explode($host, $url_idn, 2);
394
-			$url_idn = implode($host_ascii, $url_idn);
395
-		}
396
-		// et on urlencode les char utf si besoin dans le path
397
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
-	}
399
-
400
-	return $url_idn;
388
+    if ($parts = parse_url($url_idn)) {
389
+        $host = $parts['host'];
390
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
391
+            $converter = new ToIdn();
392
+            $host_ascii = $converter->convert($host);
393
+            $url_idn = explode($host, $url_idn, 2);
394
+            $url_idn = implode($host_ascii, $url_idn);
395
+        }
396
+        // et on urlencode les char utf si besoin dans le path
397
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode((string) $match[0]), $url_idn);
398
+    }
399
+
400
+    return $url_idn;
401 401
 }
402 402
 
403 403
 /**
@@ -439,228 +439,228 @@  discard block
 block discarded – undo
439 439
  *     string file : nom du fichier si enregistre dans un fichier
440 440
  */
441 441
 function recuperer_url($url, $options = []) {
442
-	// Conserve la mémoire de la méthode fournit éventuellement
443
-	$methode_demandee = $options['methode'] ?? '';
444
-	$default = [
445
-		'transcoder' => false,
446
-		'methode' => 'GET',
447
-		'taille_max' => null,
448
-		'headers' => [],
449
-		'datas' => '',
450
-		'boundary' => '',
451
-		'refuser_gz' => false,
452
-		'if_modified_since' => '',
453
-		'uri_referer' => '',
454
-		'file' => '',
455
-		'follow_location' => 10,
456
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
457
-	];
458
-	$options = array_merge($default, $options);
459
-	// copier directement dans un fichier ?
460
-	$copy = $options['file'];
461
-
462
-	if ($options['methode'] == 'HEAD') {
463
-		$options['taille_max'] = 0;
464
-	}
465
-	if (is_null($options['taille_max'])) {
466
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
467
-	}
468
-
469
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
470
-
471
-	// Ajout des en-têtes spécifiques si besoin
472
-	$formatted_data = '';
473
-	if (!empty($options['headers'])) {
474
-		foreach ($options['headers'] as $champ => $valeur) {
475
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
476
-		}
477
-	}
478
-
479
-	if (!empty($options['datas'])) {
480
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
481
-		$head .= $formatted_data;
482
-		if (stripos($head, 'Content-Length:') === false) {
483
-			$head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
484
-		}
485
-		$formatted_data = $head . "\r\n" . $postdata;
486
-		if (
487
-			strlen((string) $postdata) && !$methode_demandee
488
-		) {
489
-			$options['methode'] = 'POST';
490
-		}
491
-	} elseif ($formatted_data) {
492
-		$formatted_data .= "\r\n";
493
-	}
494
-
495
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
496
-	$url = preg_replace(',^feed://,i', 'http://', $url);
497
-	if (!tester_url_absolue($url)) {
498
-		$url = 'http://' . $url;
499
-	} elseif (str_starts_with($url, '//')) {
500
-		$url = 'http:' . $url;
501
-	}
502
-
503
-	$url = url_to_ascii($url);
504
-
505
-	$result = [
506
-		'status' => 0,
507
-		'headers' => '',
508
-		'page' => '',
509
-		'length' => 0,
510
-		'last_modified' => '',
511
-		'location' => '',
512
-		'url' => $url
513
-	];
514
-
515
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
516
-	$refuser_gz = ($options['refuser_gz'] || $copy);
517
-
518
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
519
-	[$handle, $fopen] = init_http(
520
-		$options['methode'],
521
-		$url,
522
-		$refuser_gz,
523
-		$options['uri_referer'],
524
-		$formatted_data,
525
-		$options['version_http'],
526
-		$options['if_modified_since']
527
-	);
528
-	if (!$handle) {
529
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
530
-
531
-		return false;
532
-	}
533
-
534
-	// Sauf en fopen, envoyer le flux d'entree
535
-	// et recuperer les en-tetes de reponses
536
-	if (!$fopen) {
537
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
538
-		if (!$res) {
539
-			fclose($handle);
540
-			$t = @parse_url($url);
541
-			$host = $t['host'];
542
-			// Chinoisierie inexplicable pour contrer
543
-			// les actions liberticides de l'empire du milieu
544
-			if (
545
-				!need_proxy($host)
546
-				&& ($res = @file_get_contents($url))
547
-			) {
548
-				$result['length'] = strlen($res);
549
-				if ($copy) {
550
-					ecrire_fichier($copy, $res);
551
-					$result['file'] = $copy;
552
-				} else {
553
-					$result['page'] = $res;
554
-				}
555
-				$res = [
556
-					'status' => 200,
557
-				];
558
-			} else {
559
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
560
-				return false;
561
-			}
562
-		} elseif ($res['location'] && $options['follow_location']) {
563
-			$options['follow_location']--;
564
-			fclose($handle);
565
-			include_spip('inc/filtres');
566
-			$url = suivre_lien($url, $res['location']);
567
-
568
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
569
-			if (
570
-				$options['methode'] !== 'GET'
571
-				&& (empty($res['status']) || !in_array($res['status'], [307, 308]))
572
-			) {
573
-				$options['methode'] = 'GET';
574
-				$options['datas'] = '';
575
-			}
576
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
577
-
578
-			return recuperer_url($url, $options);
579
-		} elseif ($res['status'] !== 200) {
580
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
581
-		}
582
-		$result['status'] = $res['status'];
583
-		if (isset($res['headers'])) {
584
-			$result['headers'] = $res['headers'];
585
-		}
586
-		if (isset($res['last_modified'])) {
587
-			$result['last_modified'] = $res['last_modified'];
588
-		}
589
-		if (isset($res['location'])) {
590
-			$result['location'] = $res['location'];
591
-		}
592
-		if (isset($res['content_length'])) {
593
-			$result['content_length'] = $res['content_length'];
594
-		}
595
-	}
596
-
597
-	// on ne veut que les entetes
598
-	if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
600
-		return $result;
601
-	}
602
-
603
-
604
-	// s'il faut deballer, le faire via un fichier temporaire
605
-	// sinon la memoire explose pour les gros flux
606
-
607
-	$gz = false;
608
-	if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
609
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
-	}
611
-
612
-	// si on n'a pas deja récupéré le contenu par une methode detournée
613
-	if (!$result['length']) {
614
-		$taille_max = $options['taille_max'];
615
-		if (isset($result['content_length'])
616
-		  && !empty($result['content_length'])
617
-		  && ($result['content_length'] < $taille_max)) {
618
-			$taille_max = $result['content_length'];
619
-		}
620
-		$res = recuperer_body($handle, $taille_max, $gz ?: $copy);
621
-		fclose($handle);
622
-		if ($copy) {
623
-			$result['length'] = $res;
624
-			$result['file'] = $copy;
625
-		} elseif ($res) {
626
-			$result['page'] = &$res;
627
-			$result['length'] = strlen($result['page']);
628
-		}
629
-		if (!$result['status']) {
630
-			$result['status'] = 200; // on a reussi, donc !
631
-		}
632
-	}
633
-	if (!$result['page']) {
634
-		return $result;
635
-	}
636
-
637
-	// Decompresser au besoin
638
-	if ($gz) {
639
-		$result['page'] = implode('', gzfile($gz));
640
-		$result['length'] = strlen($result['page']);
641
-		// et annuler le content-length qui correspond à la version gzip
642
-		if (isset($result['content_length'])) {
643
-			unset($result['content_length']);
644
-		}
645
-		supprimer_fichier($gz);
646
-	}
647
-
648
-	// Faut-il l'importer dans notre charset local ?
649
-	if ($options['transcoder']) {
650
-		include_spip('inc/charsets');
651
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
652
-	}
653
-
654
-	try {
655
-		$trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
656
-	} catch (JsonException $e) {
657
-		$trace = [];
658
-		spip_log('Failed to parse Json data : ' . $e->getMessage(), _LOG_ERREUR);
659
-	}
660
-	$trace['page'] = '...';
661
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
662
-
663
-	return $result;
442
+    // Conserve la mémoire de la méthode fournit éventuellement
443
+    $methode_demandee = $options['methode'] ?? '';
444
+    $default = [
445
+        'transcoder' => false,
446
+        'methode' => 'GET',
447
+        'taille_max' => null,
448
+        'headers' => [],
449
+        'datas' => '',
450
+        'boundary' => '',
451
+        'refuser_gz' => false,
452
+        'if_modified_since' => '',
453
+        'uri_referer' => '',
454
+        'file' => '',
455
+        'follow_location' => 10,
456
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
457
+    ];
458
+    $options = array_merge($default, $options);
459
+    // copier directement dans un fichier ?
460
+    $copy = $options['file'];
461
+
462
+    if ($options['methode'] == 'HEAD') {
463
+        $options['taille_max'] = 0;
464
+    }
465
+    if (is_null($options['taille_max'])) {
466
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
467
+    }
468
+
469
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
470
+
471
+    // Ajout des en-têtes spécifiques si besoin
472
+    $formatted_data = '';
473
+    if (!empty($options['headers'])) {
474
+        foreach ($options['headers'] as $champ => $valeur) {
475
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
476
+        }
477
+    }
478
+
479
+    if (!empty($options['datas'])) {
480
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
481
+        $head .= $formatted_data;
482
+        if (stripos($head, 'Content-Length:') === false) {
483
+            $head .= 'Content-Length: ' . strlen((string) $postdata) . "\r\n";
484
+        }
485
+        $formatted_data = $head . "\r\n" . $postdata;
486
+        if (
487
+            strlen((string) $postdata) && !$methode_demandee
488
+        ) {
489
+            $options['methode'] = 'POST';
490
+        }
491
+    } elseif ($formatted_data) {
492
+        $formatted_data .= "\r\n";
493
+    }
494
+
495
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
496
+    $url = preg_replace(',^feed://,i', 'http://', $url);
497
+    if (!tester_url_absolue($url)) {
498
+        $url = 'http://' . $url;
499
+    } elseif (str_starts_with($url, '//')) {
500
+        $url = 'http:' . $url;
501
+    }
502
+
503
+    $url = url_to_ascii($url);
504
+
505
+    $result = [
506
+        'status' => 0,
507
+        'headers' => '',
508
+        'page' => '',
509
+        'length' => 0,
510
+        'last_modified' => '',
511
+        'location' => '',
512
+        'url' => $url
513
+    ];
514
+
515
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
516
+    $refuser_gz = ($options['refuser_gz'] || $copy);
517
+
518
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
519
+    [$handle, $fopen] = init_http(
520
+        $options['methode'],
521
+        $url,
522
+        $refuser_gz,
523
+        $options['uri_referer'],
524
+        $formatted_data,
525
+        $options['version_http'],
526
+        $options['if_modified_since']
527
+    );
528
+    if (!$handle) {
529
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
530
+
531
+        return false;
532
+    }
533
+
534
+    // Sauf en fopen, envoyer le flux d'entree
535
+    // et recuperer les en-tetes de reponses
536
+    if (!$fopen) {
537
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
538
+        if (!$res) {
539
+            fclose($handle);
540
+            $t = @parse_url($url);
541
+            $host = $t['host'];
542
+            // Chinoisierie inexplicable pour contrer
543
+            // les actions liberticides de l'empire du milieu
544
+            if (
545
+                !need_proxy($host)
546
+                && ($res = @file_get_contents($url))
547
+            ) {
548
+                $result['length'] = strlen($res);
549
+                if ($copy) {
550
+                    ecrire_fichier($copy, $res);
551
+                    $result['file'] = $copy;
552
+                } else {
553
+                    $result['page'] = $res;
554
+                }
555
+                $res = [
556
+                    'status' => 200,
557
+                ];
558
+            } else {
559
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
560
+                return false;
561
+            }
562
+        } elseif ($res['location'] && $options['follow_location']) {
563
+            $options['follow_location']--;
564
+            fclose($handle);
565
+            include_spip('inc/filtres');
566
+            $url = suivre_lien($url, $res['location']);
567
+
568
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
569
+            if (
570
+                $options['methode'] !== 'GET'
571
+                && (empty($res['status']) || !in_array($res['status'], [307, 308]))
572
+            ) {
573
+                $options['methode'] = 'GET';
574
+                $options['datas'] = '';
575
+            }
576
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
577
+
578
+            return recuperer_url($url, $options);
579
+        } elseif ($res['status'] !== 200) {
580
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
581
+        }
582
+        $result['status'] = $res['status'];
583
+        if (isset($res['headers'])) {
584
+            $result['headers'] = $res['headers'];
585
+        }
586
+        if (isset($res['last_modified'])) {
587
+            $result['last_modified'] = $res['last_modified'];
588
+        }
589
+        if (isset($res['location'])) {
590
+            $result['location'] = $res['location'];
591
+        }
592
+        if (isset($res['content_length'])) {
593
+            $result['content_length'] = $res['content_length'];
594
+        }
595
+    }
596
+
597
+    // on ne veut que les entetes
598
+    if (!$options['taille_max'] || $options['methode'] == 'HEAD' || $result['status'] == '304') {
599
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
600
+        return $result;
601
+    }
602
+
603
+
604
+    // s'il faut deballer, le faire via un fichier temporaire
605
+    // sinon la memoire explose pour les gros flux
606
+
607
+    $gz = false;
608
+    if (preg_match(",\bContent-Encoding: .*gzip,is", (string) $result['headers'])) {
609
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
+    }
611
+
612
+    // si on n'a pas deja récupéré le contenu par une methode detournée
613
+    if (!$result['length']) {
614
+        $taille_max = $options['taille_max'];
615
+        if (isset($result['content_length'])
616
+          && !empty($result['content_length'])
617
+          && ($result['content_length'] < $taille_max)) {
618
+            $taille_max = $result['content_length'];
619
+        }
620
+        $res = recuperer_body($handle, $taille_max, $gz ?: $copy);
621
+        fclose($handle);
622
+        if ($copy) {
623
+            $result['length'] = $res;
624
+            $result['file'] = $copy;
625
+        } elseif ($res) {
626
+            $result['page'] = &$res;
627
+            $result['length'] = strlen($result['page']);
628
+        }
629
+        if (!$result['status']) {
630
+            $result['status'] = 200; // on a reussi, donc !
631
+        }
632
+    }
633
+    if (!$result['page']) {
634
+        return $result;
635
+    }
636
+
637
+    // Decompresser au besoin
638
+    if ($gz) {
639
+        $result['page'] = implode('', gzfile($gz));
640
+        $result['length'] = strlen($result['page']);
641
+        // et annuler le content-length qui correspond à la version gzip
642
+        if (isset($result['content_length'])) {
643
+            unset($result['content_length']);
644
+        }
645
+        supprimer_fichier($gz);
646
+    }
647
+
648
+    // Faut-il l'importer dans notre charset local ?
649
+    if ($options['transcoder']) {
650
+        include_spip('inc/charsets');
651
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
652
+    }
653
+
654
+    try {
655
+        $trace = json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
656
+    } catch (JsonException $e) {
657
+        $trace = [];
658
+        spip_log('Failed to parse Json data : ' . $e->getMessage(), _LOG_ERREUR);
659
+    }
660
+    $trace['page'] = '...';
661
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace, JSON_THROW_ON_ERROR), 'distant' . _LOG_DEBUG);
662
+
663
+    return $result;
664 664
 }
665 665
 
666 666
 /**
@@ -676,73 +676,73 @@  discard block
 block discarded – undo
676 676
  * @return array|bool|mixed
677 677
  */
678 678
 function recuperer_url_cache($url, $options = []) {
679
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
680
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
681
-	}
682
-	$default = [
683
-		'transcoder' => false,
684
-		'methode' => 'GET',
685
-		'taille_max' => null,
686
-		'datas' => '',
687
-		'boundary' => '',
688
-		'refuser_gz' => false,
689
-		'if_modified_since' => '',
690
-		'uri_referer' => '',
691
-		'file' => '',
692
-		'follow_location' => 10,
693
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
694
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
695
-	];
696
-	$options = array_merge($default, $options);
697
-
698
-	// cas ou il n'est pas possible de cacher
699
-	if (!empty($options['data']) || $options['methode'] == 'POST') {
700
-		return recuperer_url($url, $options);
701
-	}
702
-
703
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
704
-	static $errors = [];
705
-	if (isset($errors[$url])) {
706
-		return $errors[$url];
707
-	}
708
-
709
-	$sig = $options;
710
-	unset($sig['if_modified_since']);
711
-	unset($sig['delai_cache']);
712
-	$sig['url'] = $url;
713
-
714
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
715
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
716
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
717
-	$cache = "$sub$cache";
718
-
719
-	$res = false;
720
-	$is_cached = file_exists($cache);
721
-	if (
722
-		$is_cached
723
-		&& filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
724
-	) {
725
-		lire_fichier($cache, $res);
726
-		if ($res = unserialize($res)) {
727
-			// mettre le last_modified et le status=304 ?
728
-		}
729
-	}
730
-	if (!$res) {
731
-		$res = recuperer_url($url, $options);
732
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
733
-		if (!$res) {
734
-			if ($is_cached) {
735
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
736
-				lire_fichier($cache, $res);
737
-				$res = unserialize($res);
738
-			}
739
-
740
-			return $errors[$url] = $res;
741
-		}
742
-		ecrire_fichier($cache, serialize($res));
743
-	}
744
-
745
-	return $res;
679
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
680
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
681
+    }
682
+    $default = [
683
+        'transcoder' => false,
684
+        'methode' => 'GET',
685
+        'taille_max' => null,
686
+        'datas' => '',
687
+        'boundary' => '',
688
+        'refuser_gz' => false,
689
+        'if_modified_since' => '',
690
+        'uri_referer' => '',
691
+        'file' => '',
692
+        'follow_location' => 10,
693
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
694
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
695
+    ];
696
+    $options = array_merge($default, $options);
697
+
698
+    // cas ou il n'est pas possible de cacher
699
+    if (!empty($options['data']) || $options['methode'] == 'POST') {
700
+        return recuperer_url($url, $options);
701
+    }
702
+
703
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
704
+    static $errors = [];
705
+    if (isset($errors[$url])) {
706
+        return $errors[$url];
707
+    }
708
+
709
+    $sig = $options;
710
+    unset($sig['if_modified_since']);
711
+    unset($sig['delai_cache']);
712
+    $sig['url'] = $url;
713
+
714
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
715
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
716
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
717
+    $cache = "$sub$cache";
718
+
719
+    $res = false;
720
+    $is_cached = file_exists($cache);
721
+    if (
722
+        $is_cached
723
+        && filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache']
724
+    ) {
725
+        lire_fichier($cache, $res);
726
+        if ($res = unserialize($res)) {
727
+            // mettre le last_modified et le status=304 ?
728
+        }
729
+    }
730
+    if (!$res) {
731
+        $res = recuperer_url($url, $options);
732
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
733
+        if (!$res) {
734
+            if ($is_cached) {
735
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
736
+                lire_fichier($cache, $res);
737
+                $res = unserialize($res);
738
+            }
739
+
740
+            return $errors[$url] = $res;
741
+        }
742
+        ecrire_fichier($cache, serialize($res));
743
+    }
744
+
745
+    return $res;
746 746
 }
747 747
 
748 748
 /**
@@ -760,56 +760,56 @@  discard block
 block discarded – undo
760 760
  *   string contenu de la resource
761 761
  */
762 762
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
763
-	$tmpfile = null;
764
-	$taille = 0;
765
-	$result = '';
766
-	$fp = false;
767
-	if ($fichier) {
768
-		include_spip('inc/acces');
769
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
770
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
771
-		if (!$fp && file_exists($fichier)) {
772
-			return filesize($fichier);
773
-		}
774
-		if (!$fp) {
775
-			return false;
776
-		}
777
-		$result = 0; // on renvoie la taille du fichier
778
-	}
779
-
780
-	$max_longueur_morceaux = 8192;
781
-	while (!feof($handle) && $taille < $taille_max) {
782
-		// ne pas lire plus que ce qu'on a besoin (ou que la longueur annoncée du document)
783
-		$max_longueur_morceaux = min($max_longueur_morceaux, $taille_max - $taille);
784
-		$res = fread($handle, $max_longueur_morceaux);
785
-
786
-		// si feof ne trig pas mais on est à la fin, fread retourne false
787
-		if ($res === false) {
788
-			break;
789
-		}
790
-
791
-		$taille_morceau = strlen($res);
792
-		$taille += $taille_morceau;
793
-
794
-		if ($fp) {
795
-			fwrite($fp, $res);
796
-			$result = $taille;
797
-		} else {
798
-			$result .= $res;
799
-		}
800
-
801
-	}
802
-
803
-	if ($fp) {
804
-		spip_fclose_unlock($fp);
805
-		spip_unlink($fichier);
806
-		@rename($tmpfile, $fichier);
807
-		if (!file_exists($fichier)) {
808
-			return false;
809
-		}
810
-	}
811
-
812
-	return $result;
763
+    $tmpfile = null;
764
+    $taille = 0;
765
+    $result = '';
766
+    $fp = false;
767
+    if ($fichier) {
768
+        include_spip('inc/acces');
769
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
770
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
771
+        if (!$fp && file_exists($fichier)) {
772
+            return filesize($fichier);
773
+        }
774
+        if (!$fp) {
775
+            return false;
776
+        }
777
+        $result = 0; // on renvoie la taille du fichier
778
+    }
779
+
780
+    $max_longueur_morceaux = 8192;
781
+    while (!feof($handle) && $taille < $taille_max) {
782
+        // ne pas lire plus que ce qu'on a besoin (ou que la longueur annoncée du document)
783
+        $max_longueur_morceaux = min($max_longueur_morceaux, $taille_max - $taille);
784
+        $res = fread($handle, $max_longueur_morceaux);
785
+
786
+        // si feof ne trig pas mais on est à la fin, fread retourne false
787
+        if ($res === false) {
788
+            break;
789
+        }
790
+
791
+        $taille_morceau = strlen($res);
792
+        $taille += $taille_morceau;
793
+
794
+        if ($fp) {
795
+            fwrite($fp, $res);
796
+            $result = $taille;
797
+        } else {
798
+            $result .= $res;
799
+        }
800
+
801
+    }
802
+
803
+    if ($fp) {
804
+        spip_fclose_unlock($fp);
805
+        spip_unlink($fichier);
806
+        @rename($tmpfile, $fichier);
807
+        if (!file_exists($fichier)) {
808
+            return false;
809
+        }
810
+    }
811
+
812
+    return $result;
813 813
 }
814 814
 
815 815
 /**
@@ -831,38 +831,38 @@  discard block
 block discarded – undo
831 831
  *   string location
832 832
  */
833 833
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
834
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
835
-
836
-	$s = @trim(fgets($handle, 16384));
837
-	if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
838
-		return false;
839
-	}
840
-	$result['status'] = (int) $r[1];
841
-	while ($s = trim(fgets($handle, 16384))) {
842
-		$result['headers'][] = $s . "\n";
843
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
844
-		[, $d, $v] = $r;
845
-		$d = strtolower(trim($d));
846
-		if ( $d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
847
-			$result['location'] = $v;
848
-		} elseif ($d === 'last-modified') {
849
-			$result['last_modified'] = strtotime($v);
850
-		} elseif ($d === 'content-length' and strlen(trim($v))) {
851
-			$result['content_length'] = intval($v);
852
-		}
853
-	}
854
-	if (
855
-		$if_modified_since
856
-		&& $result['last_modified']
857
-		&& $if_modified_since > $result['last_modified']
858
-		&& $result['status'] == 200
859
-	) {
860
-		$result['status'] = 304;
861
-	}
862
-
863
-	$result['headers'] = implode('', $result['headers']);
864
-
865
-	return $result;
834
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
835
+
836
+    $s = @trim(fgets($handle, 16384));
837
+    if (!preg_match(',^HTTP/\d+\.\d+ (\d+),', $s, $r)) {
838
+        return false;
839
+    }
840
+    $result['status'] = (int) $r[1];
841
+    while ($s = trim(fgets($handle, 16384))) {
842
+        $result['headers'][] = $s . "\n";
843
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
844
+        [, $d, $v] = $r;
845
+        $d = strtolower(trim($d));
846
+        if ( $d === 'location' && $result['status'] >= 300 && $result['status'] < 400) {
847
+            $result['location'] = $v;
848
+        } elseif ($d === 'last-modified') {
849
+            $result['last_modified'] = strtotime($v);
850
+        } elseif ($d === 'content-length' and strlen(trim($v))) {
851
+            $result['content_length'] = intval($v);
852
+        }
853
+    }
854
+    if (
855
+        $if_modified_since
856
+        && $result['last_modified']
857
+        && $if_modified_since > $result['last_modified']
858
+        && $result['status'] == 200
859
+    ) {
860
+        $result['status'] = 304;
861
+    }
862
+
863
+    $result['headers'] = implode('', $result['headers']);
864
+
865
+    return $result;
866 866
 }
867 867
 
868 868
 /**
@@ -884,36 +884,36 @@  discard block
 block discarded – undo
884 884
  *     Nom du fichier pour copie locale
885 885
  **/
886 886
 function nom_fichier_copie_locale($source, $extension) {
887
-	include_spip('inc/documents');
887
+    include_spip('inc/documents');
888 888
 
889
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
890
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
889
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
890
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
891 891
 
892
-	// on se place tout le temps comme si on était a la racine
893
-	if (_DIR_RACINE) {
894
-		$d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
895
-	}
892
+    // on se place tout le temps comme si on était a la racine
893
+    if (_DIR_RACINE) {
894
+        $d = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', (string) $d);
895
+    }
896 896
 
897
-	$m = md5($source);
897
+    $m = md5($source);
898 898
 
899
-	$filename =
900
-		$d
901
-		. substr(preg_replace(',[^\w-],', '', basename($source, $extension)), 0, 16)
902
-		. '-' . substr($m, 0, 8)
903
-		. ".$extension";
899
+    $filename =
900
+        $d
901
+        . substr(preg_replace(',[^\w-],', '', basename($source, $extension)), 0, 16)
902
+        . '-' . substr($m, 0, 8)
903
+        . ".$extension";
904 904
 
905
-	// ancien nommage des fichiers distants : renommer le fichier a la volee si besoin pour eviter de dupliquer les caches
906
-	$legacy_filename =
907
-		$d
908
-		. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
909
-		. substr($m, 0, 4)
910
-		. ".$extension";
905
+    // ancien nommage des fichiers distants : renommer le fichier a la volee si besoin pour eviter de dupliquer les caches
906
+    $legacy_filename =
907
+        $d
908
+        . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
909
+        . substr($m, 0, 4)
910
+        . ".$extension";
911 911
 
912
-	if (file_exists(_DIR_RACINE . $legacy_filename)) {
913
-		@rename(_DIR_RACINE . $legacy_filename, $filename);
914
-	}
912
+    if (file_exists(_DIR_RACINE . $legacy_filename)) {
913
+        @rename(_DIR_RACINE . $legacy_filename, $filename);
914
+    }
915 915
 
916
-	return $filename;
916
+    return $filename;
917 917
 }
918 918
 
919 919
 /**
@@ -932,72 +932,72 @@  discard block
 block discarded – undo
932 932
  *      - null: Copie locale impossible
933 933
  **/
934 934
 function fichier_copie_locale($source) {
935
-	// Si c'est deja local pas de souci
936
-	if (!tester_url_absolue($source)) {
937
-		if (_DIR_RACINE) {
938
-			$source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
939
-		}
940
-
941
-		return $source;
942
-	}
943
-
944
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
945
-	// a deja ete copie en local avec cette extension
946
-	// dans ce cas elle est fiable, pas la peine de requeter en base
947
-	$path_parts = pathinfo($source);
948
-	if (!isset($path_parts['extension'])) {
949
-		$path_parts['extension'] = '';
950
-	}
951
-	$ext = $path_parts ? $path_parts['extension'] : '';
952
-	if (
953
-		$ext
954
-		&& preg_match(',^\w+$,', $ext)
955
-		&& ($f = nom_fichier_copie_locale($source, $ext))
956
-		&& file_exists(_DIR_RACINE . $f)
957
-	) {
958
-		return $f;
959
-	}
960
-
961
-
962
-	// Si c'est deja dans la table des documents,
963
-	// ramener le nom de sa copie potentielle
964
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
965
-
966
-	if ($ext) {
967
-		return nom_fichier_copie_locale($source, $ext);
968
-	}
969
-
970
-	// voir si l'extension indiquee dans le nom du fichier est ok
971
-	// et si il n'aurait pas deja ete rapatrie
972
-
973
-	$ext = $path_parts ? $path_parts['extension'] : '';
974
-
975
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
976
-		$f = nom_fichier_copie_locale($source, $ext);
977
-		if (file_exists(_DIR_RACINE . $f)) {
978
-			return $f;
979
-		}
980
-	}
981
-
982
-	// Ping  pour voir si son extension est connue et autorisee
983
-	// avec mise en cache du resultat du ping
984
-
985
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
986
-	if (
987
-		!@file_exists($cache)
988
-		|| !($path_parts = @unserialize(spip_file_get_contents($cache)))
989
-		|| _request('var_mode') === 'recalcul'
990
-	) {
991
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
992
-		ecrire_fichier($cache, serialize($path_parts));
993
-	}
994
-	$ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
995
-	if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
996
-		return nom_fichier_copie_locale($source, $ext);
997
-	}
998
-
999
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1000
-	return null;
935
+    // Si c'est deja local pas de souci
936
+    if (!tester_url_absolue($source)) {
937
+        if (_DIR_RACINE) {
938
+            $source = preg_replace(',^' . preg_quote((string) _DIR_RACINE, ',') . ',', '', $source);
939
+        }
940
+
941
+        return $source;
942
+    }
943
+
944
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
945
+    // a deja ete copie en local avec cette extension
946
+    // dans ce cas elle est fiable, pas la peine de requeter en base
947
+    $path_parts = pathinfo($source);
948
+    if (!isset($path_parts['extension'])) {
949
+        $path_parts['extension'] = '';
950
+    }
951
+    $ext = $path_parts ? $path_parts['extension'] : '';
952
+    if (
953
+        $ext
954
+        && preg_match(',^\w+$,', $ext)
955
+        && ($f = nom_fichier_copie_locale($source, $ext))
956
+        && file_exists(_DIR_RACINE . $f)
957
+    ) {
958
+        return $f;
959
+    }
960
+
961
+
962
+    // Si c'est deja dans la table des documents,
963
+    // ramener le nom de sa copie potentielle
964
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
965
+
966
+    if ($ext) {
967
+        return nom_fichier_copie_locale($source, $ext);
968
+    }
969
+
970
+    // voir si l'extension indiquee dans le nom du fichier est ok
971
+    // et si il n'aurait pas deja ete rapatrie
972
+
973
+    $ext = $path_parts ? $path_parts['extension'] : '';
974
+
975
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
976
+        $f = nom_fichier_copie_locale($source, $ext);
977
+        if (file_exists(_DIR_RACINE . $f)) {
978
+            return $f;
979
+        }
980
+    }
981
+
982
+    // Ping  pour voir si son extension est connue et autorisee
983
+    // avec mise en cache du resultat du ping
984
+
985
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
986
+    if (
987
+        !@file_exists($cache)
988
+        || !($path_parts = @unserialize(spip_file_get_contents($cache)))
989
+        || _request('var_mode') === 'recalcul'
990
+    ) {
991
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
992
+        ecrire_fichier($cache, serialize($path_parts));
993
+    }
994
+    $ext = empty($path_parts['extension']) ? '' : $path_parts['extension'];
995
+    if ($ext && sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
996
+        return nom_fichier_copie_locale($source, $ext);
997
+    }
998
+
999
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1000
+    return null;
1001 1001
 }
1002 1002
 
1003 1003
 
@@ -1026,129 +1026,129 @@  discard block
 block discarded – undo
1026 1026
  **/
1027 1027
 function recuperer_infos_distantes($source, $options = []) {
1028 1028
 
1029
-	// pas la peine de perdre son temps
1030
-	if (!tester_url_absolue($source)) {
1031
-		return false;
1032
-	}
1033
-
1034
-	$taille_max = $options['taille_max'] ?? 0;
1035
-	$charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
1036
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
1037
-
1038
-	# charger les alias des types mime
1039
-	include_spip('base/typedoc');
1040
-
1041
-	$a = [];
1042
-	$mime_type = '';
1043
-	// On va directement charger le debut des images et des fichiers html,
1044
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1045
-	// ca echoue l'utilisateur devra les entrer...
1046
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1047
-	if (
1048
-		$callback_valider_url
1049
-		&& is_callable($callback_valider_url)
1050
-		&& !$callback_valider_url($reponse['url'])
1051
-	) {
1052
-		return false;
1053
-	}
1054
-	$headers = $reponse['headers'] ?? '';
1055
-	$a['body'] = $reponse['page'] ?? '';
1056
-	if ($headers) {
1057
-		$mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1058
-
1059
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1060
-			return false;
1061
-		}
1062
-
1063
-		$a['extension'] = $extension;
1064
-
1065
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1066
-			$a['taille'] = (int) $regs[1];
1067
-		}
1068
-	}
1069
-
1070
-	// Echec avec HEAD, on tente avec GET
1071
-	if (!$a && !$taille_max) {
1072
-		spip_log("tenter GET $source", 'distant');
1073
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1074
-		$a = recuperer_infos_distantes($source, $options);
1075
-	}
1076
-
1077
-	// si on a rien trouve pas la peine d'insister
1078
-	if (!$a) {
1079
-		return false;
1080
-	}
1081
-
1082
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1083
-	// recharger le document en GET et recuperer des donnees supplementaires...
1084
-	include_spip('inc/filtres_images_lib_mini');
1085
-	include_spip('inc/documents');
1086
-	if (
1087
-		str_starts_with($mime_type, 'image/')
1088
-		&& ($extension = _image_trouver_extension_depuis_mime($mime_type))
1089
-	) {
1090
-		if (
1091
-			$taille_max == 0
1092
-			&& (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1093
-			&& in_array($extension, formats_image_acceptables())
1094
-			&& $charger_si_petite_image
1095
-		) {
1096
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1097
-			$a = recuperer_infos_distantes($source, $options);
1098
-		} else {
1099
-			if ($a['body']) {
1100
-				$a['extension'] = corriger_extension($extension);
1101
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1102
-				ecrire_fichier($a['fichier'], $a['body']);
1103
-				$size_image = @spip_getimagesize($a['fichier']);
1104
-				$a['largeur'] = (int) $size_image[0];
1105
-				$a['hauteur'] = (int) $size_image[1];
1106
-				$a['type_image'] = true;
1107
-			}
1108
-		}
1109
-	}
1110
-
1111
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1112
-	// ce sera mieux que 0x0
1113
-	// Flash is dead!
1114
-	if (
1115
-		$a
1116
-		&& isset($a['extension'])
1117
-		&& $a['extension'] == 'swf'
1118
-		&& empty($a['largeur'])
1119
-	) {
1120
-		$a['largeur'] = 425;
1121
-		$a['hauteur'] = 350;
1122
-	}
1123
-
1124
-	if ($mime_type == 'text/html') {
1125
-		include_spip('inc/filtres');
1126
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1127
-		$page = $page['page'] ?? '';
1128
-		if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1129
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1130
-		}
1131
-		if (!isset($a['taille']) || !$a['taille']) {
1132
-			$a['taille'] = strlen((string) $page); # a peu pres
1133
-		}
1134
-	}
1135
-	$a['mime_type'] = $mime_type;
1136
-
1137
-	return $a;
1029
+    // pas la peine de perdre son temps
1030
+    if (!tester_url_absolue($source)) {
1031
+        return false;
1032
+    }
1033
+
1034
+    $taille_max = $options['taille_max'] ?? 0;
1035
+    $charger_si_petite_image = (bool) ($options['charger_si_petite_image'] ?? true);
1036
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
1037
+
1038
+    # charger les alias des types mime
1039
+    include_spip('base/typedoc');
1040
+
1041
+    $a = [];
1042
+    $mime_type = '';
1043
+    // On va directement charger le debut des images et des fichiers html,
1044
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1045
+    // ca echoue l'utilisateur devra les entrer...
1046
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1047
+    if (
1048
+        $callback_valider_url
1049
+        && is_callable($callback_valider_url)
1050
+        && !$callback_valider_url($reponse['url'])
1051
+    ) {
1052
+        return false;
1053
+    }
1054
+    $headers = $reponse['headers'] ?? '';
1055
+    $a['body'] = $reponse['page'] ?? '';
1056
+    if ($headers) {
1057
+        $mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1058
+
1059
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1060
+            return false;
1061
+        }
1062
+
1063
+        $a['extension'] = $extension;
1064
+
1065
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1066
+            $a['taille'] = (int) $regs[1];
1067
+        }
1068
+    }
1069
+
1070
+    // Echec avec HEAD, on tente avec GET
1071
+    if (!$a && !$taille_max) {
1072
+        spip_log("tenter GET $source", 'distant');
1073
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1074
+        $a = recuperer_infos_distantes($source, $options);
1075
+    }
1076
+
1077
+    // si on a rien trouve pas la peine d'insister
1078
+    if (!$a) {
1079
+        return false;
1080
+    }
1081
+
1082
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1083
+    // recharger le document en GET et recuperer des donnees supplementaires...
1084
+    include_spip('inc/filtres_images_lib_mini');
1085
+    include_spip('inc/documents');
1086
+    if (
1087
+        str_starts_with($mime_type, 'image/')
1088
+        && ($extension = _image_trouver_extension_depuis_mime($mime_type))
1089
+    ) {
1090
+        if (
1091
+            $taille_max == 0
1092
+            && (empty($a['taille']) || $a['taille'] < _INC_DISTANT_MAX_SIZE)
1093
+            && in_array($extension, formats_image_acceptables())
1094
+            && $charger_si_petite_image
1095
+        ) {
1096
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1097
+            $a = recuperer_infos_distantes($source, $options);
1098
+        } else {
1099
+            if ($a['body']) {
1100
+                $a['extension'] = corriger_extension($extension);
1101
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1102
+                ecrire_fichier($a['fichier'], $a['body']);
1103
+                $size_image = @spip_getimagesize($a['fichier']);
1104
+                $a['largeur'] = (int) $size_image[0];
1105
+                $a['hauteur'] = (int) $size_image[1];
1106
+                $a['type_image'] = true;
1107
+            }
1108
+        }
1109
+    }
1110
+
1111
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1112
+    // ce sera mieux que 0x0
1113
+    // Flash is dead!
1114
+    if (
1115
+        $a
1116
+        && isset($a['extension'])
1117
+        && $a['extension'] == 'swf'
1118
+        && empty($a['largeur'])
1119
+    ) {
1120
+        $a['largeur'] = 425;
1121
+        $a['hauteur'] = 350;
1122
+    }
1123
+
1124
+    if ($mime_type == 'text/html') {
1125
+        include_spip('inc/filtres');
1126
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1127
+        $page = $page['page'] ?? '';
1128
+        if (preg_match(',<title>(.*?)</title>,ims', (string) $page, $regs)) {
1129
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1130
+        }
1131
+        if (!isset($a['taille']) || !$a['taille']) {
1132
+            $a['taille'] = strlen((string) $page); # a peu pres
1133
+        }
1134
+    }
1135
+    $a['mime_type'] = $mime_type;
1136
+
1137
+    return $a;
1138 1138
 }
1139 1139
 
1140 1140
 /**
1141 1141
  * Retrouver un mime type depuis les headers
1142 1142
  */
1143 1143
 function distant_trouver_mime_type_selon_headers(string $source, string $headers): string {
1144
-	$mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1144
+    $mime_type = preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs) ? trim($regs[1]) : ''; // inconnu
1145 1145
 
1146
-	// Appliquer les alias
1147
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1148
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1149
-	}
1146
+    // Appliquer les alias
1147
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1148
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1149
+    }
1150 1150
 
1151
-	return $mime_type;
1151
+    return $mime_type;
1152 1152
 }
1153 1153
 
1154 1154
 /**
@@ -1157,58 +1157,58 @@  discard block
 block discarded – undo
1157 1157
  * @return false|string
1158 1158
  */
1159 1159
 function distant_trouver_extension_selon_headers(string $source, string $headers) {
1160
-	$mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1161
-
1162
-	// pour corriger_extension()
1163
-	include_spip('inc/documents');
1164
-
1165
-	// Si on a un mime-type insignifiant
1166
-	// text/plain,application/octet-stream ou vide
1167
-	// c'est peut-etre que le serveur ne sait pas
1168
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1169
-	// ou le Content-Disposition: attachment; filename=...
1170
-	$t = null;
1171
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1172
-		if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1173
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1174
-		}
1175
-		if (
1176
-			!$t
1177
-			&& preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1178
-			&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1179
-		) {
1180
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1181
-		}
1182
-	}
1183
-
1184
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1185
-	if (!$t) {
1186
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1187
-	}
1188
-
1189
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1190
-	// On essaie de nouveau avec l'extension
1191
-	if (
1192
-		!$t
1193
-		&& $mime_type != 'text/plain'
1194
-		&& preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1195
-	) {
1196
-		# eviter xxx.3 => 3gp (> SPIP 3)
1197
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1198
-	}
1199
-
1200
-	if ($t) {
1201
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1202
-		return $t['extension'];
1203
-	} else {
1204
-		# par defaut on retombe sur '.bin' si c'est autorise
1205
-		spip_log("mime-type $mime_type inconnu", 'distant');
1206
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1207
-		if (!$t) {
1208
-			return false;
1209
-		}
1210
-		return $t['extension'];
1211
-	}
1160
+    $mime_type = distant_trouver_mime_type_selon_headers($source, $headers);
1161
+
1162
+    // pour corriger_extension()
1163
+    include_spip('inc/documents');
1164
+
1165
+    // Si on a un mime-type insignifiant
1166
+    // text/plain,application/octet-stream ou vide
1167
+    // c'est peut-etre que le serveur ne sait pas
1168
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1169
+    // ou le Content-Disposition: attachment; filename=...
1170
+    $t = null;
1171
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1172
+        if (!$t && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)) {
1173
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1174
+        }
1175
+        if (
1176
+            !$t
1177
+            && preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1178
+            && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1179
+        ) {
1180
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1181
+        }
1182
+    }
1183
+
1184
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1185
+    if (!$t) {
1186
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1187
+    }
1188
+
1189
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1190
+    // On essaie de nouveau avec l'extension
1191
+    if (
1192
+        !$t
1193
+        && $mime_type != 'text/plain'
1194
+        && preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1195
+    ) {
1196
+        # eviter xxx.3 => 3gp (> SPIP 3)
1197
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1198
+    }
1199
+
1200
+    if ($t) {
1201
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1202
+        return $t['extension'];
1203
+    } else {
1204
+        # par defaut on retombe sur '.bin' si c'est autorise
1205
+        spip_log("mime-type $mime_type inconnu", 'distant');
1206
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1207
+        if (!$t) {
1208
+            return false;
1209
+        }
1210
+        return $t['extension'];
1211
+    }
1212 1212
 }
1213 1213
 
1214 1214
 /**
@@ -1224,45 +1224,45 @@  discard block
 block discarded – undo
1224 1224
  */
1225 1225
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1226 1226
 
1227
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1228
-
1229
-	// rien a faire si pas de proxy :)
1230
-	if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1231
-		return '';
1232
-	}
1233
-
1234
-	if (is_null($http_noproxy)) {
1235
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1236
-	}
1237
-	// si pas d'exception, on retourne le proxy
1238
-	if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1239
-		return $http_proxy;
1240
-	}
1241
-
1242
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1243
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1244
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1245
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1246
-	$http_noproxy = " $http_noproxy ";
1247
-	$domain = $host;
1248
-	// si le domaine exact www.example.org est dans les exceptions
1249
-	if (str_contains($http_noproxy, (string) " $domain ")) {
1250
-		return '';
1251
-	}
1252
-
1253
-	while (str_contains($domain, '.')) {
1254
-		$domain = explode('.', $domain);
1255
-		array_shift($domain);
1256
-		$domain = implode('.', $domain);
1257
-
1258
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1259
-		if (str_contains($http_noproxy, (string) " .$domain ")) {
1260
-			return '';
1261
-		}
1262
-	}
1263
-
1264
-	// ok c'est pas une exception
1265
-	return $http_proxy;
1227
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1228
+
1229
+    // rien a faire si pas de proxy :)
1230
+    if (is_null($http_proxy) || !$http_proxy = trim((string) $http_proxy)) {
1231
+        return '';
1232
+    }
1233
+
1234
+    if (is_null($http_noproxy)) {
1235
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1236
+    }
1237
+    // si pas d'exception, on retourne le proxy
1238
+    if (is_null($http_noproxy) || !$http_noproxy = trim((string) $http_noproxy)) {
1239
+        return $http_proxy;
1240
+    }
1241
+
1242
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1243
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1244
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1245
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1246
+    $http_noproxy = " $http_noproxy ";
1247
+    $domain = $host;
1248
+    // si le domaine exact www.example.org est dans les exceptions
1249
+    if (str_contains($http_noproxy, (string) " $domain ")) {
1250
+        return '';
1251
+    }
1252
+
1253
+    while (str_contains($domain, '.')) {
1254
+        $domain = explode('.', $domain);
1255
+        array_shift($domain);
1256
+        $domain = implode('.', $domain);
1257
+
1258
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1259
+        if (str_contains($http_noproxy, (string) " .$domain ")) {
1260
+            return '';
1261
+        }
1262
+    }
1263
+
1264
+    // ok c'est pas une exception
1265
+    return $http_proxy;
1266 1266
 }
1267 1267
 
1268 1268
 
@@ -1285,60 +1285,60 @@  discard block
 block discarded – undo
1285 1285
  * @return array
1286 1286
  */
1287 1287
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1288
-	$user = $via_proxy = $proxy_user = '';
1289
-	$fopen = false;
1290
-
1291
-	$t = @parse_url($url);
1292
-	$host = $t['host'];
1293
-	if ($t['scheme'] == 'http') {
1294
-		$scheme = 'http';
1295
-		$noproxy = '';
1296
-	} elseif ($t['scheme'] == 'https') {
1297
-		$scheme = 'ssl';
1298
-		$noproxy = 'ssl://';
1299
-		if (!isset($t['port']) || !($port = $t['port'])) {
1300
-			$t['port'] = 443;
1301
-		}
1302
-	} else {
1303
-		$scheme = $t['scheme'];
1304
-		$noproxy = $scheme . '://';
1305
-	}
1306
-	if (isset($t['user'])) {
1307
-		// user et pass doivent être passés en urlencodé dans l'URL, on redecode ici
1308
-		$user = [urldecode($t['user']), urldecode($t['pass'])];
1309
-	}
1310
-
1311
-	if (!isset($t['port']) || !($port = $t['port'])) {
1312
-		$port = 80;
1313
-	}
1314
-	if (!isset($t['path']) || !($path = $t['path'])) {
1315
-		$path = '/';
1316
-	}
1317
-
1318
-	if (!empty($t['query'])) {
1319
-		$path .= '?' . $t['query'];
1320
-	}
1321
-
1322
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1323
-	if (!$f || !is_resource($f)) {
1324
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1325
-		// ce qui correspond a $f===110
1326
-		if (
1327
-			$f !== 110
1328
-			&& !need_proxy($host)
1329
-			&& !_request('tester_proxy')
1330
-			&& (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1331
-		) {
1332
-			$f = @fopen($url, 'rb');
1333
-			spip_log("connexion vers $url par simple fopen", 'distant');
1334
-			$fopen = true;
1335
-		} else {
1336
-			// echec total
1337
-			$f = false;
1338
-		}
1339
-	}
1340
-
1341
-	return [$f, $fopen];
1288
+    $user = $via_proxy = $proxy_user = '';
1289
+    $fopen = false;
1290
+
1291
+    $t = @parse_url($url);
1292
+    $host = $t['host'];
1293
+    if ($t['scheme'] == 'http') {
1294
+        $scheme = 'http';
1295
+        $noproxy = '';
1296
+    } elseif ($t['scheme'] == 'https') {
1297
+        $scheme = 'ssl';
1298
+        $noproxy = 'ssl://';
1299
+        if (!isset($t['port']) || !($port = $t['port'])) {
1300
+            $t['port'] = 443;
1301
+        }
1302
+    } else {
1303
+        $scheme = $t['scheme'];
1304
+        $noproxy = $scheme . '://';
1305
+    }
1306
+    if (isset($t['user'])) {
1307
+        // user et pass doivent être passés en urlencodé dans l'URL, on redecode ici
1308
+        $user = [urldecode($t['user']), urldecode($t['pass'])];
1309
+    }
1310
+
1311
+    if (!isset($t['port']) || !($port = $t['port'])) {
1312
+        $port = 80;
1313
+    }
1314
+    if (!isset($t['path']) || !($path = $t['path'])) {
1315
+        $path = '/';
1316
+    }
1317
+
1318
+    if (!empty($t['query'])) {
1319
+        $path .= '?' . $t['query'];
1320
+    }
1321
+
1322
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1323
+    if (!$f || !is_resource($f)) {
1324
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1325
+        // ce qui correspond a $f===110
1326
+        if (
1327
+            $f !== 110
1328
+            && !need_proxy($host)
1329
+            && !_request('tester_proxy')
1330
+            && (!isset($GLOBALS['inc_distant_allow_fopen']) || $GLOBALS['inc_distant_allow_fopen'])
1331
+        ) {
1332
+            $f = @fopen($url, 'rb');
1333
+            spip_log("connexion vers $url par simple fopen", 'distant');
1334
+            $fopen = true;
1335
+        } else {
1336
+            // echec total
1337
+            $f = false;
1338
+        }
1339
+    }
1340
+
1341
+    return [$f, $fopen];
1342 1342
 }
1343 1343
 
1344 1344
 /**
@@ -1373,124 +1373,124 @@  discard block
 block discarded – undo
1373 1373
  *   resource socket vers l'url demandee
1374 1374
  */
1375 1375
 function lance_requete(
1376
-	$method,
1377
-	$scheme,
1378
-	$user,
1379
-	$host,
1380
-	$path,
1381
-	$port,
1382
-	$noproxy,
1383
-	$refuse_gz = false,
1384
-	$referer = '',
1385
-	$datas = '',
1386
-	$vers = 'HTTP/1.0',
1387
-	$date = ''
1376
+    $method,
1377
+    $scheme,
1378
+    $user,
1379
+    $host,
1380
+    $path,
1381
+    $port,
1382
+    $noproxy,
1383
+    $refuse_gz = false,
1384
+    $referer = '',
1385
+    $datas = '',
1386
+    $vers = 'HTTP/1.0',
1387
+    $date = ''
1388 1388
 ) {
1389 1389
 
1390
-	$proxy_user = '';
1391
-	$http_proxy = need_proxy($host);
1392
-	if ($user) {
1393
-		$user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1394
-	}
1395
-
1396
-	$connect = '';
1397
-	if ($http_proxy) {
1398
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1399
-			$path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1400
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1401
-				. "Host: $path_host\r\n"
1402
-				. "Proxy-Connection: Keep-Alive\r\n";
1403
-		} else {
1404
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1405
-				. ($user ? "$user@" : '')
1406
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1407
-		}
1408
-		$t2 = @parse_url($http_proxy);
1409
-		$first_host = $t2['host'];
1410
-		$first_port = ($t2['port'] ?? null) ?: 80;
1411
-		if ($t2['user'] ?? null) {
1412
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1413
-		}
1414
-	} else {
1415
-		$first_host = $noproxy . $host;
1416
-		$first_port = $port;
1417
-	}
1418
-
1419
-	if ($connect) {
1420
-		$streamContext = stream_context_create([
1421
-			'ssl' => [
1422
-				'verify_peer' => false,
1423
-				'allow_self_signed' => true,
1424
-				'SNI_enabled' => true,
1425
-				'peer_name' => $host,
1426
-			]
1427
-		]);
1428
-		$f = @stream_socket_client(
1429
-			"tcp://$first_host:$first_port",
1430
-			$errno,
1431
-			$errstr,
1432
-			_INC_DISTANT_CONNECT_TIMEOUT,
1433
-			STREAM_CLIENT_CONNECT,
1434
-			$streamContext
1435
-		);
1436
-		spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1437
-		if (!$f) {
1438
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1439
-			return $errno;
1440
-		}
1441
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1442
-
1443
-		fwrite($f, $connect);
1444
-		fwrite($f, "\r\n");
1445
-		$res = fread($f, 1024);
1446
-		if (
1447
-			!$res
1448
-			|| ($res = explode(' ', $res)) === []
1449
-			|| $res[1] !== '200'
1450
-		) {
1451
-			spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1452
-			fclose($f);
1453
-
1454
-			return false;
1455
-		}
1456
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1457
-		stream_set_blocking($f, true);
1458
-		// envoyer le handshake
1459
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1460
-		spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1461
-	} else {
1462
-		$ntry = 3;
1463
-		do {
1464
-			$f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1465
-		} while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1466
-		spip_log("Recuperer $path sur $first_host:$first_port par $f");
1467
-		if (!$f) {
1468
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1469
-
1470
-			return $errno;
1471
-		}
1472
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1473
-	}
1474
-
1475
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1476
-
1477
-	$host_port = $host;
1478
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1479
-		$host_port .= ":$port";
1480
-	}
1481
-	$req = "$method $path $vers\r\n"
1482
-		. "Host: $host_port\r\n"
1483
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1484
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1485
-		. ($site ? "Referer: $site/$referer\r\n" : '')
1486
-		. ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1487
-		. ($user ? 'Authorization: Basic ' . base64_encode(urldecode($user)) . "\r\n" : '')
1488
-		. ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1489
-		. (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1390
+    $proxy_user = '';
1391
+    $http_proxy = need_proxy($host);
1392
+    if ($user) {
1393
+        $user = urlencode((string) $user[0]) . ':' . urlencode((string) $user[1]);
1394
+    }
1395
+
1396
+    $connect = '';
1397
+    if ($http_proxy) {
1398
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') && in_array($scheme, ['tls','ssl'])) {
1399
+            $path_host = ($user ? "$user@" : '') . $host . (($port != 80) ? ":$port" : '');
1400
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1401
+                . "Host: $path_host\r\n"
1402
+                . "Proxy-Connection: Keep-Alive\r\n";
1403
+        } else {
1404
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1405
+                . ($user ? "$user@" : '')
1406
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1407
+        }
1408
+        $t2 = @parse_url($http_proxy);
1409
+        $first_host = $t2['host'];
1410
+        $first_port = ($t2['port'] ?? null) ?: 80;
1411
+        if ($t2['user'] ?? null) {
1412
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1413
+        }
1414
+    } else {
1415
+        $first_host = $noproxy . $host;
1416
+        $first_port = $port;
1417
+    }
1418
+
1419
+    if ($connect) {
1420
+        $streamContext = stream_context_create([
1421
+            'ssl' => [
1422
+                'verify_peer' => false,
1423
+                'allow_self_signed' => true,
1424
+                'SNI_enabled' => true,
1425
+                'peer_name' => $host,
1426
+            ]
1427
+        ]);
1428
+        $f = @stream_socket_client(
1429
+            "tcp://$first_host:$first_port",
1430
+            $errno,
1431
+            $errstr,
1432
+            _INC_DISTANT_CONNECT_TIMEOUT,
1433
+            STREAM_CLIENT_CONNECT,
1434
+            $streamContext
1435
+        );
1436
+        spip_log("Recuperer $path sur $first_host:$first_port par $f (via CONNECT)", 'connect');
1437
+        if (!$f) {
1438
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1439
+            return $errno;
1440
+        }
1441
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1442
+
1443
+        fwrite($f, $connect);
1444
+        fwrite($f, "\r\n");
1445
+        $res = fread($f, 1024);
1446
+        if (
1447
+            !$res
1448
+            || ($res = explode(' ', $res)) === []
1449
+            || $res[1] !== '200'
1450
+        ) {
1451
+            spip_log("Echec CONNECT sur $first_host:$first_port", 'connect' . _LOG_INFO_IMPORTANTE);
1452
+            fclose($f);
1453
+
1454
+            return false;
1455
+        }
1456
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1457
+        stream_set_blocking($f, true);
1458
+        // envoyer le handshake
1459
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1460
+        spip_log("OK CONNECT sur $first_host:$first_port", 'connect');
1461
+    } else {
1462
+        $ntry = 3;
1463
+        do {
1464
+            $f = @fsockopen($first_host, $first_port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1465
+        } while (!$f && $ntry-- && $errno !== 110 && sleep(1));
1466
+        spip_log("Recuperer $path sur $first_host:$first_port par $f");
1467
+        if (!$f) {
1468
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1469
+
1470
+            return $errno;
1471
+        }
1472
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1473
+    }
1474
+
1475
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1476
+
1477
+    $host_port = $host;
1478
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1479
+        $host_port .= ":$port";
1480
+    }
1481
+    $req = "$method $path $vers\r\n"
1482
+        . "Host: $host_port\r\n"
1483
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1484
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1485
+        . ($site ? "Referer: $site/$referer\r\n" : '')
1486
+        . ($date ? 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n") : '')
1487
+        . ($user ? 'Authorization: Basic ' . base64_encode(urldecode($user)) . "\r\n" : '')
1488
+        . ($proxy_user ? "Proxy-Authorization: Basic $proxy_user\r\n" : '')
1489
+        . (strpos($vers, '1.1') ? "Keep-Alive: 300\r\nConnection: keep-alive\r\n" : '');
1490 1490
 
1491 1491
 #	spip_log("Requete\n$req", 'distant');
1492
-	fwrite($f, $req);
1493
-	fwrite($f, $datas ?: "\r\n");
1492
+    fwrite($f, $req);
1493
+    fwrite($f, $datas ?: "\r\n");
1494 1494
 
1495
-	return $f;
1495
+    return $f;
1496 1496
 }
Please login to merge, or discard this patch.
ecrire/exec/base_repair.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
  */
24 24
 
25 25
 if (!defined('_ECRIRE_INC_VERSION')) {
26
-	return;
26
+    return;
27 27
 }
28 28
 
29 29
 
@@ -31,25 +31,25 @@  discard block
 block discarded – undo
31 31
  * Réparer la base de données
32 32
  */
33 33
 function exec_base_repair_dist() {
34
-	$action = null;
35
-	$ok = false;
36
-	if (!spip_connect()) {
37
-		$message = _T('titre_probleme_technique');
38
-	} else {
39
-		$version_sql = sql_version();
40
-		if (!$version_sql) {
41
-			$message = _T('avis_erreur_connexion_mysql');
42
-		} else {
43
-			$message = _T('texte_requetes_echouent');
44
-			$ok = true;
45
-		}
46
-		$action = _T('texte_tenter_reparation');
47
-	}
48
-	if ($ok) {
49
-		$admin = charger_fonction('admin', 'inc');
50
-		echo $admin('repair', $action, $message, true);
51
-	} else {
52
-		include_spip('inc/minipres');
53
-		echo minipres(_T('titre_reparation'), "<p>$message</p>");
54
-	}
34
+    $action = null;
35
+    $ok = false;
36
+    if (!spip_connect()) {
37
+        $message = _T('titre_probleme_technique');
38
+    } else {
39
+        $version_sql = sql_version();
40
+        if (!$version_sql) {
41
+            $message = _T('avis_erreur_connexion_mysql');
42
+        } else {
43
+            $message = _T('texte_requetes_echouent');
44
+            $ok = true;
45
+        }
46
+        $action = _T('texte_tenter_reparation');
47
+    }
48
+    if ($ok) {
49
+        $admin = charger_fonction('admin', 'inc');
50
+        echo $admin('repair', $action, $message, true);
51
+    } else {
52
+        include_spip('inc/minipres');
53
+        echo minipres(_T('titre_reparation'), "<p>$message</p>");
54
+    }
55 55
 }
Please login to merge, or discard this patch.
ecrire/exec/demande_mise_a_jour.php 2 patches
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
  */
21 21
 
22 22
 if (!defined('_ECRIRE_INC_VERSION')) {
23
-	return;
23
+    return;
24 24
 }
25 25
 
26 26
 
@@ -28,29 +28,29 @@  discard block
 block discarded – undo
28 28
  * Demander à mettre à jour la base de données
29 29
  */
30 30
 function exec_demande_mise_a_jour_dist() {
31
-	// on fait la verif du path avant tout,
32
-	// et l'installation des qu'on est dans la colonne principale
33
-	// si jamais la liste des plugins actifs change, il faut faire un refresh du hit
34
-	// pour etre sur que les bons fichiers seront charges lors de l'install
35
-	include_spip('inc/plugin');
36
-	if (actualise_plugins_actifs()) {
37
-		include_spip('inc/headers');
38
-		redirige_par_entete(self());
39
-	}
31
+    // on fait la verif du path avant tout,
32
+    // et l'installation des qu'on est dans la colonne principale
33
+    // si jamais la liste des plugins actifs change, il faut faire un refresh du hit
34
+    // pour etre sur que les bons fichiers seront charges lors de l'install
35
+    include_spip('inc/plugin');
36
+    if (actualise_plugins_actifs()) {
37
+        include_spip('inc/headers');
38
+        redirige_par_entete(self());
39
+    }
40 40
 
41
-	include_spip('inc/presentation');
42
-	include_spip('inc/filtres_boites');
43
-	$commencer_page = charger_fonction('commencer_page', 'inc');
44
-	echo $commencer_page('', '', '', '', true, false, false);
41
+    include_spip('inc/presentation');
42
+    include_spip('inc/filtres_boites');
43
+    $commencer_page = charger_fonction('commencer_page', 'inc');
44
+    echo $commencer_page('', '', '', '', true, false, false);
45 45
 
46
-	echo debut_grand_cadre();
47
-	echo boite_ouvrir(_T('info_message_technique'), 'notice');
48
-	echo '<p>' . _T('info_procedure_maj_version') . '</p>',
49
-		'<p>' . _T('info_administrateur_site_01') . '</p>';
50
-	echo bouton_action(_T('bouton_mettre_a_jour_base'), generer_url_ecrire('upgrade', 'reinstall=non'));
51
-	echo boite_fermer();
52
-	// masquer les erreurs sql sur cette page car proviennent de la base pas a jour !
53
-	echo '<style type="text/css">#debug-nav {display: none;}</style>';
54
-	echo fin_grand_cadre();
55
-	echo fin_page();
46
+    echo debut_grand_cadre();
47
+    echo boite_ouvrir(_T('info_message_technique'), 'notice');
48
+    echo '<p>' . _T('info_procedure_maj_version') . '</p>',
49
+        '<p>' . _T('info_administrateur_site_01') . '</p>';
50
+    echo bouton_action(_T('bouton_mettre_a_jour_base'), generer_url_ecrire('upgrade', 'reinstall=non'));
51
+    echo boite_fermer();
52
+    // masquer les erreurs sql sur cette page car proviennent de la base pas a jour !
53
+    echo '<style type="text/css">#debug-nav {display: none;}</style>';
54
+    echo fin_grand_cadre();
55
+    echo fin_page();
56 56
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -45,8 +45,8 @@
 block discarded – undo
45 45
 
46 46
 	echo debut_grand_cadre();
47 47
 	echo boite_ouvrir(_T('info_message_technique'), 'notice');
48
-	echo '<p>' . _T('info_procedure_maj_version') . '</p>',
49
-		'<p>' . _T('info_administrateur_site_01') . '</p>';
48
+	echo '<p>'._T('info_procedure_maj_version').'</p>',
49
+		'<p>'._T('info_administrateur_site_01').'</p>';
50 50
 	echo bouton_action(_T('bouton_mettre_a_jour_base'), generer_url_ecrire('upgrade', 'reinstall=non'));
51 51
 	echo boite_fermer();
52 52
 	// masquer les erreurs sql sur cette page car proviennent de la base pas a jour !
Please login to merge, or discard this patch.
ecrire/exec/404.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -25,25 +25,25 @@  discard block
 block discarded – undo
25 25
  */
26 26
 function exec_404_dist() {
27 27
 
28
-	$exec = _request('exec');
28
+    $exec = _request('exec');
29 29
 
30
-	$titre = "exec_$exec";
31
-	$navigation = '';
32
-	$extra = '';
30
+    $titre = "exec_$exec";
31
+    $navigation = '';
32
+    $extra = '';
33 33
 
34
-	include_spip('inc/presentation'); // alleger les inclusions avec un inc/presentation_mini
35
-	$commencer_page = charger_fonction('commencer_page', 'inc');
36
-	echo $commencer_page($titre);
34
+    include_spip('inc/presentation'); // alleger les inclusions avec un inc/presentation_mini
35
+    $commencer_page = charger_fonction('commencer_page', 'inc');
36
+    echo $commencer_page($titre);
37 37
 
38
-	echo debut_gauche();
39
-	echo pipeline('affiche_gauche', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
38
+    echo debut_gauche();
39
+    echo pipeline('affiche_gauche', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
40 40
 
41
-	echo creer_colonne_droite();
42
-	echo pipeline('affiche_droite', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
41
+    echo creer_colonne_droite();
42
+    echo pipeline('affiche_droite', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
43 43
 
44
-	echo debut_droite();
45
-	echo "<h1 class='grostitre'>" . _T('fichier_introuvable', ['fichier' => $exec]) . '</h1>';
46
-	echo pipeline('affiche_milieu', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
44
+    echo debut_droite();
45
+    echo "<h1 class='grostitre'>" . _T('fichier_introuvable', ['fichier' => $exec]) . '</h1>';
46
+    echo pipeline('affiche_milieu', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
47 47
 
48
-	echo fin_gauche(), fin_page();
48
+    echo fin_gauche(), fin_page();
49 49
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@
 block discarded – undo
42 42
 	echo pipeline('affiche_droite', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
43 43
 
44 44
 	echo debut_droite();
45
-	echo "<h1 class='grostitre'>" . _T('fichier_introuvable', ['fichier' => $exec]) . '</h1>';
45
+	echo "<h1 class='grostitre'>"._T('fichier_introuvable', ['fichier' => $exec]).'</h1>';
46 46
 	echo pipeline('affiche_milieu', ['args' => ['exec' => '404', 'exec_erreur' => $exec], 'data' => '']);
47 47
 
48 48
 	echo fin_gauche(), fin_page();
Please login to merge, or discard this patch.
ecrire/inc/csv.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -87,12 +87,12 @@
 block discarded – undo
87 87
 	}
88 88
 	// si une seule colonne, en faire le titre
89 89
 	if (preg_match("/^([^$sep]+)$sep+\$/", $entete, $l)) {
90
-		$caption = "\n||" . $l[1] . '|';
90
+		$caption = "\n||".$l[1].'|';
91 91
 		[$entete, $corps] = explode("\n", $corps, 2);
92 92
 	}
93 93
 	// si premiere colonne vide, le raccourci doit quand meme produire <th...
94 94
 	if ($entete[0] == $sep) {
95
-		$entete = ' ' . $entete;
95
+		$entete = ' '.$entete;
96 96
 	}
97 97
 
98 98
 	$lignes = explode("\n", $corps);
Please login to merge, or discard this patch.
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  */
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -32,117 +32,117 @@  discard block
 block discarded – undo
32 32
  **/
33 33
 function analyse_csv($t) {
34 34
 
35
-	// Quel est le séparateur ?
36
-	$virg = substr_count($t, ',');
37
-	$pvirg = substr_count($t, ';');
38
-	$tab = substr_count($t, "\t");
39
-	if ($virg > $pvirg) {
40
-		$sep = ',';
41
-		$hs = '&#44;';
42
-	} else {
43
-		$sep = ';';
44
-		$hs = '&#59;';
45
-		$virg = $pvirg;
46
-	}
47
-	// un certain nombre de tab => le séparateur est tab
48
-	if ($tab > $virg / 10) {
49
-		$sep = "\t";
50
-		$hs = "\t";
51
-	}
35
+    // Quel est le séparateur ?
36
+    $virg = substr_count($t, ',');
37
+    $pvirg = substr_count($t, ';');
38
+    $tab = substr_count($t, "\t");
39
+    if ($virg > $pvirg) {
40
+        $sep = ',';
41
+        $hs = '&#44;';
42
+    } else {
43
+        $sep = ';';
44
+        $hs = '&#59;';
45
+        $virg = $pvirg;
46
+    }
47
+    // un certain nombre de tab => le séparateur est tab
48
+    if ($tab > $virg / 10) {
49
+        $sep = "\t";
50
+        $hs = "\t";
51
+    }
52 52
 
53
-	// un separateur suivi de 3 guillemets attention !
54
-	// attention au ; ou , suceptible d'etre confondu avec un separateur
55
-	// on substitue un # et on remplacera a la fin
56
-	$t = preg_replace("/([\n$sep])\"\"\"/", '\\1"&#34#', $t);
57
-	$t = str_replace('""', '&#34#', $t);
58
-	preg_match_all('/"[^"]*"/', $t, $r);
59
-	foreach ($r[0] as $cell) {
60
-		$t = str_replace(
61
-			$cell,
62
-			str_replace(
63
-				$sep,
64
-				$hs,
65
-				str_replace(
66
-					"\n",
67
-					'``**``', // échapper les saut de lignes, on les remettra après.
68
-					substr((string) $cell, 1, -1)
69
-				)
70
-			),
71
-			$t
72
-		);
73
-	}
53
+    // un separateur suivi de 3 guillemets attention !
54
+    // attention au ; ou , suceptible d'etre confondu avec un separateur
55
+    // on substitue un # et on remplacera a la fin
56
+    $t = preg_replace("/([\n$sep])\"\"\"/", '\\1"&#34#', $t);
57
+    $t = str_replace('""', '&#34#', $t);
58
+    preg_match_all('/"[^"]*"/', $t, $r);
59
+    foreach ($r[0] as $cell) {
60
+        $t = str_replace(
61
+            $cell,
62
+            str_replace(
63
+                $sep,
64
+                $hs,
65
+                str_replace(
66
+                    "\n",
67
+                    '``**``', // échapper les saut de lignes, on les remettra après.
68
+                    substr((string) $cell, 1, -1)
69
+                )
70
+            ),
71
+            $t
72
+        );
73
+    }
74 74
 
75
-	$t = preg_replace(
76
-		'/\r?\n/',
77
-		"\n",
78
-		preg_replace('/[\r\n]+/', "\n", $t)
79
-	);
75
+    $t = preg_replace(
76
+        '/\r?\n/',
77
+        "\n",
78
+        preg_replace('/[\r\n]+/', "\n", $t)
79
+    );
80 80
 
81
-	[$entete, $corps] = explode("\n", $t, 2);
82
-	$caption = '';
83
-	// sauter la ligne de tete formee seulement de separateurs
84
-	if (substr_count($entete, $sep) === strlen($entete)) {
85
-		[$entete, $corps] = explode("\n", $corps, 2);
86
-	}
87
-	// si une seule colonne, en faire le titre
88
-	if (preg_match("/^([^$sep]+)$sep+\$/", $entete, $l)) {
89
-		$caption = "\n||" . $l[1] . '|';
90
-		[$entete, $corps] = explode("\n", $corps, 2);
91
-	}
92
-	// si premiere colonne vide, le raccourci doit quand meme produire <th...
93
-	if ($entete[0] == $sep) {
94
-		$entete = ' ' . $entete;
95
-	}
81
+    [$entete, $corps] = explode("\n", $t, 2);
82
+    $caption = '';
83
+    // sauter la ligne de tete formee seulement de separateurs
84
+    if (substr_count($entete, $sep) === strlen($entete)) {
85
+        [$entete, $corps] = explode("\n", $corps, 2);
86
+    }
87
+    // si une seule colonne, en faire le titre
88
+    if (preg_match("/^([^$sep]+)$sep+\$/", $entete, $l)) {
89
+        $caption = "\n||" . $l[1] . '|';
90
+        [$entete, $corps] = explode("\n", $corps, 2);
91
+    }
92
+    // si premiere colonne vide, le raccourci doit quand meme produire <th...
93
+    if ($entete[0] == $sep) {
94
+        $entete = ' ' . $entete;
95
+    }
96 96
 
97
-	$lignes = explode("\n", $corps);
97
+    $lignes = explode("\n", $corps);
98 98
 
99
-	// retrait des lignes vides finales
100
-	while (
101
-		$lignes !== [] && preg_match("/^$sep*$/", $lignes[count($lignes) - 1])
102
-	) {
103
-		unset($lignes[count($lignes) - 1]);
104
-	}
105
-	//  calcul du  nombre de colonne a chaque ligne
106
-	$nbcols = [];
107
-	$max = $mil = substr_count($entete, $sep);
108
-	foreach ($lignes as $k => $v) {
109
-		if ($max !== ($nbcols[$k] = substr_count($v, $sep))) {
110
-			if ($max > $nbcols[$k]) {
111
-				$mil = $nbcols[$k];
112
-			} else {
113
-				$mil = $max;
114
-				$max = $nbcols[$k];
115
-			}
116
-		}
117
-	}
118
-	// Si pas le meme nombre, cadrer au nombre max
119
-	if ($mil !== $max) {
120
-		foreach ($nbcols as $k => $v) {
121
-			if ($v < $max) {
122
-				$lignes[$k] .= str_repeat($sep, $max - $v);
123
-			}
124
-		}
125
-	}
126
-	// et retirer les colonnes integralement vides
127
-	while (true) {
128
-		$nbcols = ($entete[strlen($entete) - 1] === $sep);
129
-		foreach ($lignes as $v) {
130
-			$nbcols &= ($v[strlen($v) - 1] === $sep);
131
-		}
132
-		if (!$nbcols) {
133
-			break;
134
-		}
135
-		$entete = substr($entete, 0, -1);
136
-		foreach ($lignes as $k => $v) {
137
-			$lignes[$k] = substr($v, 0, -1);
138
-		}
139
-	}
99
+    // retrait des lignes vides finales
100
+    while (
101
+        $lignes !== [] && preg_match("/^$sep*$/", $lignes[count($lignes) - 1])
102
+    ) {
103
+        unset($lignes[count($lignes) - 1]);
104
+    }
105
+    //  calcul du  nombre de colonne a chaque ligne
106
+    $nbcols = [];
107
+    $max = $mil = substr_count($entete, $sep);
108
+    foreach ($lignes as $k => $v) {
109
+        if ($max !== ($nbcols[$k] = substr_count($v, $sep))) {
110
+            if ($max > $nbcols[$k]) {
111
+                $mil = $nbcols[$k];
112
+            } else {
113
+                $mil = $max;
114
+                $max = $nbcols[$k];
115
+            }
116
+        }
117
+    }
118
+    // Si pas le meme nombre, cadrer au nombre max
119
+    if ($mil !== $max) {
120
+        foreach ($nbcols as $k => $v) {
121
+            if ($v < $max) {
122
+                $lignes[$k] .= str_repeat($sep, $max - $v);
123
+            }
124
+        }
125
+    }
126
+    // et retirer les colonnes integralement vides
127
+    while (true) {
128
+        $nbcols = ($entete[strlen($entete) - 1] === $sep);
129
+        foreach ($lignes as $v) {
130
+            $nbcols &= ($v[strlen($v) - 1] === $sep);
131
+        }
132
+        if (!$nbcols) {
133
+            break;
134
+        }
135
+        $entete = substr($entete, 0, -1);
136
+        foreach ($lignes as $k => $v) {
137
+            $lignes[$k] = substr($v, 0, -1);
138
+        }
139
+    }
140 140
 
141
-	foreach ($lignes as &$l) {
142
-		$l = str_replace('&#34#', '"', $l);
143
-		$l = str_replace('``**``', "\n", $l);
144
-		$l = explode($sep, $l);
145
-	}
141
+    foreach ($lignes as &$l) {
142
+        $l = str_replace('&#34#', '"', $l);
143
+        $l = str_replace('``**``', "\n", $l);
144
+        $l = explode($sep, $l);
145
+    }
146 146
 
147
-	return [explode($sep, $entete), $lignes, $caption];
147
+    return [explode($sep, $entete), $lignes, $caption];
148 148
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_images_mini.php 2 patches
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -204,8 +204,8 @@  discard block
 block discarded – undo
204 204
 	$hsl = _couleur_hex_to_hsl($couleur);
205 205
 	$hsl = [
206 206
 		'h' => round($hsl['h'] * 360),
207
-		's' => round($hsl['s'] * 100) . '%',
208
-		'l' => round($hsl['l'] * 100) . '%'
207
+		's' => round($hsl['s'] * 100).'%',
208
+		'l' => round($hsl['l'] * 100).'%'
209 209
 	];
210 210
 	if ($format === null) {
211 211
 		return "hsl({$hsl['h']}, {$hsl['s']}, {$hsl['l']})";
@@ -384,11 +384,11 @@  discard block
 block discarded – undo
384 384
 	$process = 'AUTO'
385 385
 ) {
386 386
 	// PHP 7+ type hint
387
-	$img = (string)$img;
388
-	$taille_x = (int)$taille_x;
389
-	$taille_y = (int)$taille_y;
390
-	$force = (bool)$force;
391
-	$process = (string)$process;
387
+	$img = (string) $img;
388
+	$taille_x = (int) $taille_x;
389
+	$taille_y = (int) $taille_y;
390
+	$force = (bool) $force;
391
+	$process = (string) $process;
392 392
 
393 393
 	if (!$img) {
394 394
 		return '';
@@ -465,11 +465,11 @@  discard block
 block discarded – undo
465 465
 	$process = 'AUTO'
466 466
 ) {
467 467
 	// PHP 7+ type hint
468
-	$img = (string)$img;
469
-	$taille = (int)$taille;
470
-	$taille_y = (int)$taille_y;
471
-	$force = (bool)$force;
472
-	$process = (string)$process;
468
+	$img = (string) $img;
469
+	$taille = (int) $taille;
470
+	$taille_y = (int) $taille_y;
471
+	$force = (bool) $force;
472
+	$process = (string) $process;
473 473
 
474 474
 	// Determiner la taille x,y maxi
475 475
 	// prendre le reglage de previsu par defaut
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 	$background_color = 'white'
513 513
 ) {
514 514
 	if (function_exists('image_recadre') && ($GLOBALS['meta']['image_process'] ?? '') === 'gd2') {
515
-		return image_reduire(image_recadre($im, $width . ':' . $height, '-', $position, $background_color), $width, $height);
515
+		return image_reduire(image_recadre($im, $width.':'.$height, '-', $position, $background_color), $width, $height);
516 516
 	} else { return image_passe_partout($im, $width, $height);
517 517
 	}
518 518
 }
@@ -533,9 +533,9 @@  discard block
 block discarded – undo
533 533
  **/
534 534
 function image_reduire_par($img, $val = 1, $force = false) {
535 535
 	// PHP 7+ type hint
536
-	$img = (string)$img;
537
-	$val = (int)$val;
538
-	$force = (bool)$force;
536
+	$img = (string) $img;
537
+	$val = (int) $val;
538
+	$force = (bool) $force;
539 539
 
540 540
 	[$hauteur, $largeur] = taille_image($img);
541 541
 
Please login to merge, or discard this patch.
Indentation   +312 added lines, -312 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 include_spip('inc/filtres_images_lib_mini'); // par precaution
23 23
 
@@ -30,161 +30,161 @@  discard block
 block discarded – undo
30 30
  *    Le code hexadécimal de la couleur (sans le #) ou le code couleur textuel si non trouvé
31 31
  */
32 32
 function couleur_html_to_hex($couleur) {
33
-	$couleurs_html = [
34
-		'aliceblue' => 'F0F8FF',
35
-		'antiquewhite' => 'FAEBD7',
36
-		'aqua' => '00FFFF',
37
-		'aquamarine' => '7FFFD4',
38
-		'azure' => 'F0FFFF',
39
-		'beige' => 'F5F5DC',
40
-		'bisque' => 'FFE4C4',
41
-		'black' => '000000',
42
-		'blanchedalmond' => 'FFEBCD',
43
-		'blue' => '0000FF',
44
-		'blueviolet' => '8A2BE2',
45
-		'brown' => 'A52A2A',
46
-		'burlywood' => 'DEB887',
47
-		'cadetblue' => '5F9EA0',
48
-		'chartreuse' => '7FFF00',
49
-		'chocolate' => 'D2691E',
50
-		'coral' => 'FF7F50',
51
-		'cornflowerblue' => '6495ED',
52
-		'cornsilk' => 'FFF8DC',
53
-		'crimson' => 'DC143C',
54
-		'cyan' => '00FFFF',
55
-		'darkblue' => '00008B',
56
-		'darkcyan' => '008B8B',
57
-		'darkgoldenrod' => 'B8860B',
58
-		'darkgray' => 'A9A9A9',
59
-		'darkgreen' => '006400',
60
-		'darkgrey' => 'A9A9A9',
61
-		'darkkhaki' => 'BDB76B',
62
-		'darkmagenta' => '8B008B',
63
-		'darkolivegreen' => '556B2F',
64
-		'darkorange' => 'FF8C00',
65
-		'darkorchid' => '9932CC',
66
-		'darkred' => '8B0000',
67
-		'darksalmon' => 'E9967A',
68
-		'darkseagreen' => '8FBC8F',
69
-		'darkslateblue' => '483D8B',
70
-		'darkslategray' => '2F4F4F',
71
-		'darkslategrey' => '2F4F4F',
72
-		'darkturquoise' => '00CED1',
73
-		'darkviolet' => '9400D3',
74
-		'deeppink' => 'FF1493',
75
-		'deepskyblue' => '00BFFF',
76
-		'dimgray' => '696969',
77
-		'dimgrey' => '696969',
78
-		'dodgerblue' => '1E90FF',
79
-		'firebrick' => 'B22222',
80
-		'floralwhite' => 'FFFAF0',
81
-		'forestgreen' => '228B22',
82
-		'fuchsia' => 'FF00FF',
83
-		'gainsboro' => 'DCDCDC',
84
-		'ghostwhite' => 'F8F8FF',
85
-		'gold' => 'FFD700',
86
-		'goldenrod' => 'DAA520',
87
-		'gray' => '808080',
88
-		'green' => '008000',
89
-		'greenyellow' => 'ADFF2F',
90
-		'grey' => '808080',
91
-		'honeydew' => 'F0FFF0',
92
-		'hotpink' => 'FF69B4',
93
-		'indianred' => 'CD5C5C',
94
-		'indigo' => '4B0082',
95
-		'ivory' => 'FFFFF0',
96
-		'khaki' => 'F0E68C',
97
-		'lavender' => 'E6E6FA',
98
-		'lavenderblush' => 'FFF0F5',
99
-		'lawngreen' => '7CFC00',
100
-		'lemonchiffon' => 'FFFACD',
101
-		'lightblue' => 'ADD8E6',
102
-		'lightcoral' => 'F08080',
103
-		'lightcyan' => 'E0FFFF',
104
-		'lightgoldenrodyellow' => 'FAFAD2',
105
-		'lightgray' => 'D3D3D3',
106
-		'lightgreen' => '90EE90',
107
-		'lightgrey' => 'D3D3D3',
108
-		'lightpink' => 'FFB6C1',
109
-		'lightsalmon' => 'FFA07A',
110
-		'lightseagreen' => '20B2AA',
111
-		'lightskyblue' => '87CEFA',
112
-		'lightslategray' => '778899',
113
-		'lightslategrey' => '778899',
114
-		'lightsteelblue' => 'B0C4DE',
115
-		'lightyellow' => 'FFFFE0',
116
-		'lime' => '00FF00',
117
-		'limegreen' => '32CD32',
118
-		'linen' => 'FAF0E6',
119
-		'magenta' => 'FF00FF',
120
-		'maroon' => '800000',
121
-		'mediumaquamarine' => '66CDAA',
122
-		'mediumblue' => '0000CD',
123
-		'mediumorchid' => 'BA55D3',
124
-		'mediumpurple' => '9370DB',
125
-		'mediumseagreen' => '3CB371',
126
-		'mediumslateblue' => '7B68EE',
127
-		'mediumspringgreen' => '00FA9A',
128
-		'mediumturquoise' => '48D1CC',
129
-		'mediumvioletred' => 'C71585',
130
-		'midnightblue' => '191970',
131
-		'mintcream' => 'F5FFFA',
132
-		'mistyrose' => 'FFE4E1',
133
-		'moccasin' => 'FFE4B5',
134
-		'navajowhite' => 'FFDEAD',
135
-		'navy' => '000080',
136
-		'oldlace' => 'FDF5E6',
137
-		'olive' => '808000',
138
-		'olivedrab' => '6B8E23',
139
-		'orange' => 'FFA500',
140
-		'orangered' => 'FF4500',
141
-		'orchid' => 'DA70D6',
142
-		'palegoldenrod' => 'EEE8AA',
143
-		'palegreen' => '98FB98',
144
-		'paleturquoise' => 'AFEEEE',
145
-		'palevioletred' => 'DB7093',
146
-		'papayawhip' => 'FFEFD5',
147
-		'peachpuff' => 'FFDAB9',
148
-		'peru' => 'CD853F',
149
-		'pink' => 'FFC0CB',
150
-		'plum' => 'DDA0DD',
151
-		'powderblue' => 'B0E0E6',
152
-		'purple' => '800080',
153
-		'rebeccapurple' => '663399',
154
-		'red' => 'FF0000',
155
-		'rosybrown' => 'BC8F8F',
156
-		'royalblue' => '4169E1',
157
-		'saddlebrown' => '8B4513',
158
-		'salmon' => 'FA8072',
159
-		'sandybrown' => 'F4A460',
160
-		'seagreen' => '2E8B57',
161
-		'seashell' => 'FFF5EE',
162
-		'sienna' => 'A0522D',
163
-		'silver' => 'C0C0C0',
164
-		'skyblue' => '87CEEB',
165
-		'slateblue' => '6A5ACD',
166
-		'slategray' => '708090',
167
-		'slategrey' => '708090',
168
-		'snow' => 'FFFAFA',
169
-		'springgreen' => '00FF7F',
170
-		'steelblue' => '4682B4',
171
-		'tan' => 'D2B48C',
172
-		'teal' => '008080',
173
-		'thistle' => 'D8BFD8',
174
-		'tomato' => 'FF6347',
175
-		'turquoise' => '40E0D0',
176
-		'violet' => 'EE82EE',
177
-		'wheat' => 'F5DEB3',
178
-		'white' => 'FFFFFF',
179
-		'whitesmoke' => 'F5F5F5',
180
-		'yellow' => 'FFFF00',
181
-		'yellowgreen' => '9ACD32',
182
-	];
183
-	if (isset($couleurs_html[$lc = strtolower($couleur ?? '')])) {
184
-		return $couleurs_html[$lc];
185
-	}
186
-
187
-	return $couleur;
33
+    $couleurs_html = [
34
+        'aliceblue' => 'F0F8FF',
35
+        'antiquewhite' => 'FAEBD7',
36
+        'aqua' => '00FFFF',
37
+        'aquamarine' => '7FFFD4',
38
+        'azure' => 'F0FFFF',
39
+        'beige' => 'F5F5DC',
40
+        'bisque' => 'FFE4C4',
41
+        'black' => '000000',
42
+        'blanchedalmond' => 'FFEBCD',
43
+        'blue' => '0000FF',
44
+        'blueviolet' => '8A2BE2',
45
+        'brown' => 'A52A2A',
46
+        'burlywood' => 'DEB887',
47
+        'cadetblue' => '5F9EA0',
48
+        'chartreuse' => '7FFF00',
49
+        'chocolate' => 'D2691E',
50
+        'coral' => 'FF7F50',
51
+        'cornflowerblue' => '6495ED',
52
+        'cornsilk' => 'FFF8DC',
53
+        'crimson' => 'DC143C',
54
+        'cyan' => '00FFFF',
55
+        'darkblue' => '00008B',
56
+        'darkcyan' => '008B8B',
57
+        'darkgoldenrod' => 'B8860B',
58
+        'darkgray' => 'A9A9A9',
59
+        'darkgreen' => '006400',
60
+        'darkgrey' => 'A9A9A9',
61
+        'darkkhaki' => 'BDB76B',
62
+        'darkmagenta' => '8B008B',
63
+        'darkolivegreen' => '556B2F',
64
+        'darkorange' => 'FF8C00',
65
+        'darkorchid' => '9932CC',
66
+        'darkred' => '8B0000',
67
+        'darksalmon' => 'E9967A',
68
+        'darkseagreen' => '8FBC8F',
69
+        'darkslateblue' => '483D8B',
70
+        'darkslategray' => '2F4F4F',
71
+        'darkslategrey' => '2F4F4F',
72
+        'darkturquoise' => '00CED1',
73
+        'darkviolet' => '9400D3',
74
+        'deeppink' => 'FF1493',
75
+        'deepskyblue' => '00BFFF',
76
+        'dimgray' => '696969',
77
+        'dimgrey' => '696969',
78
+        'dodgerblue' => '1E90FF',
79
+        'firebrick' => 'B22222',
80
+        'floralwhite' => 'FFFAF0',
81
+        'forestgreen' => '228B22',
82
+        'fuchsia' => 'FF00FF',
83
+        'gainsboro' => 'DCDCDC',
84
+        'ghostwhite' => 'F8F8FF',
85
+        'gold' => 'FFD700',
86
+        'goldenrod' => 'DAA520',
87
+        'gray' => '808080',
88
+        'green' => '008000',
89
+        'greenyellow' => 'ADFF2F',
90
+        'grey' => '808080',
91
+        'honeydew' => 'F0FFF0',
92
+        'hotpink' => 'FF69B4',
93
+        'indianred' => 'CD5C5C',
94
+        'indigo' => '4B0082',
95
+        'ivory' => 'FFFFF0',
96
+        'khaki' => 'F0E68C',
97
+        'lavender' => 'E6E6FA',
98
+        'lavenderblush' => 'FFF0F5',
99
+        'lawngreen' => '7CFC00',
100
+        'lemonchiffon' => 'FFFACD',
101
+        'lightblue' => 'ADD8E6',
102
+        'lightcoral' => 'F08080',
103
+        'lightcyan' => 'E0FFFF',
104
+        'lightgoldenrodyellow' => 'FAFAD2',
105
+        'lightgray' => 'D3D3D3',
106
+        'lightgreen' => '90EE90',
107
+        'lightgrey' => 'D3D3D3',
108
+        'lightpink' => 'FFB6C1',
109
+        'lightsalmon' => 'FFA07A',
110
+        'lightseagreen' => '20B2AA',
111
+        'lightskyblue' => '87CEFA',
112
+        'lightslategray' => '778899',
113
+        'lightslategrey' => '778899',
114
+        'lightsteelblue' => 'B0C4DE',
115
+        'lightyellow' => 'FFFFE0',
116
+        'lime' => '00FF00',
117
+        'limegreen' => '32CD32',
118
+        'linen' => 'FAF0E6',
119
+        'magenta' => 'FF00FF',
120
+        'maroon' => '800000',
121
+        'mediumaquamarine' => '66CDAA',
122
+        'mediumblue' => '0000CD',
123
+        'mediumorchid' => 'BA55D3',
124
+        'mediumpurple' => '9370DB',
125
+        'mediumseagreen' => '3CB371',
126
+        'mediumslateblue' => '7B68EE',
127
+        'mediumspringgreen' => '00FA9A',
128
+        'mediumturquoise' => '48D1CC',
129
+        'mediumvioletred' => 'C71585',
130
+        'midnightblue' => '191970',
131
+        'mintcream' => 'F5FFFA',
132
+        'mistyrose' => 'FFE4E1',
133
+        'moccasin' => 'FFE4B5',
134
+        'navajowhite' => 'FFDEAD',
135
+        'navy' => '000080',
136
+        'oldlace' => 'FDF5E6',
137
+        'olive' => '808000',
138
+        'olivedrab' => '6B8E23',
139
+        'orange' => 'FFA500',
140
+        'orangered' => 'FF4500',
141
+        'orchid' => 'DA70D6',
142
+        'palegoldenrod' => 'EEE8AA',
143
+        'palegreen' => '98FB98',
144
+        'paleturquoise' => 'AFEEEE',
145
+        'palevioletred' => 'DB7093',
146
+        'papayawhip' => 'FFEFD5',
147
+        'peachpuff' => 'FFDAB9',
148
+        'peru' => 'CD853F',
149
+        'pink' => 'FFC0CB',
150
+        'plum' => 'DDA0DD',
151
+        'powderblue' => 'B0E0E6',
152
+        'purple' => '800080',
153
+        'rebeccapurple' => '663399',
154
+        'red' => 'FF0000',
155
+        'rosybrown' => 'BC8F8F',
156
+        'royalblue' => '4169E1',
157
+        'saddlebrown' => '8B4513',
158
+        'salmon' => 'FA8072',
159
+        'sandybrown' => 'F4A460',
160
+        'seagreen' => '2E8B57',
161
+        'seashell' => 'FFF5EE',
162
+        'sienna' => 'A0522D',
163
+        'silver' => 'C0C0C0',
164
+        'skyblue' => '87CEEB',
165
+        'slateblue' => '6A5ACD',
166
+        'slategray' => '708090',
167
+        'slategrey' => '708090',
168
+        'snow' => 'FFFAFA',
169
+        'springgreen' => '00FF7F',
170
+        'steelblue' => '4682B4',
171
+        'tan' => 'D2B48C',
172
+        'teal' => '008080',
173
+        'thistle' => 'D8BFD8',
174
+        'tomato' => 'FF6347',
175
+        'turquoise' => '40E0D0',
176
+        'violet' => 'EE82EE',
177
+        'wheat' => 'F5DEB3',
178
+        'white' => 'FFFFFF',
179
+        'whitesmoke' => 'F5F5F5',
180
+        'yellow' => 'FFFF00',
181
+        'yellowgreen' => '9ACD32',
182
+    ];
183
+    if (isset($couleurs_html[$lc = strtolower($couleur ?? '')])) {
184
+        return $couleurs_html[$lc];
185
+    }
186
+
187
+    return $couleur;
188 188
 }
189 189
 
190 190
 /**
@@ -200,16 +200,16 @@  discard block
 block discarded – undo
200 200
  * @return string Couleur tel que "hsl(200, 40%, 34%)" ou valeur formattée
201 201
  */
202 202
 function couleur_hex_to_hsl($couleur, $format = null) {
203
-	$hsl = _couleur_hex_to_hsl($couleur);
204
-	$hsl = [
205
-		'h' => round($hsl['h'] * 360),
206
-		's' => round($hsl['s'] * 100) . '%',
207
-		'l' => round($hsl['l'] * 100) . '%'
208
-	];
209
-	if ($format === null) {
210
-		return "hsl({$hsl['h']}, {$hsl['s']}, {$hsl['l']})";
211
-	}
212
-	return str_replace(array_keys($hsl), $hsl, $format);
203
+    $hsl = _couleur_hex_to_hsl($couleur);
204
+    $hsl = [
205
+        'h' => round($hsl['h'] * 360),
206
+        's' => round($hsl['s'] * 100) . '%',
207
+        'l' => round($hsl['l'] * 100) . '%'
208
+    ];
209
+    if ($format === null) {
210
+        return "hsl({$hsl['h']}, {$hsl['s']}, {$hsl['l']})";
211
+    }
212
+    return str_replace(array_keys($hsl), $hsl, $format);
213 213
 }
214 214
 
215 215
 
@@ -226,16 +226,16 @@  discard block
 block discarded – undo
226 226
  * @return string Couleur tel que "rgb(200, 40, 84)" ou valeur formattée
227 227
  */
228 228
 function couleur_hex_to_rgb($couleur, $format = null) {
229
-	$rgb = _couleur_hex_to_dec($couleur);
230
-	$rgb = [
231
-		'r' => $rgb['red'],
232
-		'g' => $rgb['green'],
233
-		'b' => $rgb['blue'],
234
-	];
235
-	if ($format === null) {
236
-		return "rgb({$rgb['r']}, {$rgb['g']}, {$rgb['b']})";
237
-	}
238
-	return str_replace(array_keys($rgb), $rgb, $format);
229
+    $rgb = _couleur_hex_to_dec($couleur);
230
+    $rgb = [
231
+        'r' => $rgb['red'],
232
+        'g' => $rgb['green'],
233
+        'b' => $rgb['blue'],
234
+    ];
235
+    if ($format === null) {
236
+        return "rgb({$rgb['r']}, {$rgb['g']}, {$rgb['b']})";
237
+    }
238
+    return str_replace(array_keys($rgb), $rgb, $format);
239 239
 }
240 240
 
241 241
 /**
@@ -251,13 +251,13 @@  discard block
 block discarded – undo
251 251
  *    Code hexadécimal de la couleur plus foncée
252 252
  */
253 253
 function couleur_foncer($couleur, $coeff = 0.5) {
254
-	$couleurs = _couleur_hex_to_dec($couleur);
254
+    $couleurs = _couleur_hex_to_dec($couleur);
255 255
 
256
-	$red = $couleurs['red'] - round(($couleurs['red']) * $coeff);
257
-	$green = $couleurs['green'] - round(($couleurs['green']) * $coeff);
258
-	$blue = $couleurs['blue'] - round(($couleurs['blue']) * $coeff);
256
+    $red = $couleurs['red'] - round(($couleurs['red']) * $coeff);
257
+    $green = $couleurs['green'] - round(($couleurs['green']) * $coeff);
258
+    $blue = $couleurs['blue'] - round(($couleurs['blue']) * $coeff);
259 259
 
260
-	return _couleur_dec_to_hex($red, $green, $blue);
260
+    return _couleur_dec_to_hex($red, $green, $blue);
261 261
 }
262 262
 
263 263
 /**
@@ -273,13 +273,13 @@  discard block
 block discarded – undo
273 273
  *    Code hexadécimal de la couleur éclaircie
274 274
  */
275 275
 function couleur_eclaircir($couleur, $coeff = 0.5) {
276
-	$couleurs = _couleur_hex_to_dec($couleur);
276
+    $couleurs = _couleur_hex_to_dec($couleur);
277 277
 
278
-	$red = $couleurs['red'] + round((255 - $couleurs['red']) * $coeff);
279
-	$green = $couleurs['green'] + round((255 - $couleurs['green']) * $coeff);
280
-	$blue = $couleurs['blue'] + round((255 - $couleurs['blue']) * $coeff);
278
+    $red = $couleurs['red'] + round((255 - $couleurs['red']) * $coeff);
279
+    $green = $couleurs['green'] + round((255 - $couleurs['green']) * $coeff);
280
+    $blue = $couleurs['blue'] + round((255 - $couleurs['blue']) * $coeff);
281 281
 
282
-	return _couleur_dec_to_hex($red, $green, $blue);
282
+    return _couleur_dec_to_hex($red, $green, $blue);
283 283
 }
284 284
 
285 285
 /**
@@ -302,27 +302,27 @@  discard block
 block discarded – undo
302 302
  *    Le tag html `<img src=... />` avec une class `filtre_inactif` ou pas
303 303
  */
304 304
 function image_select($img, $width_min = 0, $height_min = 0, $width_max = 10000, $height_max = 1000) {
305
-	if (!$img) {
306
-		return $img;
307
-	}
308
-	[$h, $l] = taille_image($img);
309
-	$select = true;
310
-	if ($l < $width_min || $l > $width_max || $h < $height_min || $h > $height_max) {
311
-		$select = false;
312
-	}
313
-
314
-	$class = extraire_attribut($img, 'class');
315
-	$p = str_contains((string) $class, 'filtre_inactif');
316
-	if (!$select && !$p) {
317
-		$class .= ' filtre_inactif';
318
-		$img = inserer_attribut($img, 'class', $class);
319
-	}
320
-	if ($select && $p) {
321
-		$class = preg_replace(',\s*(filtre_inactif),', '', $class);
322
-		$img = inserer_attribut($img, 'class', $class);
323
-	}
324
-
325
-	return $img;
305
+    if (!$img) {
306
+        return $img;
307
+    }
308
+    [$h, $l] = taille_image($img);
309
+    $select = true;
310
+    if ($l < $width_min || $l > $width_max || $h < $height_min || $h > $height_max) {
311
+        $select = false;
312
+    }
313
+
314
+    $class = extraire_attribut($img, 'class');
315
+    $p = str_contains((string) $class, 'filtre_inactif');
316
+    if (!$select && !$p) {
317
+        $class .= ' filtre_inactif';
318
+        $img = inserer_attribut($img, 'class', $class);
319
+    }
320
+    if ($select && $p) {
321
+        $class = preg_replace(',\s*(filtre_inactif),', '', $class);
322
+        $img = inserer_attribut($img, 'class', $class);
323
+    }
324
+
325
+    return $img;
326 326
 }
327 327
 
328 328
 /**
@@ -370,45 +370,45 @@  discard block
 block discarded – undo
370 370
  *     Code HTML de l'image ou du texte.
371 371
  **/
372 372
 function image_passe_partout(
373
-	$img,
374
-	$taille_x = -1,
375
-	$taille_y = -1,
376
-	$force = false,
377
-	$cherche_image = false,
378
-	$process = 'AUTO'
373
+    $img,
374
+    $taille_x = -1,
375
+    $taille_y = -1,
376
+    $force = false,
377
+    $cherche_image = false,
378
+    $process = 'AUTO'
379 379
 ) {
380
-	// PHP 7+ type hint
381
-	$img = (string)$img;
382
-	$taille_x = (int)$taille_x;
383
-	$taille_y = (int)$taille_y;
384
-	$force = (bool)$force;
385
-	$process = (string)$process;
386
-
387
-	if (!$img) {
388
-		return '';
389
-	}
390
-	[$hauteur, $largeur] = taille_image($img);
391
-	if ($taille_x === -1) {
392
-		$taille_x = $GLOBALS['meta']['taille_preview'] ?? 150;
393
-	}
394
-	if ($taille_y === -1) {
395
-		$taille_y = $taille_x;
396
-	}
397
-
398
-	if ($taille_x === 0 && $taille_y > 0) {
399
-		$taille_x = 1;
400
-	} # {0,300} -> c'est 300 qui compte
401
-	elseif ($taille_x > 0 && $taille_y === 0) {
402
-		$taille_y = 1;
403
-	} # {300,0} -> c'est 300 qui compte
404
-	elseif ($taille_x == 0 && $taille_y === 0) {
405
-		return '';
406
-	}
407
-
408
-	[$destWidth, $destHeight, $ratio] = ratio_passe_partout($largeur ?? 0, $hauteur ?? 0, $taille_x, $taille_y);
409
-	$fonction = ['image_passe_partout', func_get_args()];
410
-
411
-	return process_image_reduire($fonction, $img, $destWidth, $destHeight, $force, $process);
380
+    // PHP 7+ type hint
381
+    $img = (string)$img;
382
+    $taille_x = (int)$taille_x;
383
+    $taille_y = (int)$taille_y;
384
+    $force = (bool)$force;
385
+    $process = (string)$process;
386
+
387
+    if (!$img) {
388
+        return '';
389
+    }
390
+    [$hauteur, $largeur] = taille_image($img);
391
+    if ($taille_x === -1) {
392
+        $taille_x = $GLOBALS['meta']['taille_preview'] ?? 150;
393
+    }
394
+    if ($taille_y === -1) {
395
+        $taille_y = $taille_x;
396
+    }
397
+
398
+    if ($taille_x === 0 && $taille_y > 0) {
399
+        $taille_x = 1;
400
+    } # {0,300} -> c'est 300 qui compte
401
+    elseif ($taille_x > 0 && $taille_y === 0) {
402
+        $taille_y = 1;
403
+    } # {300,0} -> c'est 300 qui compte
404
+    elseif ($taille_x == 0 && $taille_y === 0) {
405
+        return '';
406
+    }
407
+
408
+    [$destWidth, $destHeight, $ratio] = ratio_passe_partout($largeur ?? 0, $hauteur ?? 0, $taille_x, $taille_y);
409
+    $fonction = ['image_passe_partout', func_get_args()];
410
+
411
+    return process_image_reduire($fonction, $img, $destWidth, $destHeight, $force, $process);
412 412
 }
413 413
 
414 414
 /**
@@ -451,44 +451,44 @@  discard block
 block discarded – undo
451 451
  *     Code HTML de l'image ou du texte.
452 452
  **/
453 453
 function image_reduire(
454
-	$img,
455
-	$taille = -1,
456
-	$taille_y = -1,
457
-	$force = false,
458
-	$cherche_image = false,
459
-	$process = 'AUTO'
454
+    $img,
455
+    $taille = -1,
456
+    $taille_y = -1,
457
+    $force = false,
458
+    $cherche_image = false,
459
+    $process = 'AUTO'
460 460
 ) {
461
-	// PHP 7+ type hint
462
-	$img = (string)$img;
463
-	$taille = (int)$taille;
464
-	$taille_y = (int)$taille_y;
465
-	$force = (bool)$force;
466
-	$process = (string)$process;
467
-
468
-	// Determiner la taille x,y maxi
469
-	// prendre le reglage de previsu par defaut
470
-	if ($taille === -1) {
471
-		$taille = (isset($GLOBALS['meta']['taille_preview']) && (int) $GLOBALS['meta']['taille_preview'])
472
-			? (int) $GLOBALS['meta']['taille_preview']
473
-			: 150;
474
-	}
475
-	if ($taille_y === -1) {
476
-		$taille_y = $taille;
477
-	}
478
-
479
-	if ($taille === 0 && $taille_y > 0) {
480
-		$taille = 10000;
481
-	} # {0,300} -> c'est 300 qui compte
482
-	elseif ($taille > 0 && $taille_y === 0) {
483
-		$taille_y = 10000;
484
-	} # {300,0} -> c'est 300 qui compte
485
-	elseif ($taille == 0 && $taille_y === 0) {
486
-		return '';
487
-	}
488
-
489
-	$fonction = ['image_reduire', func_get_args()];
490
-
491
-	return process_image_reduire($fonction, $img, $taille, $taille_y, $force, $process);
461
+    // PHP 7+ type hint
462
+    $img = (string)$img;
463
+    $taille = (int)$taille;
464
+    $taille_y = (int)$taille_y;
465
+    $force = (bool)$force;
466
+    $process = (string)$process;
467
+
468
+    // Determiner la taille x,y maxi
469
+    // prendre le reglage de previsu par defaut
470
+    if ($taille === -1) {
471
+        $taille = (isset($GLOBALS['meta']['taille_preview']) && (int) $GLOBALS['meta']['taille_preview'])
472
+            ? (int) $GLOBALS['meta']['taille_preview']
473
+            : 150;
474
+    }
475
+    if ($taille_y === -1) {
476
+        $taille_y = $taille;
477
+    }
478
+
479
+    if ($taille === 0 && $taille_y > 0) {
480
+        $taille = 10000;
481
+    } # {0,300} -> c'est 300 qui compte
482
+    elseif ($taille > 0 && $taille_y === 0) {
483
+        $taille_y = 10000;
484
+    } # {300,0} -> c'est 300 qui compte
485
+    elseif ($taille == 0 && $taille_y === 0) {
486
+        return '';
487
+    }
488
+
489
+    $fonction = ['image_reduire', func_get_args()];
490
+
491
+    return process_image_reduire($fonction, $img, $taille, $taille_y, $force, $process);
492 492
 }
493 493
 
494 494
 /**
@@ -499,16 +499,16 @@  discard block
 block discarded – undo
499 499
  *
500 500
  **/
501 501
 function image_recadre_avec_fallback(
502
-	$im,
503
-	$width,
504
-	$height = '-',
505
-	$position = 'focus',
506
-	$background_color = 'white'
502
+    $im,
503
+    $width,
504
+    $height = '-',
505
+    $position = 'focus',
506
+    $background_color = 'white'
507 507
 ) {
508
-	if (function_exists('image_recadre') && ($GLOBALS['meta']['image_process'] ?? '') === 'gd2') {
509
-		return image_reduire(image_recadre($im, $width . ':' . $height, '-', $position, $background_color), $width, $height);
510
-	} else { return image_passe_partout($im, $width, $height);
511
-	}
508
+    if (function_exists('image_recadre') && ($GLOBALS['meta']['image_process'] ?? '') === 'gd2') {
509
+        return image_reduire(image_recadre($im, $width . ':' . $height, '-', $position, $background_color), $width, $height);
510
+    } else { return image_passe_partout($im, $width, $height);
511
+    }
512 512
 }
513 513
 
514 514
 /**
@@ -526,23 +526,23 @@  discard block
 block discarded – undo
526 526
  *     Code HTML de l'image ou du texte.
527 527
  **/
528 528
 function image_reduire_par($img, $val = 1, $force = false) {
529
-	// PHP 7+ type hint
530
-	$img = (string)$img;
531
-	$val = (int)$val;
532
-	$force = (bool)$force;
529
+    // PHP 7+ type hint
530
+    $img = (string)$img;
531
+    $val = (int)$val;
532
+    $force = (bool)$force;
533 533
 
534
-	[$hauteur, $largeur] = taille_image($img);
534
+    [$hauteur, $largeur] = taille_image($img);
535 535
 
536
-	$l = round($largeur / $val);
537
-	$h = round($hauteur / $val);
536
+    $l = round($largeur / $val);
537
+    $h = round($hauteur / $val);
538 538
 
539
-	if ($l > $h) {
540
-		$h = 0;
541
-	} else {
542
-		$l = 0;
543
-	}
539
+    if ($l > $h) {
540
+        $h = 0;
541
+    } else {
542
+        $l = 0;
543
+    }
544 544
 
545
-	return image_reduire($img, $l, $h, $force);
545
+    return image_reduire($img, $l, $h, $force);
546 546
 }
547 547
 
548 548
 /**
@@ -565,10 +565,10 @@  discard block
 block discarded – undo
565 565
  *      Couleur en écriture hexadécimale.
566 566
 **/
567 567
 function filtre_couleur_saturation_dist($couleur, $val, $strict = false) {
568
-	if (function_exists('couleur_saturation')) {
569
-		return couleur_saturation($couleur, $val, $strict);
570
-	}
571
-	return $couleur;
568
+    if (function_exists('couleur_saturation')) {
569
+        return couleur_saturation($couleur, $val, $strict);
570
+    }
571
+    return $couleur;
572 572
 }
573 573
 
574 574
 /**
@@ -589,8 +589,8 @@  discard block
 block discarded – undo
589 589
  *      Couleur en écriture hexadécimale.
590 590
 **/
591 591
 function filtre_couleur_luminance_dist($couleur, $val) {
592
-	if (function_exists('couleur_luminance')) {
593
-		return couleur_luminance($couleur, $val);
594
-	}
595
-	return $couleur;
592
+    if (function_exists('couleur_luminance')) {
593
+        return couleur_luminance($couleur, $val);
594
+    }
595
+    return $couleur;
596 596
 }
Please login to merge, or discard this patch.
ecrire/req/mysql.php 3 patches
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -553,16 +553,14 @@
 block discarded – undo
553 553
 		if (stripos($suite, 'SELECT') !== false) {
554 554
 			if ($echappe_textes) {
555 555
 				[$suite_echap, $textes] = query_echappe_textes($suite);
556
-			}
557
-			else {
556
+			} else {
558 557
 				$suite_echap = $suite;
559 558
 			}
560 559
 			if (preg_match('/^(.*?)([(]\s*SELECT\b.*)$/si', $suite_echap, $r)) {
561 560
 				$suite_echap = $r[1] . _mysql_traite_query($r[2], $db, $prefixe, false);
562 561
 				if ($echappe_textes) {
563 562
 					$suite = query_reinjecte_textes($suite_echap, $textes);
564
-				}
565
-				else {
563
+				} else {
566 564
 					$suite = $suite_echap;
567 565
 				}
568 566
 			}
Please login to merge, or discard this patch.
Indentation   +881 added lines, -881 removed lines patch added patch discarded remove patch
@@ -19,11 +19,11 @@  discard block
 block discarded – undo
19 19
  */
20 20
 
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	return;
22
+    return;
23 23
 }
24 24
 
25 25
 if (!defined('_MYSQL_NOPLANES')) {
26
-	define('_MYSQL_NOPLANES', true);
26
+    define('_MYSQL_NOPLANES', true);
27 27
 }
28 28
 
29 29
 /**
@@ -40,113 +40,113 @@  discard block
 block discarded – undo
40 40
  *     - tableau décrivant la connexion sinon
41 41
  */
42 42
 function req_mysql_dist($host, $port, $login, #[\SensitiveParameter] $pass, $db = '', $prefixe = '') {
43
-	if (!extension_loaded(\mysqli::class)) {
44
-		return false;
45
-	}
46
-
47
-	// si port est fourni mais pas host, c'est un socket -> compat avec vieille syntaxe de mysql_connect() et anciens fichiers connect.php
48
-	try {
49
-		if (
50
-			$port
51
-			&& !is_numeric($socket = $port)
52
-			&& (!$host || $host === 'localhost')
53
-		) {
54
-			$link = @mysqli_connect($host, $login, $pass, '', null, $socket);
55
-		} elseif ($port) {
56
-			$link = @mysqli_connect($host, $login, $pass, '', $port);
57
-		} else {
58
-			$link = @mysqli_connect($host, $login, $pass);
59
-		}
60
-	} catch (\mysqli_sql_exception $e) {
61
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
62
-		$link = false;
63
-	}
64
-
65
-	if (!$link) {
66
-		spip_log('Echec mysqli_connect. Erreur : ' . mysqli_connect_error(), 'mysql.' . _LOG_HS);
67
-
68
-		return false;
69
-	}
70
-	$last = '';
71
-	if (!$db) {
72
-		$ok = $link;
73
-		$db = 'spip';
74
-	} else {
75
-		$ok = mysqli_select_db($link, $db);
76
-		if (
77
-			defined('_MYSQL_SET_SQL_MODE')
78
-			|| defined('_MYSQL_SQL_MODE_TEXT_NOT_NULL') // compatibilite
79
-		) {
80
-			mysqli_query($link, $last = "set sql_mode=''");
81
-		}
82
-	}
83
-
84
-	spip_log(
85
-		"Connexion MySQLi vers $host, base $db, prefixe $prefixe " . ($ok ? 'operationnelle' : 'impossible'),
86
-		_LOG_DEBUG
87
-	);
88
-
89
-	return !$ok ? false : [
90
-		'db' => $db,
91
-		'last' => $last,
92
-		'prefixe' => $prefixe ?: $db,
93
-		'link' => $link,
94
-		'total_requetes' => 0,
95
-	];
43
+    if (!extension_loaded(\mysqli::class)) {
44
+        return false;
45
+    }
46
+
47
+    // si port est fourni mais pas host, c'est un socket -> compat avec vieille syntaxe de mysql_connect() et anciens fichiers connect.php
48
+    try {
49
+        if (
50
+            $port
51
+            && !is_numeric($socket = $port)
52
+            && (!$host || $host === 'localhost')
53
+        ) {
54
+            $link = @mysqli_connect($host, $login, $pass, '', null, $socket);
55
+        } elseif ($port) {
56
+            $link = @mysqli_connect($host, $login, $pass, '', $port);
57
+        } else {
58
+            $link = @mysqli_connect($host, $login, $pass);
59
+        }
60
+    } catch (\mysqli_sql_exception $e) {
61
+        spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
62
+        $link = false;
63
+    }
64
+
65
+    if (!$link) {
66
+        spip_log('Echec mysqli_connect. Erreur : ' . mysqli_connect_error(), 'mysql.' . _LOG_HS);
67
+
68
+        return false;
69
+    }
70
+    $last = '';
71
+    if (!$db) {
72
+        $ok = $link;
73
+        $db = 'spip';
74
+    } else {
75
+        $ok = mysqli_select_db($link, $db);
76
+        if (
77
+            defined('_MYSQL_SET_SQL_MODE')
78
+            || defined('_MYSQL_SQL_MODE_TEXT_NOT_NULL') // compatibilite
79
+        ) {
80
+            mysqli_query($link, $last = "set sql_mode=''");
81
+        }
82
+    }
83
+
84
+    spip_log(
85
+        "Connexion MySQLi vers $host, base $db, prefixe $prefixe " . ($ok ? 'operationnelle' : 'impossible'),
86
+        _LOG_DEBUG
87
+    );
88
+
89
+    return !$ok ? false : [
90
+        'db' => $db,
91
+        'last' => $last,
92
+        'prefixe' => $prefixe ?: $db,
93
+        'link' => $link,
94
+        'total_requetes' => 0,
95
+    ];
96 96
 }
97 97
 
98 98
 
99 99
 $GLOBALS['spip_mysql_functions_1'] = [
100
-	'alter' => 'spip_mysql_alter',
101
-	'count' => 'spip_mysql_count',
102
-	'countsel' => 'spip_mysql_countsel',
103
-	'create' => 'spip_mysql_create',
104
-	'create_base' => 'spip_mysql_create_base',
105
-	'create_view' => 'spip_mysql_create_view',
106
-	'date_proche' => 'spip_mysql_date_proche',
107
-	'delete' => 'spip_mysql_delete',
108
-	'drop_table' => 'spip_mysql_drop_table',
109
-	'drop_view' => 'spip_mysql_drop_view',
110
-	'errno' => 'spip_mysql_errno',
111
-	'error' => 'spip_mysql_error',
112
-	'explain' => 'spip_mysql_explain',
113
-	'fetch' => 'spip_mysql_fetch',
114
-	'seek' => 'spip_mysql_seek',
115
-	'free' => 'spip_mysql_free',
116
-	'hex' => 'spip_mysql_hex',
117
-	'in' => 'spip_mysql_in',
118
-	'insert' => 'spip_mysql_insert',
119
-	'insertq' => 'spip_mysql_insertq',
120
-	'insertq_multi' => 'spip_mysql_insertq_multi',
121
-	'listdbs' => 'spip_mysql_listdbs',
122
-	'multi' => 'spip_mysql_multi',
123
-	'optimize' => 'spip_mysql_optimize',
124
-	'query' => 'spip_mysql_query',
125
-	'quote' => 'spip_mysql_quote',
126
-	'replace' => 'spip_mysql_replace',
127
-	'replace_multi' => 'spip_mysql_replace_multi',
128
-	'repair' => 'spip_mysql_repair',
129
-	'select' => 'spip_mysql_select',
130
-	'selectdb' => 'spip_mysql_selectdb',
131
-	'set_charset' => 'spip_mysql_set_charset',
132
-	'get_charset' => 'spip_mysql_get_charset',
133
-	'showbase' => 'spip_mysql_showbase',
134
-	'showtable' => 'spip_mysql_showtable',
135
-	'table_exists' => 'spip_mysql_table_exists',
136
-	'update' => 'spip_mysql_update',
137
-	'updateq' => 'spip_mysql_updateq',
138
-
139
-	// association de chaque nom http d'un charset aux couples MySQL
140
-	'charsets' => [
141
-		'cp1250' => ['charset' => 'cp1250', 'collation' => 'cp1250_general_ci'],
142
-		'cp1251' => ['charset' => 'cp1251', 'collation' => 'cp1251_general_ci'],
143
-		'cp1256' => ['charset' => 'cp1256', 'collation' => 'cp1256_general_ci'],
144
-		'iso-8859-1' => ['charset' => 'latin1', 'collation' => 'latin1_swedish_ci'],
100
+    'alter' => 'spip_mysql_alter',
101
+    'count' => 'spip_mysql_count',
102
+    'countsel' => 'spip_mysql_countsel',
103
+    'create' => 'spip_mysql_create',
104
+    'create_base' => 'spip_mysql_create_base',
105
+    'create_view' => 'spip_mysql_create_view',
106
+    'date_proche' => 'spip_mysql_date_proche',
107
+    'delete' => 'spip_mysql_delete',
108
+    'drop_table' => 'spip_mysql_drop_table',
109
+    'drop_view' => 'spip_mysql_drop_view',
110
+    'errno' => 'spip_mysql_errno',
111
+    'error' => 'spip_mysql_error',
112
+    'explain' => 'spip_mysql_explain',
113
+    'fetch' => 'spip_mysql_fetch',
114
+    'seek' => 'spip_mysql_seek',
115
+    'free' => 'spip_mysql_free',
116
+    'hex' => 'spip_mysql_hex',
117
+    'in' => 'spip_mysql_in',
118
+    'insert' => 'spip_mysql_insert',
119
+    'insertq' => 'spip_mysql_insertq',
120
+    'insertq_multi' => 'spip_mysql_insertq_multi',
121
+    'listdbs' => 'spip_mysql_listdbs',
122
+    'multi' => 'spip_mysql_multi',
123
+    'optimize' => 'spip_mysql_optimize',
124
+    'query' => 'spip_mysql_query',
125
+    'quote' => 'spip_mysql_quote',
126
+    'replace' => 'spip_mysql_replace',
127
+    'replace_multi' => 'spip_mysql_replace_multi',
128
+    'repair' => 'spip_mysql_repair',
129
+    'select' => 'spip_mysql_select',
130
+    'selectdb' => 'spip_mysql_selectdb',
131
+    'set_charset' => 'spip_mysql_set_charset',
132
+    'get_charset' => 'spip_mysql_get_charset',
133
+    'showbase' => 'spip_mysql_showbase',
134
+    'showtable' => 'spip_mysql_showtable',
135
+    'table_exists' => 'spip_mysql_table_exists',
136
+    'update' => 'spip_mysql_update',
137
+    'updateq' => 'spip_mysql_updateq',
138
+
139
+    // association de chaque nom http d'un charset aux couples MySQL
140
+    'charsets' => [
141
+        'cp1250' => ['charset' => 'cp1250', 'collation' => 'cp1250_general_ci'],
142
+        'cp1251' => ['charset' => 'cp1251', 'collation' => 'cp1251_general_ci'],
143
+        'cp1256' => ['charset' => 'cp1256', 'collation' => 'cp1256_general_ci'],
144
+        'iso-8859-1' => ['charset' => 'latin1', 'collation' => 'latin1_swedish_ci'],
145 145
 //'iso-8859-6'=>array('charset'=>'latin1','collation'=>'latin1_swedish_ci'),
146
-		'iso-8859-9' => ['charset' => 'latin5', 'collation' => 'latin5_turkish_ci'],
146
+        'iso-8859-9' => ['charset' => 'latin5', 'collation' => 'latin5_turkish_ci'],
147 147
 //'iso-8859-15'=>array('charset'=>'latin1','collation'=>'latin1_swedish_ci'),
148
-		'utf-8' => ['charset' => 'utf8', 'collation' => 'utf8_general_ci']
149
-	]
148
+        'utf-8' => ['charset' => 'utf8', 'collation' => 'utf8_general_ci']
149
+    ]
150 150
 ];
151 151
 
152 152
 
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
  * @return Object Information de connexion pour mysqli
158 158
  */
159 159
 function _mysql_link($serveur = '') {
160
-	$link = &$GLOBALS['connexions'][$serveur ?: 0]['link'];
160
+    $link = &$GLOBALS['connexions'][$serveur ?: 0]['link'];
161 161
 
162
-	return $link;
162
+    return $link;
163 163
 }
164 164
 
165 165
 
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
  * @return mysqli_result|bool Jeu de résultats pour fetch()
173 173
  */
174 174
 function spip_mysql_set_charset($charset, $serveur = '', $requeter = true) {
175
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
176
-	spip_log('changement de charset sql : ' . 'SET NAMES ' . _q($charset), _LOG_DEBUG);
175
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
176
+    spip_log('changement de charset sql : ' . 'SET NAMES ' . _q($charset), _LOG_DEBUG);
177 177
 
178
-	return mysqli_query($connexion['link'], $connexion['last'] = 'SET NAMES ' . _q($charset));
178
+    return mysqli_query($connexion['link'], $connexion['last'] = 'SET NAMES ' . _q($charset));
179 179
 }
180 180
 
181 181
 
@@ -188,11 +188,11 @@  discard block
 block discarded – undo
188 188
  * @return array Description du charset (son nom est dans 'charset')
189 189
  */
190 190
 function spip_mysql_get_charset($charset = [], $serveur = '', $requeter = true) {
191
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
192
-	$connexion['last'] = $c = 'SHOW CHARACTER SET'
193
-		. (!$charset ? '' : (' LIKE ' . _q($charset['charset'])));
191
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
192
+    $connexion['last'] = $c = 'SHOW CHARACTER SET'
193
+        . (!$charset ? '' : (' LIKE ' . _q($charset['charset'])));
194 194
 
195
-	return spip_mysql_fetch(mysqli_query($connexion['link'], $c), null, $serveur);
195
+    return spip_mysql_fetch(mysqli_query($connexion['link'], $c), null, $serveur);
196 196
 }
197 197
 
198 198
 /**
@@ -208,80 +208,80 @@  discard block
 block discarded – undo
208 208
  */
209 209
 function spip_mysql_query($query, $serveur = '', $requeter = true) {
210 210
 
211
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
212
-	$prefixe = $connexion['prefixe'];
213
-	$link = $connexion['link'];
214
-	$db = $connexion['db'];
215
-
216
-	$query = _mysql_traite_query($query, $db, $prefixe);
217
-
218
-	// renvoyer la requete inerte si demandee
219
-	if (!$requeter) {
220
-		return $query;
221
-	}
222
-
223
-	if (isset($_GET['var_profile']) || defined('_DEBUG_TRACE_QUERIES') && _DEBUG_TRACE_QUERIES) {
224
-		include_spip('public/tracer');
225
-		$t = trace_query_start();
226
-	} else {
227
-		$t = 0;
228
-	}
229
-
230
-	$connexion['last'] = $query;
231
-	$connexion['total_requetes']++;
232
-
233
-	// ajouter un debug utile dans log/mysql-slow.log ?
234
-	$debug = '';
235
-	if (defined('_DEBUG_SLOW_QUERIES') && _DEBUG_SLOW_QUERIES) {
236
-		if (isset($GLOBALS['debug']['aucasou'])) {
237
-			[, $id, , $infos] = $GLOBALS['debug']['aucasou'];
238
-			$debug .= "BOUCLE$id @ " . ($infos[0] ?? '') . ' | ';
239
-		}
240
-		if (isset($_SERVER['REQUEST_URI'])) {
241
-			$debug .= $_SERVER['REQUEST_URI'];
242
-		}
243
-		if (!empty($GLOBALS['ip'])) {
244
-			$debug .= ' + ' . $GLOBALS['ip'];
245
-		}
246
-		$debug = ' /* ' . mysqli_real_escape_string($link, str_replace('*/', '@/', $debug)) . ' */';
247
-	}
248
-	try {
249
-		$r = mysqli_query($link, $query . $debug);
250
-	} catch (\mysqli_sql_exception $e) {
251
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
252
-		$r = false;
253
-		// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
254
-		// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
255
-	}
256
-
257
-	//Eviter de propager le GoneAway sur les autres requetes d'un même processus PHP
258
-	if ($e = spip_mysql_errno($serveur)) {  // Log d'un Gone Away
259
-		if ($e == 2006) { //Si Gone Away on relance une connexion vierge
260
-			//Fermer la connexion defaillante
261
-			mysqli_close($connexion['link']);
262
-			unset($GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]);
263
-			//Relancer une connexion vierge
264
-			spip_connect($serveur);
265
-			$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
266
-			$link = $connexion['link'];
267
-			//On retente au cas où
268
-			try {
269
-				$r = mysqli_query($link, $query . $debug);
270
-			} catch (\mysqli_sql_exception $e) {
271
-				spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
272
-				$r = false;
273
-				// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
274
-				// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
275
-			}
276
-		}
277
-	}
278
-
279
-	// Log de l'erreur eventuelle
280
-	if ($e = spip_mysql_errno($serveur)) {
281
-		// et du fautif
282
-		$e .= spip_mysql_error($query, $serveur);
283
-	}
284
-	return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
211
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
212
+    $prefixe = $connexion['prefixe'];
213
+    $link = $connexion['link'];
214
+    $db = $connexion['db'];
215
+
216
+    $query = _mysql_traite_query($query, $db, $prefixe);
217
+
218
+    // renvoyer la requete inerte si demandee
219
+    if (!$requeter) {
220
+        return $query;
221
+    }
222
+
223
+    if (isset($_GET['var_profile']) || defined('_DEBUG_TRACE_QUERIES') && _DEBUG_TRACE_QUERIES) {
224
+        include_spip('public/tracer');
225
+        $t = trace_query_start();
226
+    } else {
227
+        $t = 0;
228
+    }
229
+
230
+    $connexion['last'] = $query;
231
+    $connexion['total_requetes']++;
232
+
233
+    // ajouter un debug utile dans log/mysql-slow.log ?
234
+    $debug = '';
235
+    if (defined('_DEBUG_SLOW_QUERIES') && _DEBUG_SLOW_QUERIES) {
236
+        if (isset($GLOBALS['debug']['aucasou'])) {
237
+            [, $id, , $infos] = $GLOBALS['debug']['aucasou'];
238
+            $debug .= "BOUCLE$id @ " . ($infos[0] ?? '') . ' | ';
239
+        }
240
+        if (isset($_SERVER['REQUEST_URI'])) {
241
+            $debug .= $_SERVER['REQUEST_URI'];
242
+        }
243
+        if (!empty($GLOBALS['ip'])) {
244
+            $debug .= ' + ' . $GLOBALS['ip'];
245
+        }
246
+        $debug = ' /* ' . mysqli_real_escape_string($link, str_replace('*/', '@/', $debug)) . ' */';
247
+    }
248
+    try {
249
+        $r = mysqli_query($link, $query . $debug);
250
+    } catch (\mysqli_sql_exception $e) {
251
+        spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
252
+        $r = false;
253
+        // TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
254
+        // mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
255
+    }
256
+
257
+    //Eviter de propager le GoneAway sur les autres requetes d'un même processus PHP
258
+    if ($e = spip_mysql_errno($serveur)) {  // Log d'un Gone Away
259
+        if ($e == 2006) { //Si Gone Away on relance une connexion vierge
260
+            //Fermer la connexion defaillante
261
+            mysqli_close($connexion['link']);
262
+            unset($GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]);
263
+            //Relancer une connexion vierge
264
+            spip_connect($serveur);
265
+            $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
266
+            $link = $connexion['link'];
267
+            //On retente au cas où
268
+            try {
269
+                $r = mysqli_query($link, $query . $debug);
270
+            } catch (\mysqli_sql_exception $e) {
271
+                spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
272
+                $r = false;
273
+                // TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
274
+                // mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
275
+            }
276
+        }
277
+    }
278
+
279
+    // Log de l'erreur eventuelle
280
+    if ($e = spip_mysql_errno($serveur)) {
281
+        // et du fautif
282
+        $e .= spip_mysql_error($query, $serveur);
283
+    }
284
+    return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
285 285
 }
286 286
 
287 287
 /**
@@ -296,12 +296,12 @@  discard block
 block discarded – undo
296 296
  *     - array  : Tableau décrivant requête et temps d'exécution si var_profile actif pour tracer.
297 297
  */
298 298
 function spip_mysql_alter($query, $serveur = '', $requeter = true) {
299
-	// ici on supprime les ` entourant le nom de table pour permettre
300
-	// la transposition du prefixe, compte tenu que les plugins ont la mauvaise habitude
301
-	// d'utiliser ceux-ci, copie-colle de phpmyadmin
302
-	$query = preg_replace(',^TABLE\s*`([^`]*)`,i', "TABLE \\1", $query);
299
+    // ici on supprime les ` entourant le nom de table pour permettre
300
+    // la transposition du prefixe, compte tenu que les plugins ont la mauvaise habitude
301
+    // d'utiliser ceux-ci, copie-colle de phpmyadmin
302
+    $query = preg_replace(',^TABLE\s*`([^`]*)`,i', "TABLE \\1", $query);
303 303
 
304
-	return spip_mysql_query('ALTER ' . $query, $serveur, $requeter); # i.e. que PG se debrouille
304
+    return spip_mysql_query('ALTER ' . $query, $serveur, $requeter); # i.e. que PG se debrouille
305 305
 }
306 306
 
307 307
 
@@ -314,9 +314,9 @@  discard block
 block discarded – undo
314 314
  * @return bool            Toujours true
315 315
  */
316 316
 function spip_mysql_optimize($table, $serveur = '', $requeter = true) {
317
-	spip_mysql_query('OPTIMIZE TABLE ' . $table);
317
+    spip_mysql_query('OPTIMIZE TABLE ' . $table);
318 318
 
319
-	return true;
319
+    return true;
320 320
 }
321 321
 
322 322
 
@@ -329,18 +329,18 @@  discard block
 block discarded – undo
329 329
  * @return array           Tableau de l'explication
330 330
  */
331 331
 function spip_mysql_explain($query, $serveur = '', $requeter = true) {
332
-	if (!str_starts_with(ltrim($query), 'SELECT')) {
333
-		return [];
334
-	}
335
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
336
-	$prefixe = $connexion['prefixe'];
337
-	$link = $connexion['link'];
338
-	$db = $connexion['db'];
339
-
340
-	$query = 'EXPLAIN ' . _mysql_traite_query($query, $db, $prefixe);
341
-	$r = mysqli_query($link, $query);
342
-
343
-	return spip_mysql_fetch($r, null, $serveur);
332
+    if (!str_starts_with(ltrim($query), 'SELECT')) {
333
+        return [];
334
+    }
335
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
336
+    $prefixe = $connexion['prefixe'];
337
+    $link = $connexion['link'];
338
+    $db = $connexion['db'];
339
+
340
+    $query = 'EXPLAIN ' . _mysql_traite_query($query, $db, $prefixe);
341
+    $r = mysqli_query($link, $query);
342
+
343
+    return spip_mysql_fetch($r, null, $serveur);
344 344
 }
345 345
 
346 346
 
@@ -369,35 +369,35 @@  discard block
 block discarded – undo
369 369
  *     - array  : Tableau décrivant requête et temps d'exécution si var_profile actif pour tracer.
370 370
  */
371 371
 function spip_mysql_select(
372
-	$select,
373
-	$from,
374
-	$where = '',
375
-	$groupby = '',
376
-	$orderby = '',
377
-	$limit = '',
378
-	$having = '',
379
-	$serveur = '',
380
-	$requeter = true
372
+    $select,
373
+    $from,
374
+    $where = '',
375
+    $groupby = '',
376
+    $orderby = '',
377
+    $limit = '',
378
+    $having = '',
379
+    $serveur = '',
380
+    $requeter = true
381 381
 ) {
382 382
 
383 383
 
384
-	$from = (!is_array($from) ? $from : spip_mysql_select_as($from));
385
-	$query =
386
-		calculer_mysql_expression('SELECT', $select, ', ')
387
-		. calculer_mysql_expression('FROM', $from, ', ')
388
-		. calculer_mysql_expression('WHERE', $where)
389
-		. calculer_mysql_expression('GROUP BY', $groupby, ',')
390
-		. calculer_mysql_expression('HAVING', $having)
391
-		. ($orderby ? ("\nORDER BY " . spip_mysql_order($orderby)) : '')
392
-		. ($limit ? "\nLIMIT $limit" : '');
384
+    $from = (!is_array($from) ? $from : spip_mysql_select_as($from));
385
+    $query =
386
+        calculer_mysql_expression('SELECT', $select, ', ')
387
+        . calculer_mysql_expression('FROM', $from, ', ')
388
+        . calculer_mysql_expression('WHERE', $where)
389
+        . calculer_mysql_expression('GROUP BY', $groupby, ',')
390
+        . calculer_mysql_expression('HAVING', $having)
391
+        . ($orderby ? ("\nORDER BY " . spip_mysql_order($orderby)) : '')
392
+        . ($limit ? "\nLIMIT $limit" : '');
393 393
 
394
-	// renvoyer la requete inerte si demandee
395
-	if ($requeter === false) {
396
-		return $query;
397
-	}
398
-	$r = spip_mysql_query($query, $serveur, $requeter);
394
+    // renvoyer la requete inerte si demandee
395
+    if ($requeter === false) {
396
+        return $query;
397
+    }
398
+    $r = spip_mysql_query($query, $serveur, $requeter);
399 399
 
400
-	return $r ?: $query;
400
+    return $r ?: $query;
401 401
 }
402 402
 
403 403
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
  * @return string texte du orderby préparé
415 415
  */
416 416
 function spip_mysql_order($orderby) {
417
-	return (is_array($orderby)) ? join(', ', $orderby) : $orderby;
417
+    return (is_array($orderby)) ? join(', ', $orderby) : $orderby;
418 418
 }
419 419
 
420 420
 
@@ -437,26 +437,26 @@  discard block
 block discarded – undo
437 437
  *     Contrainte pour clause WHERE
438 438
  */
439 439
 function calculer_mysql_where($v) {
440
-	if (!is_array($v)) {
441
-		return $v;
442
-	}
443
-
444
-	$op = array_shift($v);
445
-	if (!($n = count($v))) {
446
-		return $op;
447
-	} else {
448
-		$arg = calculer_mysql_where(array_shift($v));
449
-		if ($n == 1) {
450
-			return "$op($arg)";
451
-		} else {
452
-			$arg2 = calculer_mysql_where(array_shift($v));
453
-			if ($n == 2) {
454
-				return "($arg $op $arg2)";
455
-			} else {
456
-				return "($arg $op ($arg2) : $v[0])";
457
-			}
458
-		}
459
-	}
440
+    if (!is_array($v)) {
441
+        return $v;
442
+    }
443
+
444
+    $op = array_shift($v);
445
+    if (!($n = count($v))) {
446
+        return $op;
447
+    } else {
448
+        $arg = calculer_mysql_where(array_shift($v));
449
+        if ($n == 1) {
450
+            return "$op($arg)";
451
+        } else {
452
+            $arg2 = calculer_mysql_where(array_shift($v));
453
+            if ($n == 2) {
454
+                return "($arg $op $arg2)";
455
+            } else {
456
+                return "($arg $op ($arg2) : $v[0])";
457
+            }
458
+        }
459
+    }
460 460
 }
461 461
 
462 462
 /**
@@ -471,21 +471,21 @@  discard block
 block discarded – undo
471 471
  * @return string            texte de l'expression, une partie donc, du texte la requête.
472 472
  */
473 473
 function calculer_mysql_expression($expression, $v, $join = 'AND') {
474
-	if (empty($v)) {
475
-		return '';
476
-	}
477
-
478
-	$exp = "\n$expression ";
479
-
480
-	if (!is_array($v)) {
481
-		return $exp . $v;
482
-	} else {
483
-		if (strtoupper($join) === 'AND') {
484
-			return $exp . join("\n\t$join ", array_map('calculer_mysql_where', $v));
485
-		} else {
486
-			return $exp . join($join, $v);
487
-		}
488
-	}
474
+    if (empty($v)) {
475
+        return '';
476
+    }
477
+
478
+    $exp = "\n$expression ";
479
+
480
+    if (!is_array($v)) {
481
+        return $exp . $v;
482
+    } else {
483
+        if (strtoupper($join) === 'AND') {
484
+            return $exp . join("\n\t$join ", array_map('calculer_mysql_where', $v));
485
+        } else {
486
+            return $exp . join($join, $v);
487
+        }
488
+    }
489 489
 }
490 490
 
491 491
 
@@ -496,26 +496,26 @@  discard block
 block discarded – undo
496 496
  * @return string Sélection de colonnes pour une clause SELECT
497 497
  */
498 498
 function spip_mysql_select_as($args) {
499
-	$res = '';
500
-	foreach ($args as $k => $v) {
501
-		if (str_ends_with($k, '@')) {
502
-			// c'est une jointure qui se refere au from precedent
503
-			// pas de virgule
504
-			$res .= '  ' . $v;
505
-		} else {
506
-			if (!is_numeric($k)) {
507
-				$p = strpos($v, ' ');
508
-				if ($p) {
509
-					$v = substr($v, 0, $p) . " AS `$k`" . substr($v, $p);
510
-				} else {
511
-					$v .= " AS `$k`";
512
-				}
513
-			}
514
-			$res .= ', ' . $v;
515
-		}
516
-	}
517
-
518
-	return substr($res, 2);
499
+    $res = '';
500
+    foreach ($args as $k => $v) {
501
+        if (str_ends_with($k, '@')) {
502
+            // c'est une jointure qui se refere au from precedent
503
+            // pas de virgule
504
+            $res .= '  ' . $v;
505
+        } else {
506
+            if (!is_numeric($k)) {
507
+                $p = strpos($v, ' ');
508
+                if ($p) {
509
+                    $v = substr($v, 0, $p) . " AS `$k`" . substr($v, $p);
510
+                } else {
511
+                    $v .= " AS `$k`";
512
+                }
513
+            }
514
+            $res .= ', ' . $v;
515
+        }
516
+    }
517
+
518
+    return substr($res, 2);
519 519
 }
520 520
 
521 521
 
@@ -540,58 +540,58 @@  discard block
 block discarded – undo
540 540
  */
541 541
 function _mysql_traite_query($query, $db = '', $prefixe = '', $echappe_textes = true) {
542 542
 
543
-	if ($GLOBALS['mysql_rappel_nom_base'] && $db) {
544
-		$pref = '`' . $db . '`.';
545
-	} else {
546
-		$pref = '';
547
-	}
548
-
549
-	if ($prefixe) {
550
-		$pref .= $prefixe . '_';
551
-	}
552
-
553
-	if (!preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
554
-		$suite = '';
555
-	} else {
556
-		$suite = strstr($query, (string) $regs[0]);
557
-		$query = substr($query, 0, -strlen($suite));
558
-		// propager le prefixe en cas de requete imbriquee
559
-		// il faut alors echapper les chaine avant de le faire, pour ne pas risquer de
560
-		// modifier une requete qui est en fait juste du texte dans un champ
561
-		if (stripos($suite, 'SELECT') !== false) {
562
-			if ($echappe_textes) {
563
-				[$suite_echap, $textes] = query_echappe_textes($suite);
564
-			}
565
-			else {
566
-				$suite_echap = $suite;
567
-			}
568
-			if (preg_match('/^(.*?)([(]\s*SELECT\b.*)$/si', $suite_echap, $r)) {
569
-				$suite_echap = $r[1] . _mysql_traite_query($r[2], $db, $prefixe, false);
570
-				if ($echappe_textes) {
571
-					$suite = query_reinjecte_textes($suite_echap, $textes);
572
-				}
573
-				else {
574
-					$suite = $suite_echap;
575
-				}
576
-			}
577
-		}
578
-	}
579
-	$r = preg_replace(_SQL_PREFIXE_TABLE_MYSQL, '\1' . $pref, $query) . $suite;
580
-
581
-	// en option, remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
582
-	// remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
583
-	if (
584
-		defined('_MYSQL_NOPLANES')
585
-		&& _MYSQL_NOPLANES
586
-		&& !empty($GLOBALS['meta']['charset_sql_connexion'])
587
-		&& $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
588
-	) {
589
-		include_spip('inc/charsets');
590
-		$r = utf8_noplanes($r);
591
-	}
592
-
593
-	#spip_log("_mysql_traite_query: " . substr($r,0, 50) . ".... $db, $prefixe", _LOG_DEBUG);
594
-	return $r;
543
+    if ($GLOBALS['mysql_rappel_nom_base'] && $db) {
544
+        $pref = '`' . $db . '`.';
545
+    } else {
546
+        $pref = '';
547
+    }
548
+
549
+    if ($prefixe) {
550
+        $pref .= $prefixe . '_';
551
+    }
552
+
553
+    if (!preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
554
+        $suite = '';
555
+    } else {
556
+        $suite = strstr($query, (string) $regs[0]);
557
+        $query = substr($query, 0, -strlen($suite));
558
+        // propager le prefixe en cas de requete imbriquee
559
+        // il faut alors echapper les chaine avant de le faire, pour ne pas risquer de
560
+        // modifier une requete qui est en fait juste du texte dans un champ
561
+        if (stripos($suite, 'SELECT') !== false) {
562
+            if ($echappe_textes) {
563
+                [$suite_echap, $textes] = query_echappe_textes($suite);
564
+            }
565
+            else {
566
+                $suite_echap = $suite;
567
+            }
568
+            if (preg_match('/^(.*?)([(]\s*SELECT\b.*)$/si', $suite_echap, $r)) {
569
+                $suite_echap = $r[1] . _mysql_traite_query($r[2], $db, $prefixe, false);
570
+                if ($echappe_textes) {
571
+                    $suite = query_reinjecte_textes($suite_echap, $textes);
572
+                }
573
+                else {
574
+                    $suite = $suite_echap;
575
+                }
576
+            }
577
+        }
578
+    }
579
+    $r = preg_replace(_SQL_PREFIXE_TABLE_MYSQL, '\1' . $pref, $query) . $suite;
580
+
581
+    // en option, remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
582
+    // remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
583
+    if (
584
+        defined('_MYSQL_NOPLANES')
585
+        && _MYSQL_NOPLANES
586
+        && !empty($GLOBALS['meta']['charset_sql_connexion'])
587
+        && $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
588
+    ) {
589
+        include_spip('inc/charsets');
590
+        $r = utf8_noplanes($r);
591
+    }
592
+
593
+    #spip_log("_mysql_traite_query: " . substr($r,0, 50) . ".... $db, $prefixe", _LOG_DEBUG);
594
+    return $r;
595 595
 }
596 596
 
597 597
 /**
@@ -609,17 +609,17 @@  discard block
 block discarded – undo
609 609
  *     - False en cas d'erreur.
610 610
  **/
611 611
 function spip_mysql_selectdb($db, $serveur = '', $requeter = true) {
612
-	$link = _mysql_link($serveur);
613
-	try {
614
-		$ok = mysqli_select_db($link, $db);
615
-	} catch (\mysqli_sql_exception) {
616
-		$ok = false;
617
-	}
618
-	if (!$ok) {
619
-		spip_log('Echec mysqli_selectdb. Erreur : ' . mysqli_error($link), 'mysql.' . _LOG_CRITIQUE);
620
-	}
621
-
622
-	return $ok;
612
+    $link = _mysql_link($serveur);
613
+    try {
614
+        $ok = mysqli_select_db($link, $db);
615
+    } catch (\mysqli_sql_exception) {
616
+        $ok = false;
617
+    }
618
+    if (!$ok) {
619
+        spip_log('Echec mysqli_selectdb. Erreur : ' . mysqli_error($link), 'mysql.' . _LOG_CRITIQUE);
620
+    }
621
+
622
+    return $ok;
623 623
 }
624 624
 
625 625
 
@@ -640,14 +640,14 @@  discard block
 block discarded – undo
640 640
  *     Liste de noms de bases de données
641 641
  **/
642 642
 function spip_mysql_listdbs($serveur = '', $requeter = true) {
643
-	$dbs = [];
644
-	if ($res = spip_mysql_query('SHOW DATABASES', $serveur)) {
645
-		while ($row = mysqli_fetch_assoc($res)) {
646
-			$dbs[] = $row['Database'];
647
-		}
648
-	}
649
-
650
-	return $dbs;
643
+    $dbs = [];
644
+    if ($res = spip_mysql_query('SHOW DATABASES', $serveur)) {
645
+        while ($row = mysqli_fetch_assoc($res)) {
646
+            $dbs[] = $row['Database'];
647
+        }
648
+    }
649
+
650
+    return $dbs;
651 651
 }
652 652
 
653 653
 
@@ -670,73 +670,73 @@  discard block
 block discarded – undo
670 670
  *     - true si la requête réussie, false sinon.
671 671
  */
672 672
 function spip_mysql_create(
673
-	$nom,
674
-	$champs,
675
-	$cles,
676
-	$autoinc = false,
677
-	$temporary = false,
678
-	$serveur = '',
679
-	$requeter = true
673
+    $nom,
674
+    $champs,
675
+    $cles,
676
+    $autoinc = false,
677
+    $temporary = false,
678
+    $serveur = '',
679
+    $requeter = true
680 680
 ) {
681 681
 
682
-	$query = '';
683
-	$keys = '';
684
-	$s = '';
685
-	$p = '';
686
-
687
-	// certains plugins declarent les tables  (permet leur inclusion dans le dump)
688
-	// sans les renseigner (laisse le compilo recuperer la description)
689
-	if (!is_array($champs) || !is_array($cles)) {
690
-		return;
691
-	}
692
-
693
-	$res = spip_mysql_query('SELECT version() as v', $serveur);
694
-	if (($row = mysqli_fetch_array($res)) && (version_compare($row['v'], '5.0', '>='))) {
695
-		spip_mysql_query("SET sql_mode=''", $serveur);
696
-	}
697
-
698
-	foreach ($cles as $k => $v) {
699
-		$keys .= "$s\n\t\t$k ($v)";
700
-		if ($k == 'PRIMARY KEY') {
701
-			$p = $v;
702
-		}
703
-		$s = ',';
704
-	}
705
-	$s = '';
706
-
707
-	$character_set = '';
708
-	if (@$GLOBALS['meta']['charset_sql_base']) {
709
-		$character_set .= ' CHARACTER SET ' . $GLOBALS['meta']['charset_sql_base'];
710
-	}
711
-	if (@$GLOBALS['meta']['charset_collation_sql_base']) {
712
-		$character_set .= ' COLLATE ' . $GLOBALS['meta']['charset_collation_sql_base'];
713
-	}
714
-
715
-	foreach ($champs as $k => $v) {
716
-		$v = _mysql_remplacements_definitions_table($v);
717
-		if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
718
-			if (
719
-				preg_match(',(char|text),i', $defs[1])
720
-				&& !preg_match(',(binary|CHARACTER|COLLATE),i', $v)
721
-			) {
722
-				$v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
723
-			}
724
-		}
725
-
726
-		$query .= "$s\n\t\t$k $v"
727
-			. (($autoinc && ($p == $k) && preg_match(',\b(big|small|medium)?int\b,i', $v))
728
-				? ' auto_increment'
729
-				: ''
730
-			);
731
-		$s = ',';
732
-	}
733
-	$temporary = $temporary ? 'TEMPORARY' : '';
734
-	$q = "CREATE $temporary TABLE IF NOT EXISTS $nom ($query" . ($keys ? ",$keys" : '') . ')'
735
-		. (defined('_MYSQL_ENGINE') ? ' ENGINE=' . _MYSQL_ENGINE : '')
736
-		. ($character_set ? " DEFAULT $character_set" : '')
737
-		. "\n";
738
-
739
-	return spip_mysql_query($q, $serveur);
682
+    $query = '';
683
+    $keys = '';
684
+    $s = '';
685
+    $p = '';
686
+
687
+    // certains plugins declarent les tables  (permet leur inclusion dans le dump)
688
+    // sans les renseigner (laisse le compilo recuperer la description)
689
+    if (!is_array($champs) || !is_array($cles)) {
690
+        return;
691
+    }
692
+
693
+    $res = spip_mysql_query('SELECT version() as v', $serveur);
694
+    if (($row = mysqli_fetch_array($res)) && (version_compare($row['v'], '5.0', '>='))) {
695
+        spip_mysql_query("SET sql_mode=''", $serveur);
696
+    }
697
+
698
+    foreach ($cles as $k => $v) {
699
+        $keys .= "$s\n\t\t$k ($v)";
700
+        if ($k == 'PRIMARY KEY') {
701
+            $p = $v;
702
+        }
703
+        $s = ',';
704
+    }
705
+    $s = '';
706
+
707
+    $character_set = '';
708
+    if (@$GLOBALS['meta']['charset_sql_base']) {
709
+        $character_set .= ' CHARACTER SET ' . $GLOBALS['meta']['charset_sql_base'];
710
+    }
711
+    if (@$GLOBALS['meta']['charset_collation_sql_base']) {
712
+        $character_set .= ' COLLATE ' . $GLOBALS['meta']['charset_collation_sql_base'];
713
+    }
714
+
715
+    foreach ($champs as $k => $v) {
716
+        $v = _mysql_remplacements_definitions_table($v);
717
+        if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
718
+            if (
719
+                preg_match(',(char|text),i', $defs[1])
720
+                && !preg_match(',(binary|CHARACTER|COLLATE),i', $v)
721
+            ) {
722
+                $v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
723
+            }
724
+        }
725
+
726
+        $query .= "$s\n\t\t$k $v"
727
+            . (($autoinc && ($p == $k) && preg_match(',\b(big|small|medium)?int\b,i', $v))
728
+                ? ' auto_increment'
729
+                : ''
730
+            );
731
+        $s = ',';
732
+    }
733
+    $temporary = $temporary ? 'TEMPORARY' : '';
734
+    $q = "CREATE $temporary TABLE IF NOT EXISTS $nom ($query" . ($keys ? ",$keys" : '') . ')'
735
+        . (defined('_MYSQL_ENGINE') ? ' ENGINE=' . _MYSQL_ENGINE : '')
736
+        . ($character_set ? " DEFAULT $character_set" : '')
737
+        . "\n";
738
+
739
+    return spip_mysql_query($q, $serveur);
740 740
 }
741 741
 
742 742
 
@@ -749,25 +749,25 @@  discard block
 block discarded – undo
749 749
  *     Définition SQL adaptée pour MySQL d'un champ de table
750 750
  */
751 751
 function _mysql_remplacements_definitions_table($query) {
752
-	// quelques remplacements
753
-	$num = '(\s*\([0-9]*\))?';
754
-	$enum = '(\s*\([^\)]*\))?';
755
-
756
-	$remplace = [
757
-		'/VARCHAR(\s*[^\s\(])/is' => 'VARCHAR(255)\\1',
758
-		'/^TIMESTAMP($| NULL DEFAULT NULL)/is' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
759
-	];
760
-
761
-	if (is_string($query)) {
762
-		$query = preg_replace(array_keys($remplace), $remplace, $query);
763
-	} elseif (is_array($query)) {
764
-		$keys = array_keys($remplace);
765
-		foreach ($query as $k => $q) {
766
-			$query[$k] = preg_replace($keys, $remplace, $q);
767
-		}
768
-	}
769
-
770
-	return $query;
752
+    // quelques remplacements
753
+    $num = '(\s*\([0-9]*\))?';
754
+    $enum = '(\s*\([^\)]*\))?';
755
+
756
+    $remplace = [
757
+        '/VARCHAR(\s*[^\s\(])/is' => 'VARCHAR(255)\\1',
758
+        '/^TIMESTAMP($| NULL DEFAULT NULL)/is' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
759
+    ];
760
+
761
+    if (is_string($query)) {
762
+        $query = preg_replace(array_keys($remplace), $remplace, $query);
763
+    } elseif (is_array($query)) {
764
+        $keys = array_keys($remplace);
765
+        foreach ($query as $k => $q) {
766
+            $query[$k] = preg_replace($keys, $remplace, $q);
767
+        }
768
+    }
769
+
770
+    return $query;
771 771
 }
772 772
 
773 773
 
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
  * @return bool true si la base est créee.
781 781
  **/
782 782
 function spip_mysql_create_base($nom, $serveur = '', $requeter = true) {
783
-	return spip_mysql_query("CREATE DATABASE `$nom`", $serveur, $requeter);
783
+    return spip_mysql_query("CREATE DATABASE `$nom`", $serveur, $requeter);
784 784
 }
785 785
 
786 786
 
@@ -801,19 +801,19 @@  discard block
 block discarded – undo
801 801
  *     - string texte de la requête si $requeter vaut false
802 802
  */
803 803
 function spip_mysql_create_view($nom, $query_select, $serveur = '', $requeter = true) {
804
-	if (!$query_select) {
805
-		return false;
806
-	}
807
-	// vue deja presente
808
-	if (sql_showtable($nom, false, $serveur)) {
809
-		spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", _LOG_ERREUR);
804
+    if (!$query_select) {
805
+        return false;
806
+    }
807
+    // vue deja presente
808
+    if (sql_showtable($nom, false, $serveur)) {
809
+        spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", _LOG_ERREUR);
810 810
 
811
-		return false;
812
-	}
811
+        return false;
812
+    }
813 813
 
814
-	$query = "CREATE VIEW $nom AS " . $query_select;
814
+    $query = "CREATE VIEW $nom AS " . $query_select;
815 815
 
816
-	return spip_mysql_query($query, $serveur, $requeter);
816
+    return spip_mysql_query($query, $serveur, $requeter);
817 817
 }
818 818
 
819 819
 
@@ -829,9 +829,9 @@  discard block
 block discarded – undo
829 829
  *     - true si la requête a réussie, false sinon
830 830
  */
831 831
 function spip_mysql_drop_table($table, $exist = false, $serveur = '', $requeter = true) {
832
-	$exist = (bool) $exist ? ' IF EXISTS' : '';
832
+    $exist = (bool) $exist ? ' IF EXISTS' : '';
833 833
 
834
-	return spip_mysql_query("DROP TABLE$exist $table", $serveur, $requeter);
834
+    return spip_mysql_query("DROP TABLE$exist $table", $serveur, $requeter);
835 835
 }
836 836
 
837 837
 /**
@@ -846,9 +846,9 @@  discard block
 block discarded – undo
846 846
  *     - true si la requête a réussie, false sinon
847 847
  */
848 848
 function spip_mysql_drop_view($view, $exist = false, $serveur = '', $requeter = true) {
849
-	$exist = (bool) $exist ? ' IF EXISTS' : '';
849
+    $exist = (bool) $exist ? ' IF EXISTS' : '';
850 850
 
851
-	return spip_mysql_query("DROP VIEW$exist $view", $serveur, $requeter);
851
+    return spip_mysql_query("DROP VIEW$exist $view", $serveur, $requeter);
852 852
 }
853 853
 
854 854
 /**
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
  *     Ressource à utiliser avec sql_fetch()
866 866
  **/
867 867
 function spip_mysql_showbase($match, $serveur = '', $requeter = true) {
868
-	return spip_mysql_query('SHOW TABLES LIKE ' . _q($match), $serveur, $requeter);
868
+    return spip_mysql_query('SHOW TABLES LIKE ' . _q($match), $serveur, $requeter);
869 869
 }
870 870
 
871 871
 /**
@@ -881,18 +881,18 @@  discard block
 block discarded – undo
881 881
  *     - true si la requête a réussie, false sinon
882 882
  */
883 883
 function spip_mysql_repair($table, $serveur = '', $requeter = true) {
884
-	$table_status = spip_mysql_fetch(spip_mysql_query('SHOW TABLE STATUS WHERE Name = ' . _q($table), $serveur, true));
885
-	$engine = $table_status['Engine'];
886
-	if ($engine == 'InnoDB') {
887
-		if (spip_mysql_alter("TABLE $table ENGINE = InnoDB", $serveur, $requeter)) {
888
-			return [' OK '];
889
-		}
890
-	} elseif ($engine == 'MyISAM') {
891
-		return spip_mysql_query("REPAIR TABLE `$table`", $serveur, $requeter);
892
-	} else {
893
-		spip_log("spip_mysql_repair impossible pour la table $table engine $engine", 'mysql.' . _LOG_DEBUG);
894
-	}
895
-	return false;
884
+    $table_status = spip_mysql_fetch(spip_mysql_query('SHOW TABLE STATUS WHERE Name = ' . _q($table), $serveur, true));
885
+    $engine = $table_status['Engine'];
886
+    if ($engine == 'InnoDB') {
887
+        if (spip_mysql_alter("TABLE $table ENGINE = InnoDB", $serveur, $requeter)) {
888
+            return [' OK '];
889
+        }
890
+    } elseif ($engine == 'MyISAM') {
891
+        return spip_mysql_query("REPAIR TABLE `$table`", $serveur, $requeter);
892
+    } else {
893
+        spip_log("spip_mysql_repair impossible pour la table $table engine $engine", 'mysql.' . _LOG_DEBUG);
894
+    }
895
+    return false;
896 896
 }
897 897
 
898 898
 /**
@@ -910,12 +910,12 @@  discard block
 block discarded – undo
910 910
  *     - string : requete sql, si $requeter = true
911 911
  **/
912 912
 function spip_mysql_table_exists(string $table, $serveur = '', $requeter = true) {
913
-	$r = spip_mysql_query('SHOW TABLES LIKE ' . _q($table), $serveur, $requeter);
914
-	if (!$requeter) {
915
-		return $r;
916
-	}
917
-	$res = spip_mysql_fetch($r);
918
-	return (bool) $res;
913
+    $r = spip_mysql_query('SHOW TABLES LIKE ' . _q($table), $serveur, $requeter);
914
+    if (!$requeter) {
915
+        return $r;
916
+    }
917
+    $res = spip_mysql_fetch($r);
918
+    return (bool) $res;
919 919
 }
920 920
 
921 921
 define('_MYSQL_RE_SHOW_TABLE', '/^[^(),]*\(((?:[^()]*\((?:[^()]*\([^()]*\))?[^()]*\)[^()]*)*[^()]*)\)[^()]*$/');
@@ -938,86 +938,86 @@  discard block
 block discarded – undo
938 938
  *     - array description de la table sinon
939 939
  */
940 940
 function spip_mysql_showtable($nom_table, $serveur = '', $requeter = true) {
941
-	$s = spip_mysql_query("SHOW CREATE TABLE `$nom_table`", $serveur, $requeter);
942
-	if (!$s) {
943
-		return '';
944
-	}
945
-	if (!$requeter) {
946
-		return $s;
947
-	}
948
-
949
-	[, $a] = mysqli_fetch_array($s, MYSQLI_NUM);
950
-	if (preg_match(_MYSQL_RE_SHOW_TABLE, $a, $r)) {
951
-		$desc = $r[1];
952
-		// extraction d'une KEY éventuelle en prenant garde de ne pas
953
-		// relever un champ dont le nom contient KEY (ex. ID_WHISKEY)
954
-		if (preg_match('/^(.*?),([^,]*\sKEY[ (].*)$/s', $desc, $r)) {
955
-			$namedkeys = $r[2];
956
-			$desc = $r[1];
957
-		} else {
958
-			$namedkeys = '';
959
-		}
960
-
961
-		$fields = [];
962
-		foreach (preg_split('/,\s*`/', $desc) as $v) {
963
-			preg_match('/^\s*`?([^`]*)`\s*(.*)/', $v, $r);
964
-			$fields[strtolower($r[1])] = $r[2];
965
-		}
966
-		$keys = [];
967
-
968
-		foreach (preg_split('/\)\s*(,|$)/', $namedkeys) as $v) {
969
-			if (preg_match('/^\s*([^(]*)\(([^(]*(\(\d+\))?)$/', $v, $r)) {
970
-				$k = str_replace('`', '', trim($r[1]));
971
-				$t = strtolower(str_replace('`', '', $r[2]));
972
-				if ($k && !isset($keys[$k])) {
973
-					$keys[$k] = $t;
974
-				} else {
975
-					$keys[] = $t;
976
-				}
977
-			}
978
-		}
979
-		spip_mysql_free($s);
980
-
981
-		return ['field' => $fields, 'key' => $keys];
982
-	}
983
-
984
-	$res = spip_mysql_query("SHOW COLUMNS FROM `$nom_table`", $serveur);
985
-	if ($res) {
986
-		$nfields = [];
987
-		$nkeys = [];
988
-		while ($val = spip_mysql_fetch($res)) {
989
-			$nfields[$val['Field']] = $val['Type'];
990
-			if ($val['Null'] == 'NO') {
991
-				$nfields[$val['Field']] .= ' NOT NULL';
992
-			}
993
-			if ($val['Default'] === '0' || $val['Default']) {
994
-				if (preg_match('/[A-Z_]/', $val['Default'])) {
995
-					$nfields[$val['Field']] .= ' DEFAULT ' . $val['Default'];
996
-				} else {
997
-					$nfields[$val['Field']] .= " DEFAULT '" . $val['Default'] . "'";
998
-				}
999
-			}
1000
-			if ($val['Extra']) {
1001
-				$nfields[$val['Field']] .= ' ' . $val['Extra'];
1002
-			}
1003
-			if ($val['Key'] == 'PRI') {
1004
-				$nkeys['PRIMARY KEY'] = $val['Field'];
1005
-			} else {
1006
-				if ($val['Key'] == 'MUL') {
1007
-					$nkeys['KEY ' . $val['Field']] = $val['Field'];
1008
-				} else {
1009
-					if ($val['Key'] == 'UNI') {
1010
-						$nkeys['UNIQUE KEY ' . $val['Field']] = $val['Field'];
1011
-					}
1012
-				}
1013
-			}
1014
-		}
1015
-		spip_mysql_free($res);
1016
-
1017
-		return ['field' => $nfields, 'key' => $nkeys];
1018
-	}
1019
-
1020
-	return '';
941
+    $s = spip_mysql_query("SHOW CREATE TABLE `$nom_table`", $serveur, $requeter);
942
+    if (!$s) {
943
+        return '';
944
+    }
945
+    if (!$requeter) {
946
+        return $s;
947
+    }
948
+
949
+    [, $a] = mysqli_fetch_array($s, MYSQLI_NUM);
950
+    if (preg_match(_MYSQL_RE_SHOW_TABLE, $a, $r)) {
951
+        $desc = $r[1];
952
+        // extraction d'une KEY éventuelle en prenant garde de ne pas
953
+        // relever un champ dont le nom contient KEY (ex. ID_WHISKEY)
954
+        if (preg_match('/^(.*?),([^,]*\sKEY[ (].*)$/s', $desc, $r)) {
955
+            $namedkeys = $r[2];
956
+            $desc = $r[1];
957
+        } else {
958
+            $namedkeys = '';
959
+        }
960
+
961
+        $fields = [];
962
+        foreach (preg_split('/,\s*`/', $desc) as $v) {
963
+            preg_match('/^\s*`?([^`]*)`\s*(.*)/', $v, $r);
964
+            $fields[strtolower($r[1])] = $r[2];
965
+        }
966
+        $keys = [];
967
+
968
+        foreach (preg_split('/\)\s*(,|$)/', $namedkeys) as $v) {
969
+            if (preg_match('/^\s*([^(]*)\(([^(]*(\(\d+\))?)$/', $v, $r)) {
970
+                $k = str_replace('`', '', trim($r[1]));
971
+                $t = strtolower(str_replace('`', '', $r[2]));
972
+                if ($k && !isset($keys[$k])) {
973
+                    $keys[$k] = $t;
974
+                } else {
975
+                    $keys[] = $t;
976
+                }
977
+            }
978
+        }
979
+        spip_mysql_free($s);
980
+
981
+        return ['field' => $fields, 'key' => $keys];
982
+    }
983
+
984
+    $res = spip_mysql_query("SHOW COLUMNS FROM `$nom_table`", $serveur);
985
+    if ($res) {
986
+        $nfields = [];
987
+        $nkeys = [];
988
+        while ($val = spip_mysql_fetch($res)) {
989
+            $nfields[$val['Field']] = $val['Type'];
990
+            if ($val['Null'] == 'NO') {
991
+                $nfields[$val['Field']] .= ' NOT NULL';
992
+            }
993
+            if ($val['Default'] === '0' || $val['Default']) {
994
+                if (preg_match('/[A-Z_]/', $val['Default'])) {
995
+                    $nfields[$val['Field']] .= ' DEFAULT ' . $val['Default'];
996
+                } else {
997
+                    $nfields[$val['Field']] .= " DEFAULT '" . $val['Default'] . "'";
998
+                }
999
+            }
1000
+            if ($val['Extra']) {
1001
+                $nfields[$val['Field']] .= ' ' . $val['Extra'];
1002
+            }
1003
+            if ($val['Key'] == 'PRI') {
1004
+                $nkeys['PRIMARY KEY'] = $val['Field'];
1005
+            } else {
1006
+                if ($val['Key'] == 'MUL') {
1007
+                    $nkeys['KEY ' . $val['Field']] = $val['Field'];
1008
+                } else {
1009
+                    if ($val['Key'] == 'UNI') {
1010
+                        $nkeys['UNIQUE KEY ' . $val['Field']] = $val['Field'];
1011
+                    }
1012
+                }
1013
+            }
1014
+        }
1015
+        spip_mysql_free($res);
1016
+
1017
+        return ['field' => $nfields, 'key' => $nkeys];
1018
+    }
1019
+
1020
+    return '';
1021 1021
 }
1022 1022
 
1023 1023
 
@@ -1036,13 +1036,13 @@  discard block
 block discarded – undo
1036 1036
  *     - false Erreur
1037 1037
  */
1038 1038
 function spip_mysql_fetch($r, $t = '', $serveur = '', $requeter = true) {
1039
-	if (!$t) {
1040
-		$t = \MYSQLI_ASSOC;
1041
-	}
1042
-	if ($r) {
1043
-		return mysqli_fetch_array($r, $t);
1044
-	}
1045
-	return false;
1039
+    if (!$t) {
1040
+        $t = \MYSQLI_ASSOC;
1041
+    }
1042
+    if ($r) {
1043
+        return mysqli_fetch_array($r, $t);
1044
+    }
1045
+    return false;
1046 1046
 }
1047 1047
 
1048 1048
 /**
@@ -1055,10 +1055,10 @@  discard block
 block discarded – undo
1055 1055
  * @return bool True si déplacement réussi, false sinon.
1056 1056
  **/
1057 1057
 function spip_mysql_seek($r, $row_number, $serveur = '', $requeter = true) {
1058
-	if ($r && mysqli_num_rows($r)) {
1059
-		return mysqli_data_seek($r, $row_number);
1060
-	}
1061
-	return false;
1058
+    if ($r && mysqli_num_rows($r)) {
1059
+        return mysqli_data_seek($r, $row_number);
1060
+    }
1061
+    return false;
1062 1062
 }
1063 1063
 
1064 1064
 
@@ -1076,26 +1076,26 @@  discard block
 block discarded – undo
1076 1076
  *     - int Nombre de lignes (0 si la requête n'a pas réussie)
1077 1077
  **/
1078 1078
 function spip_mysql_countsel(
1079
-	$from = [],
1080
-	$where = [],
1081
-	$groupby = '',
1082
-	$having = [],
1083
-	$serveur = '',
1084
-	$requeter = true
1079
+    $from = [],
1080
+    $where = [],
1081
+    $groupby = '',
1082
+    $having = [],
1083
+    $serveur = '',
1084
+    $requeter = true
1085 1085
 ) {
1086
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
1087
-
1088
-	$r = spip_mysql_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
1089
-	if (!$requeter) {
1090
-		return $r;
1091
-	}
1092
-	if (!$r instanceof mysqli_result) {
1093
-		return 0;
1094
-	}
1095
-	[$c] = mysqli_fetch_array($r, MYSQLI_NUM);
1096
-	mysqli_free_result($r);
1097
-
1098
-	return intval($c);
1086
+    $c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
1087
+
1088
+    $r = spip_mysql_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
1089
+    if (!$requeter) {
1090
+        return $r;
1091
+    }
1092
+    if (!$r instanceof mysqli_result) {
1093
+        return 0;
1094
+    }
1095
+    [$c] = mysqli_fetch_array($r, MYSQLI_NUM);
1096
+    mysqli_free_result($r);
1097
+
1098
+    return intval($c);
1099 1099
 }
1100 1100
 
1101 1101
 
@@ -1118,16 +1118,16 @@  discard block
 block discarded – undo
1118 1118
  *     Erreur eventuelle
1119 1119
  **/
1120 1120
 function spip_mysql_error($query = '', $serveur = '', $requeter = true) {
1121
-	$link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1122
-	$s = mysqli_error($link);
1123
-	if ($s) {
1124
-		$trace = debug_backtrace();
1125
-		if ($trace[0]['function'] != 'spip_mysql_error') {
1126
-			spip_log("$s - $query - " . sql_error_backtrace(), 'mysql.' . _LOG_ERREUR);
1127
-		}
1128
-	}
1129
-
1130
-	return $s;
1121
+    $link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1122
+    $s = mysqli_error($link);
1123
+    if ($s) {
1124
+        $trace = debug_backtrace();
1125
+        if ($trace[0]['function'] != 'spip_mysql_error') {
1126
+            spip_log("$s - $query - " . sql_error_backtrace(), 'mysql.' . _LOG_ERREUR);
1127
+        }
1128
+    }
1129
+
1130
+    return $s;
1131 1131
 }
1132 1132
 
1133 1133
 
@@ -1142,18 +1142,18 @@  discard block
 block discarded – undo
1142 1142
  *     0, pas d'erreur. Autre, numéro de l'erreur.
1143 1143
  **/
1144 1144
 function spip_mysql_errno($serveur = '', $requeter = true) {
1145
-	$link = $GLOBALS['connexions'][$serveur ?: 0]['link'];
1146
-	$s = mysqli_errno($link);
1147
-	// 2006 MySQL server has gone away
1148
-	// 2013 Lost connection to MySQL server during query
1149
-	if (in_array($s, [2006, 2013])) {
1150
-		define('spip_interdire_cache', true);
1151
-	}
1152
-	if ($s) {
1153
-		spip_log("Erreur mysql $s", _LOG_ERREUR);
1154
-	}
1155
-
1156
-	return $s;
1145
+    $link = $GLOBALS['connexions'][$serveur ?: 0]['link'];
1146
+    $s = mysqli_errno($link);
1147
+    // 2006 MySQL server has gone away
1148
+    // 2013 Lost connection to MySQL server during query
1149
+    if (in_array($s, [2006, 2013])) {
1150
+        define('spip_interdire_cache', true);
1151
+    }
1152
+    if ($s) {
1153
+        spip_log("Erreur mysql $s", _LOG_ERREUR);
1154
+    }
1155
+
1156
+    return $s;
1157 1157
 }
1158 1158
 
1159 1159
 
@@ -1167,9 +1167,9 @@  discard block
 block discarded – undo
1167 1167
  * @return int               Nombre de lignes
1168 1168
  */
1169 1169
 function spip_mysql_count($r, $serveur = '', $requeter = true) {
1170
-	if ($r) {
1171
-		return mysqli_num_rows($r);
1172
-	}
1170
+    if ($r) {
1171
+        return mysqli_num_rows($r);
1172
+    }
1173 1173
 }
1174 1174
 
1175 1175
 
@@ -1185,11 +1185,11 @@  discard block
 block discarded – undo
1185 1185
  * @return bool              True si réussi
1186 1186
  */
1187 1187
 function spip_mysql_free($r, $serveur = '', $requeter = true) {
1188
-	if ($r instanceof mysqli_result) {
1189
-		mysqli_free_result($r);
1190
-		return true;
1191
-	}
1192
-	return false;
1188
+    if ($r instanceof mysqli_result) {
1189
+        mysqli_free_result($r);
1190
+        return true;
1191
+    }
1192
+    return false;
1193 1193
 }
1194 1194
 
1195 1195
 
@@ -1217,59 +1217,59 @@  discard block
 block discarded – undo
1217 1217
  **/
1218 1218
 function spip_mysql_insert($table, $champs, $valeurs, $desc = [], $serveur = '', $requeter = true) {
1219 1219
 
1220
-	$e = null;
1221
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1222
-	$link = $connexion['link'];
1223
-	$table = prefixer_table_spip($table, $connexion['prefixe']);
1224
-
1225
-	// remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
1226
-	if (
1227
-		defined('_MYSQL_NOPLANES')
1228
-		&& _MYSQL_NOPLANES
1229
-		&& !empty($GLOBALS['meta']['charset_sql_connexion'])
1230
-		&& $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
1231
-	) {
1232
-		include_spip('inc/charsets');
1233
-		$valeurs = utf8_noplanes($valeurs);
1234
-	}
1235
-
1236
-	$query = "INSERT INTO $table $champs VALUES $valeurs";
1237
-	if (!$requeter) {
1238
-		return $query;
1239
-	}
1240
-
1241
-	if (isset($_GET['var_profile'])) {
1242
-		include_spip('public/tracer');
1243
-		$t = trace_query_start();
1244
-		$e = '';
1245
-	} else {
1246
-		$t = 0;
1247
-	}
1248
-
1249
-	$connexion['last'] = $query;
1250
-	#spip_log($query, 'mysql.'._LOG_DEBUG);
1251
-	$r = false;
1252
-	$insert = false;
1253
-	try {
1254
-		$insert = mysqli_query($link, $query);
1255
-	} catch (\mysqli_sql_exception $e) {
1256
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
1257
-		// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
1258
-		// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
1259
-	}
1260
-	if ($insert) {
1261
-		$r = mysqli_insert_id($link);
1262
-	} else {
1263
-		// Log de l'erreur eventuelle
1264
-		if ($e = spip_mysql_errno($serveur)) {
1265
-			// et du fautif
1266
-			$e .= spip_mysql_error($query, $serveur);
1267
-		}
1268
-	}
1269
-
1270
-	return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
1271
-
1272
-	// return $r ? $r : (($r===0) ? -1 : 0); pb avec le multi-base.
1220
+    $e = null;
1221
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1222
+    $link = $connexion['link'];
1223
+    $table = prefixer_table_spip($table, $connexion['prefixe']);
1224
+
1225
+    // remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
1226
+    if (
1227
+        defined('_MYSQL_NOPLANES')
1228
+        && _MYSQL_NOPLANES
1229
+        && !empty($GLOBALS['meta']['charset_sql_connexion'])
1230
+        && $GLOBALS['meta']['charset_sql_connexion'] == 'utf8'
1231
+    ) {
1232
+        include_spip('inc/charsets');
1233
+        $valeurs = utf8_noplanes($valeurs);
1234
+    }
1235
+
1236
+    $query = "INSERT INTO $table $champs VALUES $valeurs";
1237
+    if (!$requeter) {
1238
+        return $query;
1239
+    }
1240
+
1241
+    if (isset($_GET['var_profile'])) {
1242
+        include_spip('public/tracer');
1243
+        $t = trace_query_start();
1244
+        $e = '';
1245
+    } else {
1246
+        $t = 0;
1247
+    }
1248
+
1249
+    $connexion['last'] = $query;
1250
+    #spip_log($query, 'mysql.'._LOG_DEBUG);
1251
+    $r = false;
1252
+    $insert = false;
1253
+    try {
1254
+        $insert = mysqli_query($link, $query);
1255
+    } catch (\mysqli_sql_exception $e) {
1256
+        spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
1257
+        // TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
1258
+        // mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
1259
+    }
1260
+    if ($insert) {
1261
+        $r = mysqli_insert_id($link);
1262
+    } else {
1263
+        // Log de l'erreur eventuelle
1264
+        if ($e = spip_mysql_errno($serveur)) {
1265
+            // et du fautif
1266
+            $e .= spip_mysql_error($query, $serveur);
1267
+        }
1268
+    }
1269
+
1270
+    return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
1271
+
1272
+    // return $r ? $r : (($r===0) ? -1 : 0); pb avec le multi-base.
1273 1273
 }
1274 1274
 
1275 1275
 /**
@@ -1294,26 +1294,26 @@  discard block
 block discarded – undo
1294 1294
  **/
1295 1295
 function spip_mysql_insertq($table, $couples = [], $desc = [], $serveur = '', $requeter = true) {
1296 1296
 
1297
-	if (!$desc) {
1298
-		$desc = description_table($table, $serveur);
1299
-	}
1300
-	if (!$desc) {
1301
-		$couples = [];
1302
-	}
1303
-	$fields = $desc['field'] ?? [];
1304
-
1305
-	foreach ($couples as $champ => $val) {
1306
-		$couples[$champ] = spip_mysql_cite($val, $fields[$champ]);
1307
-	}
1308
-
1309
-	return spip_mysql_insert(
1310
-		$table,
1311
-		'(' . join(',', array_keys($couples)) . ')',
1312
-		'(' . join(',', $couples) . ')',
1313
-		$desc,
1314
-		$serveur,
1315
-		$requeter
1316
-	);
1297
+    if (!$desc) {
1298
+        $desc = description_table($table, $serveur);
1299
+    }
1300
+    if (!$desc) {
1301
+        $couples = [];
1302
+    }
1303
+    $fields = $desc['field'] ?? [];
1304
+
1305
+    foreach ($couples as $champ => $val) {
1306
+        $couples[$champ] = spip_mysql_cite($val, $fields[$champ]);
1307
+    }
1308
+
1309
+    return spip_mysql_insert(
1310
+        $table,
1311
+        '(' . join(',', array_keys($couples)) . ')',
1312
+        '(' . join(',', $couples) . ')',
1313
+        $desc,
1314
+        $serveur,
1315
+        $requeter
1316
+    );
1317 1317
 }
1318 1318
 
1319 1319
 
@@ -1338,34 +1338,34 @@  discard block
 block discarded – undo
1338 1338
  **/
1339 1339
 function spip_mysql_insertq_multi($table, $tab_couples = [], $desc = [], $serveur = '', $requeter = true) {
1340 1340
 
1341
-	if (!$desc) {
1342
-		$desc = description_table($table, $serveur);
1343
-	}
1344
-	if (!$desc) {
1345
-		$tab_couples = [];
1346
-	}
1347
-	$fields = $desc['field'] ?? [];
1348
-
1349
-	$cles = '(' . join(',', array_keys(reset($tab_couples))) . ')';
1350
-	$valeurs = [];
1351
-	$r = false;
1352
-
1353
-	// Quoter et Inserer par groupes de 100 max pour eviter un debordement de pile
1354
-	foreach ($tab_couples as $couples) {
1355
-		foreach ($couples as $champ => $val) {
1356
-			$couples[$champ] = spip_mysql_cite($val, $fields[$champ]);
1357
-		}
1358
-		$valeurs[] = '(' . join(',', $couples) . ')';
1359
-		if (count($valeurs) >= 100) {
1360
-			$r = spip_mysql_insert($table, $cles, join(', ', $valeurs), $desc, $serveur, $requeter);
1361
-			$valeurs = [];
1362
-		}
1363
-	}
1364
-	if (count($valeurs)) {
1365
-		$r = spip_mysql_insert($table, $cles, join(', ', $valeurs), $desc, $serveur, $requeter);
1366
-	}
1367
-
1368
-	return $r; // dans le cas d'une table auto_increment, le dernier insert_id
1341
+    if (!$desc) {
1342
+        $desc = description_table($table, $serveur);
1343
+    }
1344
+    if (!$desc) {
1345
+        $tab_couples = [];
1346
+    }
1347
+    $fields = $desc['field'] ?? [];
1348
+
1349
+    $cles = '(' . join(',', array_keys(reset($tab_couples))) . ')';
1350
+    $valeurs = [];
1351
+    $r = false;
1352
+
1353
+    // Quoter et Inserer par groupes de 100 max pour eviter un debordement de pile
1354
+    foreach ($tab_couples as $couples) {
1355
+        foreach ($couples as $champ => $val) {
1356
+            $couples[$champ] = spip_mysql_cite($val, $fields[$champ]);
1357
+        }
1358
+        $valeurs[] = '(' . join(',', $couples) . ')';
1359
+        if (count($valeurs) >= 100) {
1360
+            $r = spip_mysql_insert($table, $cles, join(', ', $valeurs), $desc, $serveur, $requeter);
1361
+            $valeurs = [];
1362
+        }
1363
+    }
1364
+    if (count($valeurs)) {
1365
+        $r = spip_mysql_insert($table, $cles, join(', ', $valeurs), $desc, $serveur, $requeter);
1366
+    }
1367
+
1368
+    return $r; // dans le cas d'une table auto_increment, le dernier insert_id
1369 1369
 }
1370 1370
 
1371 1371
 /**
@@ -1390,20 +1390,20 @@  discard block
 block discarded – undo
1390 1390
  *     - array Tableau décrivant la requête et son temps d'exécution si var_profile est actif
1391 1391
  */
1392 1392
 function spip_mysql_update($table, $champs, $where = '', $desc = [], $serveur = '', $requeter = true) {
1393
-	$set = [];
1394
-	foreach ($champs as $champ => $val) {
1395
-		$set[] = $champ . "=$val";
1396
-	}
1397
-	if (!empty($set)) {
1398
-		return spip_mysql_query(
1399
-			calculer_mysql_expression('UPDATE', $table, ',')
1400
-			. calculer_mysql_expression('SET', $set, ',')
1401
-			. calculer_mysql_expression('WHERE', $where),
1402
-			$serveur,
1403
-			$requeter
1404
-		);
1405
-	}
1406
-	return false;
1393
+    $set = [];
1394
+    foreach ($champs as $champ => $val) {
1395
+        $set[] = $champ . "=$val";
1396
+    }
1397
+    if (!empty($set)) {
1398
+        return spip_mysql_query(
1399
+            calculer_mysql_expression('UPDATE', $table, ',')
1400
+            . calculer_mysql_expression('SET', $set, ',')
1401
+            . calculer_mysql_expression('WHERE', $where),
1402
+            $serveur,
1403
+            $requeter
1404
+        );
1405
+    }
1406
+    return false;
1407 1407
 }
1408 1408
 
1409 1409
 /**
@@ -1436,29 +1436,29 @@  discard block
 block discarded – undo
1436 1436
  */
1437 1437
 function spip_mysql_updateq($table, $champs, $where = '', $desc = [], $serveur = '', $requeter = true) {
1438 1438
 
1439
-	if (!$champs) {
1440
-		return;
1441
-	}
1442
-	if (!$desc) {
1443
-		$desc = description_table($table, $serveur);
1444
-	}
1445
-	if (!$desc) {
1446
-		$champs = [];
1447
-	} else {
1448
-		$fields = $desc['field'];
1449
-	}
1450
-	$set = [];
1451
-	foreach ($champs as $champ => $val) {
1452
-		$set[] = $champ . '=' . spip_mysql_cite($val, @$fields[$champ]);
1453
-	}
1454
-
1455
-	return spip_mysql_query(
1456
-		calculer_mysql_expression('UPDATE', $table, ',')
1457
-		. calculer_mysql_expression('SET', $set, ',')
1458
-		. calculer_mysql_expression('WHERE', $where),
1459
-		$serveur,
1460
-		$requeter
1461
-	);
1439
+    if (!$champs) {
1440
+        return;
1441
+    }
1442
+    if (!$desc) {
1443
+        $desc = description_table($table, $serveur);
1444
+    }
1445
+    if (!$desc) {
1446
+        $champs = [];
1447
+    } else {
1448
+        $fields = $desc['field'];
1449
+    }
1450
+    $set = [];
1451
+    foreach ($champs as $champ => $val) {
1452
+        $set[] = $champ . '=' . spip_mysql_cite($val, @$fields[$champ]);
1453
+    }
1454
+
1455
+    return spip_mysql_query(
1456
+        calculer_mysql_expression('UPDATE', $table, ',')
1457
+        . calculer_mysql_expression('SET', $set, ',')
1458
+        . calculer_mysql_expression('WHERE', $where),
1459
+        $serveur,
1460
+        $requeter
1461
+    );
1462 1462
 }
1463 1463
 
1464 1464
 /**
@@ -1474,22 +1474,22 @@  discard block
 block discarded – undo
1474 1474
  *     - false en cas d'erreur.
1475 1475
  **/
1476 1476
 function spip_mysql_delete($table, $where = '', $serveur = '', $requeter = true) {
1477
-	$res = spip_mysql_query(
1478
-		calculer_mysql_expression('DELETE FROM', $table, ',')
1479
-		. calculer_mysql_expression('WHERE', $where),
1480
-		$serveur,
1481
-		$requeter
1482
-	);
1483
-	if (!$requeter) {
1484
-		return $res;
1485
-	}
1486
-	if ($res) {
1487
-		$link = _mysql_link($serveur);
1488
-
1489
-		return mysqli_affected_rows($link);
1490
-	} else {
1491
-		return false;
1492
-	}
1477
+    $res = spip_mysql_query(
1478
+        calculer_mysql_expression('DELETE FROM', $table, ',')
1479
+        . calculer_mysql_expression('WHERE', $where),
1480
+        $serveur,
1481
+        $requeter
1482
+    );
1483
+    if (!$requeter) {
1484
+        return $res;
1485
+    }
1486
+    if ($res) {
1487
+        $link = _mysql_link($serveur);
1488
+
1489
+        return mysqli_affected_rows($link);
1490
+    } else {
1491
+        return false;
1492
+    }
1493 1493
 }
1494 1494
 
1495 1495
 
@@ -1518,10 +1518,10 @@  discard block
 block discarded – undo
1518 1518
  *     - false en cas d'erreur.
1519 1519
  **/
1520 1520
 function spip_mysql_replace($table, $couples, $desc = [], $serveur = '', $requeter = true) {
1521
-	return spip_mysql_query("REPLACE $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1522
-		',',
1523
-		array_map('_q', $couples)
1524
-	) . ')', $serveur, $requeter);
1521
+    return spip_mysql_query("REPLACE $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1522
+        ',',
1523
+        array_map('_q', $couples)
1524
+    ) . ')', $serveur, $requeter);
1525 1525
 }
1526 1526
 
1527 1527
 
@@ -1550,14 +1550,14 @@  discard block
 block discarded – undo
1550 1550
  *     - false en cas d'erreur.
1551 1551
  **/
1552 1552
 function spip_mysql_replace_multi($table, $tab_couples, $desc = [], $serveur = '', $requeter = true) {
1553
-	$cles = '(' . join(',', array_keys($tab_couples[0])) . ')';
1554
-	$valeurs = [];
1555
-	foreach ($tab_couples as $couples) {
1556
-		$valeurs[] = '(' . join(',', array_map('_q', $couples)) . ')';
1557
-	}
1558
-	$valeurs = implode(', ', $valeurs);
1559
-
1560
-	return spip_mysql_query("REPLACE $table $cles VALUES $valeurs", $serveur, $requeter);
1553
+    $cles = '(' . join(',', array_keys($tab_couples[0])) . ')';
1554
+    $valeurs = [];
1555
+    foreach ($tab_couples as $couples) {
1556
+        $valeurs[] = '(' . join(',', array_map('_q', $couples)) . ')';
1557
+    }
1558
+    $valeurs = implode(', ', $valeurs);
1559
+
1560
+    return spip_mysql_query("REPLACE $table $cles VALUES $valeurs", $serveur, $requeter);
1561 1561
 }
1562 1562
 
1563 1563
 
@@ -1572,32 +1572,32 @@  discard block
 block discarded – undo
1572 1572
  * @return string       texte de sélection pour la requête
1573 1573
  */
1574 1574
 function spip_mysql_multi($objet, $lang) {
1575
-	$lengthlang = strlen("[$lang]");
1576
-	$posmulti = 'INSTR(' . $objet . ", '<multi>')";
1577
-	$posfinmulti = 'INSTR(' . $objet . ", '</multi>')";
1578
-	$debutchaine = 'LEFT(' . $objet . ", $posmulti-1)";
1579
-	$finchaine = 'RIGHT(' . $objet . ', CHAR_LENGTH(' . $objet . ") -(7+$posfinmulti))";
1580
-	$chainemulti = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7, $posfinmulti -(7+$posmulti)))";
1581
-	$poslang = "INSTR($chainemulti,'[" . $lang . "]')";
1582
-	$poslang = "IF($poslang=0,INSTR($chainemulti,']')+1,$poslang+$lengthlang)";
1583
-	$chainelang = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7+$poslang-1,$posfinmulti -($posmulti+7+$poslang-1) ))";
1584
-	$posfinlang = 'INSTR(' . $chainelang . ", '[')";
1585
-	$chainelang = "IF($posfinlang>0,LEFT($chainelang,$posfinlang-1),$chainelang)";
1586
-	//$chainelang = "LEFT($chainelang,$posfinlang-1)";
1587
-	$retour = "(TRIM(IF($posmulti = 0 , " .
1588
-		'     TRIM(' . $objet . '), ' .
1589
-		'     CONCAT( ' .
1590
-		"          $debutchaine, " .
1591
-		'          IF( ' .
1592
-		"               $poslang = 0, " .
1593
-		"                     $chainemulti, " .
1594
-		"               $chainelang" .
1595
-		'          ), ' .
1596
-		"          $finchaine" .
1597
-		'     ) ' .
1598
-		'))) AS multi';
1599
-
1600
-	return $retour;
1575
+    $lengthlang = strlen("[$lang]");
1576
+    $posmulti = 'INSTR(' . $objet . ", '<multi>')";
1577
+    $posfinmulti = 'INSTR(' . $objet . ", '</multi>')";
1578
+    $debutchaine = 'LEFT(' . $objet . ", $posmulti-1)";
1579
+    $finchaine = 'RIGHT(' . $objet . ', CHAR_LENGTH(' . $objet . ") -(7+$posfinmulti))";
1580
+    $chainemulti = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7, $posfinmulti -(7+$posmulti)))";
1581
+    $poslang = "INSTR($chainemulti,'[" . $lang . "]')";
1582
+    $poslang = "IF($poslang=0,INSTR($chainemulti,']')+1,$poslang+$lengthlang)";
1583
+    $chainelang = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7+$poslang-1,$posfinmulti -($posmulti+7+$poslang-1) ))";
1584
+    $posfinlang = 'INSTR(' . $chainelang . ", '[')";
1585
+    $chainelang = "IF($posfinlang>0,LEFT($chainelang,$posfinlang-1),$chainelang)";
1586
+    //$chainelang = "LEFT($chainelang,$posfinlang-1)";
1587
+    $retour = "(TRIM(IF($posmulti = 0 , " .
1588
+        '     TRIM(' . $objet . '), ' .
1589
+        '     CONCAT( ' .
1590
+        "          $debutchaine, " .
1591
+        '          IF( ' .
1592
+        "               $poslang = 0, " .
1593
+        "                     $chainemulti, " .
1594
+        "               $chainelang" .
1595
+        '          ), ' .
1596
+        "          $finchaine" .
1597
+        '     ) ' .
1598
+        '))) AS multi';
1599
+
1600
+    return $retour;
1601 1601
 }
1602 1602
 
1603 1603
 /**
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
  *     Valeur hexadécimale pour MySQL
1612 1612
  **/
1613 1613
 function spip_mysql_hex($v) {
1614
-	return '0x' . $v;
1614
+    return '0x' . $v;
1615 1615
 }
1616 1616
 
1617 1617
 /**
@@ -1627,15 +1627,15 @@  discard block
 block discarded – undo
1627 1627
  *    Donnée prête à être utilisée par le gestionnaire SQL
1628 1628
  */
1629 1629
 function spip_mysql_quote($v, $type = '') {
1630
-	if (!is_array($v)) {
1631
-		return spip_mysql_cite($v, $type);
1632
-	}
1633
-
1634
-	// si c'est un tableau, le parcourir en propageant le type
1635
-	foreach ($v as $k => $r) {
1636
-		$v[$k] = spip_mysql_quote($r, $type);
1637
-	}
1638
-	return implode(',', $v);
1630
+    if (!is_array($v)) {
1631
+        return spip_mysql_cite($v, $type);
1632
+    }
1633
+
1634
+    // si c'est un tableau, le parcourir en propageant le type
1635
+    foreach ($v as $k => $r) {
1636
+        $v[$k] = spip_mysql_quote($r, $type);
1637
+    }
1638
+    return implode(',', $v);
1639 1639
 }
1640 1640
 
1641 1641
 /**
@@ -1651,18 +1651,18 @@  discard block
 block discarded – undo
1651 1651
  *     Expression SQL
1652 1652
  **/
1653 1653
 function spip_mysql_date_proche($champ, $interval, $unite) {
1654
-	$use_now = ( ($champ === 'maj' || strpos($champ, '.maj')) ? true : false );
1655
-	return '('
1656
-	. $champ
1657
-	. (($interval <= 0) ? '>' : '<')
1658
-	. (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1659
-	. '('
1660
-	. ($use_now ? 'NOW()' : sql_quote(date('Y-m-d H:i:s')))
1661
-	. ', INTERVAL '
1662
-	. (($interval > 0) ? $interval : (0 - $interval))
1663
-	. ' '
1664
-	. $unite
1665
-	. '))';
1654
+    $use_now = ( ($champ === 'maj' || strpos($champ, '.maj')) ? true : false );
1655
+    return '('
1656
+    . $champ
1657
+    . (($interval <= 0) ? '>' : '<')
1658
+    . (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1659
+    . '('
1660
+    . ($use_now ? 'NOW()' : sql_quote(date('Y-m-d H:i:s')))
1661
+    . ', INTERVAL '
1662
+    . (($interval > 0) ? $interval : (0 - $interval))
1663
+    . ' '
1664
+    . $unite
1665
+    . '))';
1666 1666
 }
1667 1667
 
1668 1668
 
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
  *     Expression de requête SQL
1687 1687
  **/
1688 1688
 function spip_mysql_in($val, $valeurs, $not = '', $serveur = '', $requeter = true) {
1689
-	return "($val $not IN ($valeurs))";
1689
+    return "($val $not IN ($valeurs))";
1690 1690
 }
1691 1691
 
1692 1692
 
@@ -1698,39 +1698,39 @@  discard block
 block discarded – undo
1698 1698
  * @return string|number     texte ou nombre échappé
1699 1699
  */
1700 1700
 function spip_mysql_cite($v, $type) {
1701
-	if (!$type) {
1702
-		if (is_bool($v)) {
1703
-			return strval(intval($v));
1704
-		} elseif (is_numeric($v)) {
1705
-			return strval($v);
1706
-		} elseif ($v === null) {
1707
-			return "''";
1708
-		}
1709
-		return "'" . addslashes($v) . "'";
1710
-	}
1711
-
1712
-	if ($v === null) {
1713
-		if (stripos($type, 'NOT NULL') === false) {
1714
-			// null php se traduit en NULL SQL
1715
-			return 'NULL';
1716
-		} else {
1717
-			return "''";
1718
-		}
1719
-	} elseif (sql_test_date($type) && preg_match('/^\w+\(/', $v)) {
1720
-		return $v;
1721
-	} elseif (sql_test_int($type)) {
1722
-		if (
1723
-			is_numeric($v)
1724
-			|| $v && ctype_xdigit(substr($v, 2)) && $v[0] === '0' && $v[1] === 'x'
1725
-		) {
1726
-			return $v;
1727
-		} else {
1728
-			// si pas numerique, forcer le intval
1729
-			return intval($v);
1730
-		}
1731
-	}
1732
-
1733
-	return ("'" . addslashes($v) . "'");
1701
+    if (!$type) {
1702
+        if (is_bool($v)) {
1703
+            return strval(intval($v));
1704
+        } elseif (is_numeric($v)) {
1705
+            return strval($v);
1706
+        } elseif ($v === null) {
1707
+            return "''";
1708
+        }
1709
+        return "'" . addslashes($v) . "'";
1710
+    }
1711
+
1712
+    if ($v === null) {
1713
+        if (stripos($type, 'NOT NULL') === false) {
1714
+            // null php se traduit en NULL SQL
1715
+            return 'NULL';
1716
+        } else {
1717
+            return "''";
1718
+        }
1719
+    } elseif (sql_test_date($type) && preg_match('/^\w+\(/', $v)) {
1720
+        return $v;
1721
+    } elseif (sql_test_int($type)) {
1722
+        if (
1723
+            is_numeric($v)
1724
+            || $v && ctype_xdigit(substr($v, 2)) && $v[0] === '0' && $v[1] === 'x'
1725
+        ) {
1726
+            return $v;
1727
+        } else {
1728
+            // si pas numerique, forcer le intval
1729
+            return intval($v);
1730
+        }
1731
+    }
1732
+
1733
+    return ("'" . addslashes($v) . "'");
1734 1734
 }
1735 1735
 
1736 1736
 /**
@@ -1740,7 +1740,7 @@  discard block
 block discarded – undo
1740 1740
  *     True si on a les fonctions, false sinon
1741 1741
  */
1742 1742
 function spip_versions_mysql() {
1743
-	return function_exists('mysqli_query');
1743
+    return function_exists('mysqli_query');
1744 1744
 }
1745 1745
 
1746 1746
 
@@ -1753,20 +1753,20 @@  discard block
 block discarded – undo
1753 1753
  *     - chaîne : code compilé pour le faire désactiver par SPIP sinon
1754 1754
  */
1755 1755
 function test_rappel_nom_base_mysql($server_db) {
1756
-	$GLOBALS['mysql_rappel_nom_base'] = true;
1757
-	sql_delete('spip_meta', "nom='mysql_rappel_nom_base'", $server_db);
1758
-	$ok = spip_query("INSERT INTO spip_meta (nom,valeur) VALUES ('mysql_rappel_nom_base', 'test')", $server_db);
1756
+    $GLOBALS['mysql_rappel_nom_base'] = true;
1757
+    sql_delete('spip_meta', "nom='mysql_rappel_nom_base'", $server_db);
1758
+    $ok = spip_query("INSERT INTO spip_meta (nom,valeur) VALUES ('mysql_rappel_nom_base', 'test')", $server_db);
1759 1759
 
1760
-	if ($ok) {
1761
-		sql_delete('spip_meta', "nom='mysql_rappel_nom_base'", $server_db);
1760
+    if ($ok) {
1761
+        sql_delete('spip_meta', "nom='mysql_rappel_nom_base'", $server_db);
1762 1762
 
1763
-		return '';
1764
-	} else {
1765
-		$GLOBALS['mysql_rappel_nom_base'] = false;
1763
+        return '';
1764
+    } else {
1765
+        $GLOBALS['mysql_rappel_nom_base'] = false;
1766 1766
 
1767
-		return "\$GLOBALS['mysql_rappel_nom_base'] = false; " .
1768
-		"/* echec de test_rappel_nom_base_mysql a l'installation. */\n";
1769
-	}
1767
+        return "\$GLOBALS['mysql_rappel_nom_base'] = false; " .
1768
+        "/* echec de test_rappel_nom_base_mysql a l'installation. */\n";
1769
+    }
1770 1770
 }
1771 1771
 
1772 1772
 /**
@@ -1780,13 +1780,13 @@  discard block
 block discarded – undo
1780 1780
  *     - chaîne : code compilé pour l'indiquer le résultat du test à SPIP
1781 1781
  */
1782 1782
 function test_sql_mode_mysql($server_db) {
1783
-	$res = sql_select('version() as v', '', '', '', '', '', '', $server_db);
1784
-	$row = sql_fetch($res, $server_db);
1785
-	if (version_compare($row['v'], '5.0.0', '>=')) {
1786
-		defined('_MYSQL_SET_SQL_MODE') || define('_MYSQL_SET_SQL_MODE', true);
1783
+    $res = sql_select('version() as v', '', '', '', '', '', '', $server_db);
1784
+    $row = sql_fetch($res, $server_db);
1785
+    if (version_compare($row['v'], '5.0.0', '>=')) {
1786
+        defined('_MYSQL_SET_SQL_MODE') || define('_MYSQL_SET_SQL_MODE', true);
1787 1787
 
1788
-		return "defined('_MYSQL_SET_SQL_MODE') || define('_MYSQL_SET_SQL_MODE',true);\n";
1789
-	}
1788
+        return "defined('_MYSQL_SET_SQL_MODE') || define('_MYSQL_SET_SQL_MODE',true);\n";
1789
+    }
1790 1790
 
1791
-	return '';
1791
+    return '';
1792 1792
 }
Please login to merge, or discard this patch.
Spacing   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
 			$link = @mysqli_connect($host, $login, $pass);
59 59
 		}
60 60
 	} catch (\mysqli_sql_exception $e) {
61
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
61
+		spip_log('mysqli_sql_exception: '.$e->getMessage(), 'mysql.'._LOG_DEBUG);
62 62
 		$link = false;
63 63
 	}
64 64
 
65 65
 	if (!$link) {
66
-		spip_log('Echec mysqli_connect. Erreur : ' . mysqli_connect_error(), 'mysql.' . _LOG_HS);
66
+		spip_log('Echec mysqli_connect. Erreur : '.mysqli_connect_error(), 'mysql.'._LOG_HS);
67 67
 
68 68
 		return false;
69 69
 	}
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	}
83 83
 
84 84
 	spip_log(
85
-		"Connexion MySQLi vers $host, base $db, prefixe $prefixe " . ($ok ? 'operationnelle' : 'impossible'),
85
+		"Connexion MySQLi vers $host, base $db, prefixe $prefixe ".($ok ? 'operationnelle' : 'impossible'),
86 86
 		_LOG_DEBUG
87 87
 	);
88 88
 
@@ -173,9 +173,9 @@  discard block
 block discarded – undo
173 173
  */
174 174
 function spip_mysql_set_charset($charset, $serveur = '', $requeter = true) {
175 175
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
176
-	spip_log('changement de charset sql : ' . 'SET NAMES ' . _q($charset), _LOG_DEBUG);
176
+	spip_log('changement de charset sql : '.'SET NAMES '._q($charset), _LOG_DEBUG);
177 177
 
178
-	return mysqli_query($connexion['link'], $connexion['last'] = 'SET NAMES ' . _q($charset));
178
+	return mysqli_query($connexion['link'], $connexion['last'] = 'SET NAMES '._q($charset));
179 179
 }
180 180
 
181 181
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 function spip_mysql_get_charset($charset = [], $serveur = '', $requeter = true) {
191 191
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
192 192
 	$connexion['last'] = $c = 'SHOW CHARACTER SET'
193
-		. (!$charset ? '' : (' LIKE ' . _q($charset['charset'])));
193
+		. (!$charset ? '' : (' LIKE '._q($charset['charset'])));
194 194
 
195 195
 	return spip_mysql_fetch(mysqli_query($connexion['link'], $c), null, $serveur);
196 196
 }
@@ -234,21 +234,21 @@  discard block
 block discarded – undo
234 234
 	$debug = '';
235 235
 	if (defined('_DEBUG_SLOW_QUERIES') && _DEBUG_SLOW_QUERIES) {
236 236
 		if (isset($GLOBALS['debug']['aucasou'])) {
237
-			[, $id, , $infos] = $GLOBALS['debug']['aucasou'];
238
-			$debug .= "BOUCLE$id @ " . ($infos[0] ?? '') . ' | ';
237
+			[, $id,, $infos] = $GLOBALS['debug']['aucasou'];
238
+			$debug .= "BOUCLE$id @ ".($infos[0] ?? '').' | ';
239 239
 		}
240 240
 		if (isset($_SERVER['REQUEST_URI'])) {
241 241
 			$debug .= $_SERVER['REQUEST_URI'];
242 242
 		}
243 243
 		if (!empty($GLOBALS['ip'])) {
244
-			$debug .= ' + ' . $GLOBALS['ip'];
244
+			$debug .= ' + '.$GLOBALS['ip'];
245 245
 		}
246
-		$debug = ' /* ' . mysqli_real_escape_string($link, str_replace('*/', '@/', $debug)) . ' */';
246
+		$debug = ' /* '.mysqli_real_escape_string($link, str_replace('*/', '@/', $debug)).' */';
247 247
 	}
248 248
 	try {
249
-		$r = mysqli_query($link, $query . $debug);
249
+		$r = mysqli_query($link, $query.$debug);
250 250
 	} catch (\mysqli_sql_exception $e) {
251
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
251
+		spip_log('mysqli_sql_exception: '.$e->getMessage(), 'mysql.'._LOG_DEBUG);
252 252
 		$r = false;
253 253
 		// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
254 254
 		// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
@@ -266,9 +266,9 @@  discard block
 block discarded – undo
266 266
 			$link = $connexion['link'];
267 267
 			//On retente au cas où
268 268
 			try {
269
-				$r = mysqli_query($link, $query . $debug);
269
+				$r = mysqli_query($link, $query.$debug);
270 270
 			} catch (\mysqli_sql_exception $e) {
271
-				spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
271
+				spip_log('mysqli_sql_exception: '.$e->getMessage(), 'mysql.'._LOG_DEBUG);
272 272
 				$r = false;
273 273
 				// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
274 274
 				// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	// d'utiliser ceux-ci, copie-colle de phpmyadmin
302 302
 	$query = preg_replace(',^TABLE\s*`([^`]*)`,i', "TABLE \\1", $query);
303 303
 
304
-	return spip_mysql_query('ALTER ' . $query, $serveur, $requeter); # i.e. que PG se debrouille
304
+	return spip_mysql_query('ALTER '.$query, $serveur, $requeter); # i.e. que PG se debrouille
305 305
 }
306 306
 
307 307
 
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
  * @return bool            Toujours true
315 315
  */
316 316
 function spip_mysql_optimize($table, $serveur = '', $requeter = true) {
317
-	spip_mysql_query('OPTIMIZE TABLE ' . $table);
317
+	spip_mysql_query('OPTIMIZE TABLE '.$table);
318 318
 
319 319
 	return true;
320 320
 }
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 	$link = $connexion['link'];
338 338
 	$db = $connexion['db'];
339 339
 
340
-	$query = 'EXPLAIN ' . _mysql_traite_query($query, $db, $prefixe);
340
+	$query = 'EXPLAIN '._mysql_traite_query($query, $db, $prefixe);
341 341
 	$r = mysqli_query($link, $query);
342 342
 
343 343
 	return spip_mysql_fetch($r, null, $serveur);
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 		. calculer_mysql_expression('WHERE', $where)
389 389
 		. calculer_mysql_expression('GROUP BY', $groupby, ',')
390 390
 		. calculer_mysql_expression('HAVING', $having)
391
-		. ($orderby ? ("\nORDER BY " . spip_mysql_order($orderby)) : '')
391
+		. ($orderby ? ("\nORDER BY ".spip_mysql_order($orderby)) : '')
392 392
 		. ($limit ? "\nLIMIT $limit" : '');
393 393
 
394 394
 	// renvoyer la requete inerte si demandee
@@ -478,12 +478,12 @@  discard block
 block discarded – undo
478 478
 	$exp = "\n$expression ";
479 479
 
480 480
 	if (!is_array($v)) {
481
-		return $exp . $v;
481
+		return $exp.$v;
482 482
 	} else {
483 483
 		if (strtoupper($join) === 'AND') {
484
-			return $exp . join("\n\t$join ", array_map('calculer_mysql_where', $v));
484
+			return $exp.join("\n\t$join ", array_map('calculer_mysql_where', $v));
485 485
 		} else {
486
-			return $exp . join($join, $v);
486
+			return $exp.join($join, $v);
487 487
 		}
488 488
 	}
489 489
 }
@@ -501,17 +501,17 @@  discard block
 block discarded – undo
501 501
 		if (str_ends_with($k, '@')) {
502 502
 			// c'est une jointure qui se refere au from precedent
503 503
 			// pas de virgule
504
-			$res .= '  ' . $v;
504
+			$res .= '  '.$v;
505 505
 		} else {
506 506
 			if (!is_numeric($k)) {
507 507
 				$p = strpos($v, ' ');
508 508
 				if ($p) {
509
-					$v = substr($v, 0, $p) . " AS `$k`" . substr($v, $p);
509
+					$v = substr($v, 0, $p)." AS `$k`".substr($v, $p);
510 510
 				} else {
511 511
 					$v .= " AS `$k`";
512 512
 				}
513 513
 			}
514
-			$res .= ', ' . $v;
514
+			$res .= ', '.$v;
515 515
 		}
516 516
 	}
517 517
 
@@ -541,13 +541,13 @@  discard block
 block discarded – undo
541 541
 function _mysql_traite_query($query, $db = '', $prefixe = '', $echappe_textes = true) {
542 542
 
543 543
 	if ($GLOBALS['mysql_rappel_nom_base'] && $db) {
544
-		$pref = '`' . $db . '`.';
544
+		$pref = '`'.$db.'`.';
545 545
 	} else {
546 546
 		$pref = '';
547 547
 	}
548 548
 
549 549
 	if ($prefixe) {
550
-		$pref .= $prefixe . '_';
550
+		$pref .= $prefixe.'_';
551 551
 	}
552 552
 
553 553
 	if (!preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 				$suite_echap = $suite;
567 567
 			}
568 568
 			if (preg_match('/^(.*?)([(]\s*SELECT\b.*)$/si', $suite_echap, $r)) {
569
-				$suite_echap = $r[1] . _mysql_traite_query($r[2], $db, $prefixe, false);
569
+				$suite_echap = $r[1]._mysql_traite_query($r[2], $db, $prefixe, false);
570 570
 				if ($echappe_textes) {
571 571
 					$suite = query_reinjecte_textes($suite_echap, $textes);
572 572
 				}
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 			}
577 577
 		}
578 578
 	}
579
-	$r = preg_replace(_SQL_PREFIXE_TABLE_MYSQL, '\1' . $pref, $query) . $suite;
579
+	$r = preg_replace(_SQL_PREFIXE_TABLE_MYSQL, '\1'.$pref, $query).$suite;
580 580
 
581 581
 	// en option, remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
582 582
 	// remplacer les emoji (que mysql ne sait pas gérer) en &#128169;
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		$ok = false;
617 617
 	}
618 618
 	if (!$ok) {
619
-		spip_log('Echec mysqli_selectdb. Erreur : ' . mysqli_error($link), 'mysql.' . _LOG_CRITIQUE);
619
+		spip_log('Echec mysqli_selectdb. Erreur : '.mysqli_error($link), 'mysql.'._LOG_CRITIQUE);
620 620
 	}
621 621
 
622 622
 	return $ok;
@@ -706,10 +706,10 @@  discard block
 block discarded – undo
706 706
 
707 707
 	$character_set = '';
708 708
 	if (@$GLOBALS['meta']['charset_sql_base']) {
709
-		$character_set .= ' CHARACTER SET ' . $GLOBALS['meta']['charset_sql_base'];
709
+		$character_set .= ' CHARACTER SET '.$GLOBALS['meta']['charset_sql_base'];
710 710
 	}
711 711
 	if (@$GLOBALS['meta']['charset_collation_sql_base']) {
712
-		$character_set .= ' COLLATE ' . $GLOBALS['meta']['charset_collation_sql_base'];
712
+		$character_set .= ' COLLATE '.$GLOBALS['meta']['charset_collation_sql_base'];
713 713
 	}
714 714
 
715 715
 	foreach ($champs as $k => $v) {
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 				preg_match(',(char|text),i', $defs[1])
720 720
 				&& !preg_match(',(binary|CHARACTER|COLLATE),i', $v)
721 721
 			) {
722
-				$v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
722
+				$v = $defs[1].$character_set.' '.substr($v, strlen($defs[1]));
723 723
 			}
724 724
 		}
725 725
 
@@ -731,8 +731,8 @@  discard block
 block discarded – undo
731 731
 		$s = ',';
732 732
 	}
733 733
 	$temporary = $temporary ? 'TEMPORARY' : '';
734
-	$q = "CREATE $temporary TABLE IF NOT EXISTS $nom ($query" . ($keys ? ",$keys" : '') . ')'
735
-		. (defined('_MYSQL_ENGINE') ? ' ENGINE=' . _MYSQL_ENGINE : '')
734
+	$q = "CREATE $temporary TABLE IF NOT EXISTS $nom ($query".($keys ? ",$keys" : '').')'
735
+		. (defined('_MYSQL_ENGINE') ? ' ENGINE='._MYSQL_ENGINE : '')
736 736
 		. ($character_set ? " DEFAULT $character_set" : '')
737 737
 		. "\n";
738 738
 
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
 		return false;
812 812
 	}
813 813
 
814
-	$query = "CREATE VIEW $nom AS " . $query_select;
814
+	$query = "CREATE VIEW $nom AS ".$query_select;
815 815
 
816 816
 	return spip_mysql_query($query, $serveur, $requeter);
817 817
 }
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
  *     Ressource à utiliser avec sql_fetch()
866 866
  **/
867 867
 function spip_mysql_showbase($match, $serveur = '', $requeter = true) {
868
-	return spip_mysql_query('SHOW TABLES LIKE ' . _q($match), $serveur, $requeter);
868
+	return spip_mysql_query('SHOW TABLES LIKE '._q($match), $serveur, $requeter);
869 869
 }
870 870
 
871 871
 /**
@@ -881,7 +881,7 @@  discard block
 block discarded – undo
881 881
  *     - true si la requête a réussie, false sinon
882 882
  */
883 883
 function spip_mysql_repair($table, $serveur = '', $requeter = true) {
884
-	$table_status = spip_mysql_fetch(spip_mysql_query('SHOW TABLE STATUS WHERE Name = ' . _q($table), $serveur, true));
884
+	$table_status = spip_mysql_fetch(spip_mysql_query('SHOW TABLE STATUS WHERE Name = '._q($table), $serveur, true));
885 885
 	$engine = $table_status['Engine'];
886 886
 	if ($engine == 'InnoDB') {
887 887
 		if (spip_mysql_alter("TABLE $table ENGINE = InnoDB", $serveur, $requeter)) {
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 	} elseif ($engine == 'MyISAM') {
891 891
 		return spip_mysql_query("REPAIR TABLE `$table`", $serveur, $requeter);
892 892
 	} else {
893
-		spip_log("spip_mysql_repair impossible pour la table $table engine $engine", 'mysql.' . _LOG_DEBUG);
893
+		spip_log("spip_mysql_repair impossible pour la table $table engine $engine", 'mysql.'._LOG_DEBUG);
894 894
 	}
895 895
 	return false;
896 896
 }
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
  *     - string : requete sql, si $requeter = true
911 911
  **/
912 912
 function spip_mysql_table_exists(string $table, $serveur = '', $requeter = true) {
913
-	$r = spip_mysql_query('SHOW TABLES LIKE ' . _q($table), $serveur, $requeter);
913
+	$r = spip_mysql_query('SHOW TABLES LIKE '._q($table), $serveur, $requeter);
914 914
 	if (!$requeter) {
915 915
 		return $r;
916 916
 	}
@@ -992,22 +992,22 @@  discard block
 block discarded – undo
992 992
 			}
993 993
 			if ($val['Default'] === '0' || $val['Default']) {
994 994
 				if (preg_match('/[A-Z_]/', $val['Default'])) {
995
-					$nfields[$val['Field']] .= ' DEFAULT ' . $val['Default'];
995
+					$nfields[$val['Field']] .= ' DEFAULT '.$val['Default'];
996 996
 				} else {
997
-					$nfields[$val['Field']] .= " DEFAULT '" . $val['Default'] . "'";
997
+					$nfields[$val['Field']] .= " DEFAULT '".$val['Default']."'";
998 998
 				}
999 999
 			}
1000 1000
 			if ($val['Extra']) {
1001
-				$nfields[$val['Field']] .= ' ' . $val['Extra'];
1001
+				$nfields[$val['Field']] .= ' '.$val['Extra'];
1002 1002
 			}
1003 1003
 			if ($val['Key'] == 'PRI') {
1004 1004
 				$nkeys['PRIMARY KEY'] = $val['Field'];
1005 1005
 			} else {
1006 1006
 				if ($val['Key'] == 'MUL') {
1007
-					$nkeys['KEY ' . $val['Field']] = $val['Field'];
1007
+					$nkeys['KEY '.$val['Field']] = $val['Field'];
1008 1008
 				} else {
1009 1009
 					if ($val['Key'] == 'UNI') {
1010
-						$nkeys['UNIQUE KEY ' . $val['Field']] = $val['Field'];
1010
+						$nkeys['UNIQUE KEY '.$val['Field']] = $val['Field'];
1011 1011
 					}
1012 1012
 				}
1013 1013
 			}
@@ -1083,7 +1083,7 @@  discard block
 block discarded – undo
1083 1083
 	$serveur = '',
1084 1084
 	$requeter = true
1085 1085
 ) {
1086
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
1086
+	$c = !$groupby ? '*' : ('DISTINCT '.(is_string($groupby) ? $groupby : join(',', $groupby)));
1087 1087
 
1088 1088
 	$r = spip_mysql_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
1089 1089
 	if (!$requeter) {
@@ -1123,7 +1123,7 @@  discard block
 block discarded – undo
1123 1123
 	if ($s) {
1124 1124
 		$trace = debug_backtrace();
1125 1125
 		if ($trace[0]['function'] != 'spip_mysql_error') {
1126
-			spip_log("$s - $query - " . sql_error_backtrace(), 'mysql.' . _LOG_ERREUR);
1126
+			spip_log("$s - $query - ".sql_error_backtrace(), 'mysql.'._LOG_ERREUR);
1127 1127
 		}
1128 1128
 	}
1129 1129
 
@@ -1253,7 +1253,7 @@  discard block
 block discarded – undo
1253 1253
 	try {
1254 1254
 		$insert = mysqli_query($link, $query);
1255 1255
 	} catch (\mysqli_sql_exception $e) {
1256
-		spip_log('mysqli_sql_exception: ' . $e->getMessage(), 'mysql.' . _LOG_DEBUG);
1256
+		spip_log('mysqli_sql_exception: '.$e->getMessage(), 'mysql.'._LOG_DEBUG);
1257 1257
 		// TODO: utiliser l’exception ensuite plutôt que les appels à spip_mysql_errno()
1258 1258
 		// mais il faut pour php < 8.1 forcer les exeptions via mysqli_report().
1259 1259
 	}
@@ -1308,8 +1308,8 @@  discard block
 block discarded – undo
1308 1308
 
1309 1309
 	return spip_mysql_insert(
1310 1310
 		$table,
1311
-		'(' . join(',', array_keys($couples)) . ')',
1312
-		'(' . join(',', $couples) . ')',
1311
+		'('.join(',', array_keys($couples)).')',
1312
+		'('.join(',', $couples).')',
1313 1313
 		$desc,
1314 1314
 		$serveur,
1315 1315
 		$requeter
@@ -1346,7 +1346,7 @@  discard block
 block discarded – undo
1346 1346
 	}
1347 1347
 	$fields = $desc['field'] ?? [];
1348 1348
 
1349
-	$cles = '(' . join(',', array_keys(reset($tab_couples))) . ')';
1349
+	$cles = '('.join(',', array_keys(reset($tab_couples))).')';
1350 1350
 	$valeurs = [];
1351 1351
 	$r = false;
1352 1352
 
@@ -1355,7 +1355,7 @@  discard block
 block discarded – undo
1355 1355
 		foreach ($couples as $champ => $val) {
1356 1356
 			$couples[$champ] = spip_mysql_cite($val, $fields[$champ]);
1357 1357
 		}
1358
-		$valeurs[] = '(' . join(',', $couples) . ')';
1358
+		$valeurs[] = '('.join(',', $couples).')';
1359 1359
 		if (count($valeurs) >= 100) {
1360 1360
 			$r = spip_mysql_insert($table, $cles, join(', ', $valeurs), $desc, $serveur, $requeter);
1361 1361
 			$valeurs = [];
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
 function spip_mysql_update($table, $champs, $where = '', $desc = [], $serveur = '', $requeter = true) {
1393 1393
 	$set = [];
1394 1394
 	foreach ($champs as $champ => $val) {
1395
-		$set[] = $champ . "=$val";
1395
+		$set[] = $champ."=$val";
1396 1396
 	}
1397 1397
 	if (!empty($set)) {
1398 1398
 		return spip_mysql_query(
@@ -1449,7 +1449,7 @@  discard block
 block discarded – undo
1449 1449
 	}
1450 1450
 	$set = [];
1451 1451
 	foreach ($champs as $champ => $val) {
1452
-		$set[] = $champ . '=' . spip_mysql_cite($val, @$fields[$champ]);
1452
+		$set[] = $champ.'='.spip_mysql_cite($val, @$fields[$champ]);
1453 1453
 	}
1454 1454
 
1455 1455
 	return spip_mysql_query(
@@ -1518,10 +1518,10 @@  discard block
 block discarded – undo
1518 1518
  *     - false en cas d'erreur.
1519 1519
  **/
1520 1520
 function spip_mysql_replace($table, $couples, $desc = [], $serveur = '', $requeter = true) {
1521
-	return spip_mysql_query("REPLACE $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1521
+	return spip_mysql_query("REPLACE $table (".join(',', array_keys($couples)).') VALUES ('.join(
1522 1522
 		',',
1523 1523
 		array_map('_q', $couples)
1524
-	) . ')', $serveur, $requeter);
1524
+	).')', $serveur, $requeter);
1525 1525
 }
1526 1526
 
1527 1527
 
@@ -1550,10 +1550,10 @@  discard block
 block discarded – undo
1550 1550
  *     - false en cas d'erreur.
1551 1551
  **/
1552 1552
 function spip_mysql_replace_multi($table, $tab_couples, $desc = [], $serveur = '', $requeter = true) {
1553
-	$cles = '(' . join(',', array_keys($tab_couples[0])) . ')';
1553
+	$cles = '('.join(',', array_keys($tab_couples[0])).')';
1554 1554
 	$valeurs = [];
1555 1555
 	foreach ($tab_couples as $couples) {
1556
-		$valeurs[] = '(' . join(',', array_map('_q', $couples)) . ')';
1556
+		$valeurs[] = '('.join(',', array_map('_q', $couples)).')';
1557 1557
 	}
1558 1558
 	$valeurs = implode(', ', $valeurs);
1559 1559
 
@@ -1573,28 +1573,28 @@  discard block
 block discarded – undo
1573 1573
  */
1574 1574
 function spip_mysql_multi($objet, $lang) {
1575 1575
 	$lengthlang = strlen("[$lang]");
1576
-	$posmulti = 'INSTR(' . $objet . ", '<multi>')";
1577
-	$posfinmulti = 'INSTR(' . $objet . ", '</multi>')";
1578
-	$debutchaine = 'LEFT(' . $objet . ", $posmulti-1)";
1579
-	$finchaine = 'RIGHT(' . $objet . ', CHAR_LENGTH(' . $objet . ") -(7+$posfinmulti))";
1580
-	$chainemulti = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7, $posfinmulti -(7+$posmulti)))";
1581
-	$poslang = "INSTR($chainemulti,'[" . $lang . "]')";
1576
+	$posmulti = 'INSTR('.$objet.", '<multi>')";
1577
+	$posfinmulti = 'INSTR('.$objet.", '</multi>')";
1578
+	$debutchaine = 'LEFT('.$objet.", $posmulti-1)";
1579
+	$finchaine = 'RIGHT('.$objet.', CHAR_LENGTH('.$objet.") -(7+$posfinmulti))";
1580
+	$chainemulti = 'TRIM(SUBSTRING('.$objet.", $posmulti+7, $posfinmulti -(7+$posmulti)))";
1581
+	$poslang = "INSTR($chainemulti,'[".$lang."]')";
1582 1582
 	$poslang = "IF($poslang=0,INSTR($chainemulti,']')+1,$poslang+$lengthlang)";
1583
-	$chainelang = 'TRIM(SUBSTRING(' . $objet . ", $posmulti+7+$poslang-1,$posfinmulti -($posmulti+7+$poslang-1) ))";
1584
-	$posfinlang = 'INSTR(' . $chainelang . ", '[')";
1583
+	$chainelang = 'TRIM(SUBSTRING('.$objet.", $posmulti+7+$poslang-1,$posfinmulti -($posmulti+7+$poslang-1) ))";
1584
+	$posfinlang = 'INSTR('.$chainelang.", '[')";
1585 1585
 	$chainelang = "IF($posfinlang>0,LEFT($chainelang,$posfinlang-1),$chainelang)";
1586 1586
 	//$chainelang = "LEFT($chainelang,$posfinlang-1)";
1587
-	$retour = "(TRIM(IF($posmulti = 0 , " .
1588
-		'     TRIM(' . $objet . '), ' .
1589
-		'     CONCAT( ' .
1590
-		"          $debutchaine, " .
1591
-		'          IF( ' .
1592
-		"               $poslang = 0, " .
1593
-		"                     $chainemulti, " .
1594
-		"               $chainelang" .
1595
-		'          ), ' .
1596
-		"          $finchaine" .
1597
-		'     ) ' .
1587
+	$retour = "(TRIM(IF($posmulti = 0 , ".
1588
+		'     TRIM('.$objet.'), '.
1589
+		'     CONCAT( '.
1590
+		"          $debutchaine, ".
1591
+		'          IF( '.
1592
+		"               $poslang = 0, ".
1593
+		"                     $chainemulti, ".
1594
+		"               $chainelang".
1595
+		'          ), '.
1596
+		"          $finchaine".
1597
+		'     ) '.
1598 1598
 		'))) AS multi';
1599 1599
 
1600 1600
 	return $retour;
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
  *     Valeur hexadécimale pour MySQL
1612 1612
  **/
1613 1613
 function spip_mysql_hex($v) {
1614
-	return '0x' . $v;
1614
+	return '0x'.$v;
1615 1615
 }
1616 1616
 
1617 1617
 /**
@@ -1651,7 +1651,7 @@  discard block
 block discarded – undo
1651 1651
  *     Expression SQL
1652 1652
  **/
1653 1653
 function spip_mysql_date_proche($champ, $interval, $unite) {
1654
-	$use_now = ( ($champ === 'maj' || strpos($champ, '.maj')) ? true : false );
1654
+	$use_now = (($champ === 'maj' || strpos($champ, '.maj')) ? true : false);
1655 1655
 	return '('
1656 1656
 	. $champ
1657 1657
 	. (($interval <= 0) ? '>' : '<')
@@ -1706,7 +1706,7 @@  discard block
 block discarded – undo
1706 1706
 		} elseif ($v === null) {
1707 1707
 			return "''";
1708 1708
 		}
1709
-		return "'" . addslashes($v) . "'";
1709
+		return "'".addslashes($v)."'";
1710 1710
 	}
1711 1711
 
1712 1712
 	if ($v === null) {
@@ -1730,7 +1730,7 @@  discard block
 block discarded – undo
1730 1730
 		}
1731 1731
 	}
1732 1732
 
1733
-	return ("'" . addslashes($v) . "'");
1733
+	return ("'".addslashes($v)."'");
1734 1734
 }
1735 1735
 
1736 1736
 /**
@@ -1764,7 +1764,7 @@  discard block
 block discarded – undo
1764 1764
 	} else {
1765 1765
 		$GLOBALS['mysql_rappel_nom_base'] = false;
1766 1766
 
1767
-		return "\$GLOBALS['mysql_rappel_nom_base'] = false; " .
1767
+		return "\$GLOBALS['mysql_rappel_nom_base'] = false; ".
1768 1768
 		"/* echec de test_rappel_nom_base_mysql a l'installation. */\n";
1769 1769
 	}
1770 1770
 }
Please login to merge, or discard this patch.
ecrire/xml/indenter.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -63,9 +63,9 @@
 block discarded – undo
63 63
 	$f = new IndenteurXML();
64 64
 	$sax($page, $apply, $f);
65 65
 	if (!$f->err) {
66
-		return $f->entete . $f->res;
66
+		return $f->entete.$f->res;
67 67
 	}
68
-	spip_log('indentation impossible ' . (is_countable($f->err) ? count($f->err) : 0) . ' erreurs de validation');
68
+	spip_log('indentation impossible '.(is_countable($f->err) ? count($f->err) : 0).' erreurs de validation');
69 69
 
70
-	return $f->entete . $f->page;
70
+	return $f->entete.$f->page;
71 71
 }
Please login to merge, or discard this patch.
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -10,54 +10,54 @@
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 class IndenteurXML {
17
-	public function debutElement($phraseur, $name, $attrs) {
18
-		xml_debutElement($this, $name, $attrs);
19
-	}
20
-
21
-	public function finElement($phraseur, $name) {
22
-		xml_finElement($this, $name);
23
-	}
24
-
25
-	public function textElement($phraseur, $data) {
26
-		xml_textElement($this, $data);
27
-	}
28
-
29
-	public function piElement($phraseur, $target, $data) {
30
-		xml_PiElement($this, $target, $data);
31
-	}
32
-
33
-	public function defaultElement($phraseur, $data) {
34
-		xml_defaultElement($this, $data);
35
-	}
36
-
37
-	public function phraserTout($phraseur, $data) {
38
-		xml_parsestring($this, $data);
39
-	}
40
-
41
-	public $depth = '';
42
-	public $res = '';
43
-	public $err = [];
44
-	public $contenu = [];
45
-	public $ouvrant = [];
46
-	public $reperes = [];
47
-	public $entete = '';
48
-	public $page = '';
49
-	public $dtc = null;
50
-	public $sax = null;
17
+    public function debutElement($phraseur, $name, $attrs) {
18
+        xml_debutElement($this, $name, $attrs);
19
+    }
20
+
21
+    public function finElement($phraseur, $name) {
22
+        xml_finElement($this, $name);
23
+    }
24
+
25
+    public function textElement($phraseur, $data) {
26
+        xml_textElement($this, $data);
27
+    }
28
+
29
+    public function piElement($phraseur, $target, $data) {
30
+        xml_PiElement($this, $target, $data);
31
+    }
32
+
33
+    public function defaultElement($phraseur, $data) {
34
+        xml_defaultElement($this, $data);
35
+    }
36
+
37
+    public function phraserTout($phraseur, $data) {
38
+        xml_parsestring($this, $data);
39
+    }
40
+
41
+    public $depth = '';
42
+    public $res = '';
43
+    public $err = [];
44
+    public $contenu = [];
45
+    public $ouvrant = [];
46
+    public $reperes = [];
47
+    public $entete = '';
48
+    public $page = '';
49
+    public $dtc = null;
50
+    public $sax = null;
51 51
 }
52 52
 
53 53
 function xml_indenter_dist($page, $apply = false) {
54
-	$sax = charger_fonction('sax', 'xml');
55
-	$f = new IndenteurXML();
56
-	$sax($page, $apply, $f);
57
-	if (!$f->err) {
58
-		return $f->entete . $f->res;
59
-	}
60
-	spip_log('indentation impossible ' . (is_countable($f->err) ? count($f->err) : 0) . ' erreurs de validation');
61
-
62
-	return $f->entete . $f->page;
54
+    $sax = charger_fonction('sax', 'xml');
55
+    $f = new IndenteurXML();
56
+    $sax($page, $apply, $f);
57
+    if (!$f->err) {
58
+        return $f->entete . $f->res;
59
+    }
60
+    spip_log('indentation impossible ' . (is_countable($f->err) ? count($f->err) : 0) . ' erreurs de validation');
61
+
62
+    return $f->entete . $f->page;
63 63
 }
Please login to merge, or discard this patch.
ecrire/inc/presentation.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Presentation
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 include_spip('inc/presentation_mini');
@@ -31,141 +31,141 @@  discard block
 block discarded – undo
31 31
 include_spip('inc/filtres_alertes');
32 32
 
33 33
 function debut_cadre($style, $icone = '', $fonction = '', $titre = '', $id = '', $class = '', $padding = true) {
34
-	$fond = null;
35
-	$style_mapping = [
36
-		'r' => 'simple',
37
-		'e' => 'raccourcis',
38
-		'couleur' => 'basic highlight',
39
-		'couleur-foncee' => 'basic highlight',
40
-		'trait-couleur' => 'important',
41
-		'alerte' => 'notice',
42
-		'info' => 'info',
43
-		'sous_rub' => 'simple sous-rub'
44
-	];
45
-	$style_titre_mapping = ['couleur' => 'topper', 'trait-couleur' => 'section'];
46
-	$c = $style_mapping[$style] ?? 'simple';
47
-	$class = $c . ($class ? " $class" : '');
48
-	if (!$padding) {
49
-		$class .= ($class ? ' ' : '') . 'no-padding';
50
-	}
51
-
52
-	//($id?"id='$id' ":"")
53
-	if (strlen($icone) > 1) {
54
-		if ($icone_renommer = charger_fonction('icone_renommer', 'inc', true)) {
55
-			[$fond, $fonction] = $icone_renommer($icone, $fonction);
56
-		}
57
-		$size = 24;
58
-		if (preg_match('/-([0-9]{1,3})[.](gif|png)$/i', $fond, $match)) {
59
-			$size = $match[1];
60
-		}
61
-		if ($fonction) {
62
-			// 2 images pour composer l'icone : le fond (article) en background,
63
-			// la fonction (new) en image
64
-			$icone = http_img_pack($fonction, '', "class='cadre-icone' width='$size' height='$size'\n" .
65
-				http_style_background($fond, 'no-repeat center center', $size));
66
-		} else {
67
-			$icone = http_img_pack($fond, '', "class='cadre-icone' width='$size' height='$size'");
68
-		}
69
-		$titre = $icone . $titre;
70
-	}
71
-
72
-	return boite_ouvrir($titre, $class, $style_titre_mapping[$style] ?? '', $id);
34
+    $fond = null;
35
+    $style_mapping = [
36
+        'r' => 'simple',
37
+        'e' => 'raccourcis',
38
+        'couleur' => 'basic highlight',
39
+        'couleur-foncee' => 'basic highlight',
40
+        'trait-couleur' => 'important',
41
+        'alerte' => 'notice',
42
+        'info' => 'info',
43
+        'sous_rub' => 'simple sous-rub'
44
+    ];
45
+    $style_titre_mapping = ['couleur' => 'topper', 'trait-couleur' => 'section'];
46
+    $c = $style_mapping[$style] ?? 'simple';
47
+    $class = $c . ($class ? " $class" : '');
48
+    if (!$padding) {
49
+        $class .= ($class ? ' ' : '') . 'no-padding';
50
+    }
51
+
52
+    //($id?"id='$id' ":"")
53
+    if (strlen($icone) > 1) {
54
+        if ($icone_renommer = charger_fonction('icone_renommer', 'inc', true)) {
55
+            [$fond, $fonction] = $icone_renommer($icone, $fonction);
56
+        }
57
+        $size = 24;
58
+        if (preg_match('/-([0-9]{1,3})[.](gif|png)$/i', $fond, $match)) {
59
+            $size = $match[1];
60
+        }
61
+        if ($fonction) {
62
+            // 2 images pour composer l'icone : le fond (article) en background,
63
+            // la fonction (new) en image
64
+            $icone = http_img_pack($fonction, '', "class='cadre-icone' width='$size' height='$size'\n" .
65
+                http_style_background($fond, 'no-repeat center center', $size));
66
+        } else {
67
+            $icone = http_img_pack($fond, '', "class='cadre-icone' width='$size' height='$size'");
68
+        }
69
+        $titre = $icone . $titre;
70
+    }
71
+
72
+    return boite_ouvrir($titre, $class, $style_titre_mapping[$style] ?? '', $id);
73 73
 }
74 74
 
75 75
 function fin_cadre() {
76
- return boite_fermer();
76
+    return boite_fermer();
77 77
 }
78 78
 
79 79
 
80 80
 function debut_cadre_relief(
81
-	$icone = '',
82
-	$dummy = '',
83
-	$fonction = '',
84
-	$titre = '',
85
-	$id = '',
86
-	$class = ''
81
+    $icone = '',
82
+    $dummy = '',
83
+    $fonction = '',
84
+    $titre = '',
85
+    $id = '',
86
+    $class = ''
87 87
 ) {
88
-	return debut_cadre('r', $icone, $fonction, $titre, $id, $class);
88
+    return debut_cadre('r', $icone, $fonction, $titre, $id, $class);
89 89
 }
90 90
 
91 91
 function fin_cadre_relief() {
92
- return fin_cadre();
92
+    return fin_cadre();
93 93
 }
94 94
 
95 95
 function debut_cadre_enfonce(
96
-	$icone = '',
97
-	$dummy = '',
98
-	$fonction = '',
99
-	$titre = '',
100
-	$id = '',
101
-	$class = ''
96
+    $icone = '',
97
+    $dummy = '',
98
+    $fonction = '',
99
+    $titre = '',
100
+    $id = '',
101
+    $class = ''
102 102
 ) {
103
-	return debut_cadre('e', $icone, $fonction, $titre, $id, $class);
103
+    return debut_cadre('e', $icone, $fonction, $titre, $id, $class);
104 104
 }
105 105
 
106 106
 function fin_cadre_enfonce() {
107
- return fin_cadre();
107
+    return fin_cadre();
108 108
 }
109 109
 
110 110
 function debut_cadre_sous_rub(
111
-	$icone = '',
112
-	$dummy = '',
113
-	$fonction = '',
114
-	$titre = '',
115
-	$id = '',
116
-	$class = ''
111
+    $icone = '',
112
+    $dummy = '',
113
+    $fonction = '',
114
+    $titre = '',
115
+    $id = '',
116
+    $class = ''
117 117
 ) {
118
-	return debut_cadre('sous_rub', $icone, $fonction, $titre, $id, $class);
118
+    return debut_cadre('sous_rub', $icone, $fonction, $titre, $id, $class);
119 119
 }
120 120
 
121 121
 function fin_cadre_sous_rub() {
122
- return fin_cadre();
122
+    return fin_cadre();
123 123
 }
124 124
 
125 125
 function debut_cadre_couleur(
126
-	$icone = '',
127
-	$dummy = '',
128
-	$fonction = '',
129
-	$titre = '',
130
-	$id = '',
131
-	$class = ''
126
+    $icone = '',
127
+    $dummy = '',
128
+    $fonction = '',
129
+    $titre = '',
130
+    $id = '',
131
+    $class = ''
132 132
 ) {
133
-	return debut_cadre('couleur', $icone, $fonction, $titre, $id, $class);
133
+    return debut_cadre('couleur', $icone, $fonction, $titre, $id, $class);
134 134
 }
135 135
 
136 136
 function fin_cadre_couleur() {
137
- return fin_cadre();
137
+    return fin_cadre();
138 138
 }
139 139
 
140 140
 function debut_cadre_trait_couleur(
141
-	$icone = '',
142
-	$dummy = '',
143
-	$fonction = '',
144
-	$titre = '',
145
-	$id = '',
146
-	$class = ''
141
+    $icone = '',
142
+    $dummy = '',
143
+    $fonction = '',
144
+    $titre = '',
145
+    $id = '',
146
+    $class = ''
147 147
 ) {
148
-	return debut_cadre('trait-couleur', $icone, $fonction, $titre, $id, $class);
148
+    return debut_cadre('trait-couleur', $icone, $fonction, $titre, $id, $class);
149 149
 }
150 150
 
151 151
 function fin_cadre_trait_couleur() {
152
- return fin_cadre();
152
+    return fin_cadre();
153 153
 }
154 154
 
155 155
 function debut_boite_alerte() {
156
- return debut_cadre('alerte', '', '', '', '', '');
156
+    return debut_cadre('alerte', '', '', '', '', '');
157 157
 }
158 158
 
159 159
 function fin_boite_alerte() {
160
- return fin_cadre();
160
+    return fin_cadre();
161 161
 }
162 162
 
163 163
 function debut_boite_info() {
164
- return debut_cadre('info', '', '', '', '', '');
164
+    return debut_cadre('info', '', '', '', '', '');
165 165
 }
166 166
 
167 167
 function fin_boite_info() {
168
- return fin_cadre();
168
+    return fin_cadre();
169 169
 }
170 170
 
171 171
 /**
@@ -176,17 +176,17 @@  discard block
 block discarded – undo
176 176
  * @return string Code PHP.
177 177
  **/
178 178
 function gros_titre(
179
-	$titre,
180
-	$ze_logo = ''
179
+    $titre,
180
+    $ze_logo = ''
181 181
 ) {
182
-	return "<h1 class = 'grostitre'>" . $ze_logo . ' ' . typo($titre) . "</h1>\n";
182
+    return "<h1 class = 'grostitre'>" . $ze_logo . ' ' . typo($titre) . "</h1>\n";
183 183
 }
184 184
 
185 185
 // La boite des raccourcis
186 186
 // Se place a droite si l'ecran est en mode panoramique.
187 187
 function bloc_des_raccourcis($bloc) {
188
-	return creer_colonne_droite()
189
-	. boite_ouvrir(_T('titre_cadre_raccourcis'), 'raccourcis') . $bloc . boite_fermer();
188
+    return creer_colonne_droite()
189
+    . boite_ouvrir(_T('titre_cadre_raccourcis'), 'raccourcis') . $bloc . boite_fermer();
190 190
 }
191 191
 
192 192
 //
@@ -196,18 +196,18 @@  discard block
 block discarded – undo
196 196
 // Fonctions onglets
197 197
 // @param string $sous_classe	prend la valeur second pour definir les onglet de deuxieme niveau
198 198
 function debut_onglet($classe = 'barre_onglet') {
199
- return "<div class = '$classe clearfix'><ul>\n";
199
+    return "<div class = '$classe clearfix'><ul>\n";
200 200
 }
201 201
 
202 202
 function fin_onglet() {
203
- return "</ul></div>\n";
203
+    return "</ul></div>\n";
204 204
 }
205 205
 
206 206
 function onglet($texte, $lien, $onglet_ref, $onglet, $icone = '') {
207
-	return '<li>'
208
-	. ($icone ? http_img_pack($icone, '', " class='cadre-icone'") : '')
209
-	. lien_ou_expose($lien, $texte, $onglet == $onglet_ref)
210
-	. '</li>';
207
+    return '<li>'
208
+    . ($icone ? http_img_pack($icone, '', " class='cadre-icone'") : '')
209
+    . lien_ou_expose($lien, $texte, $onglet == $onglet_ref)
210
+    . '</li>';
211 211
 }
212 212
 
213 213
 /**
@@ -239,14 +239,14 @@  discard block
 block discarded – undo
239 239
  *     Code HTML du lien
240 240
  **/
241 241
 function icone_verticale($texte, $lien, $fond, $fonction = '', $align = '', $javascript = '') {
242
-	// cas d'ajax_action_auteur: faut defaire le boulot
243
-	// (il faudrait fusionner avec le cas $javascript)
244
-	if (preg_match(",^<a\shref='([^']*)'([^>]*)>(.*)</a>$,i", $lien, $r)) {
245
-		[$x, $lien, $atts, $texte] = $r;
246
-		$javascript .= $atts;
247
-	}
248
-
249
-	return icone_base($lien, $texte, $fond, $fonction, "verticale $align", $javascript);
242
+    // cas d'ajax_action_auteur: faut defaire le boulot
243
+    // (il faudrait fusionner avec le cas $javascript)
244
+    if (preg_match(",^<a\shref='([^']*)'([^>]*)>(.*)</a>$,i", $lien, $r)) {
245
+        [$x, $lien, $atts, $texte] = $r;
246
+        $javascript .= $atts;
247
+    }
248
+
249
+    return icone_base($lien, $texte, $fond, $fonction, "verticale $align", $javascript);
250 250
 }
251 251
 
252 252
 /**
@@ -271,15 +271,15 @@  discard block
 block discarded – undo
271 271
  *     Code HTML du lien
272 272
  **/
273 273
 function icone_horizontale($texte, $lien, $fond, $fonction = '', $dummy = '', $javascript = '') {
274
-	$retour = '';
275
-	// cas d'ajax_action_auteur: faut defaire le boulot
276
-	// (il faudrait fusionner avec le cas $javascript)
277
-	if (preg_match(",^<a\shref='([^']*)'([^>]*)>(.*)</a>$,i", $lien, $r)) {
278
-		[$x, $lien, $atts, $texte] = $r;
279
-		$javascript .= $atts;
280
-	}
274
+    $retour = '';
275
+    // cas d'ajax_action_auteur: faut defaire le boulot
276
+    // (il faudrait fusionner avec le cas $javascript)
277
+    if (preg_match(",^<a\shref='([^']*)'([^>]*)>(.*)</a>$,i", $lien, $r)) {
278
+        [$x, $lien, $atts, $texte] = $r;
279
+        $javascript .= $atts;
280
+    }
281 281
 
282
-	$retour = icone_base($lien, $texte, $fond, $fonction, 'horizontale', $javascript);
282
+    $retour = icone_base($lien, $texte, $fond, $fonction, 'horizontale', $javascript);
283 283
 
284
-	return $retour;
284
+    return $retour;
285 285
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -44,9 +44,9 @@  discard block
 block discarded – undo
44 44
 	];
45 45
 	$style_titre_mapping = ['couleur' => 'topper', 'trait-couleur' => 'section'];
46 46
 	$c = $style_mapping[$style] ?? 'simple';
47
-	$class = $c . ($class ? " $class" : '');
47
+	$class = $c.($class ? " $class" : '');
48 48
 	if (!$padding) {
49
-		$class .= ($class ? ' ' : '') . 'no-padding';
49
+		$class .= ($class ? ' ' : '').'no-padding';
50 50
 	}
51 51
 
52 52
 	//($id?"id='$id' ":"")
@@ -61,12 +61,12 @@  discard block
 block discarded – undo
61 61
 		if ($fonction) {
62 62
 			// 2 images pour composer l'icone : le fond (article) en background,
63 63
 			// la fonction (new) en image
64
-			$icone = http_img_pack($fonction, '', "class='cadre-icone' width='$size' height='$size'\n" .
64
+			$icone = http_img_pack($fonction, '', "class='cadre-icone' width='$size' height='$size'\n".
65 65
 				http_style_background($fond, 'no-repeat center center', $size));
66 66
 		} else {
67 67
 			$icone = http_img_pack($fond, '', "class='cadre-icone' width='$size' height='$size'");
68 68
 		}
69
-		$titre = $icone . $titre;
69
+		$titre = $icone.$titre;
70 70
 	}
71 71
 
72 72
 	return boite_ouvrir($titre, $class, $style_titre_mapping[$style] ?? '', $id);
@@ -179,14 +179,14 @@  discard block
 block discarded – undo
179 179
 	$titre,
180 180
 	$ze_logo = ''
181 181
 ) {
182
-	return "<h1 class = 'grostitre'>" . $ze_logo . ' ' . typo($titre) . "</h1>\n";
182
+	return "<h1 class = 'grostitre'>".$ze_logo.' '.typo($titre)."</h1>\n";
183 183
 }
184 184
 
185 185
 // La boite des raccourcis
186 186
 // Se place a droite si l'ecran est en mode panoramique.
187 187
 function bloc_des_raccourcis($bloc) {
188 188
 	return creer_colonne_droite()
189
-	. boite_ouvrir(_T('titre_cadre_raccourcis'), 'raccourcis') . $bloc . boite_fermer();
189
+	. boite_ouvrir(_T('titre_cadre_raccourcis'), 'raccourcis').$bloc.boite_fermer();
190 190
 }
191 191
 
192 192
 //
Please login to merge, or discard this patch.