Completed
Push — master ( d64163...2218f7 )
by cam
04:20
created
ecrire/inc/distant.php 4 patches
Doc Comments   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
  *   permet de specifier le nom du fichier local (stockage d'un cache par exemple, et non document IMG)
65 65
  * @param int $taille_max
66 66
  *   taille maxi de la copie local, par defaut _COPIE_LOCALE_MAX_SIZE
67
- * @return bool|string
67
+ * @return string|false
68 68
  */
69 69
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null) {
70 70
 
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
  * La fonction PHP idn_to_ascii depend d'un package php5-intl et est rarement disponible
247 247
  *
248 248
  * @param string $url_idn
249
- * @return array|string
249
+ * @return string|boolean
250 250
  */
251 251
 function url_to_ascii($url_idn) {
252 252
 
@@ -642,13 +642,13 @@  discard block
 block discarded – undo
642 642
  *
643 643
  * @param string $url
644 644
  *     URL de la page à récupérer
645
- * @param bool|null|string $trans
645
+ * @param boolean $trans
646 646
  *     - chaîne longue : c'est un nom de fichier (nom pour sa copie locale)
647 647
  *     - true : demande d'encodage/charset
648 648
  *     - null : ne retourner que les headers
649 649
  * @param string $get
650 650
  *     Type de requête HTTP à faire (HEAD, GET ou POST)
651
- * @param int|bool $taille_max
651
+ * @param integer $taille_max
652 652
  *     Arrêter le contenu au-delà (0 = seulement les entetes ==> requête HEAD).
653 653
  *     Par defaut taille_max = 1Mo.
654 654
  * @param string|array $datas
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
  *
775 775
  * @param resource $handle
776 776
  * @param int|bool $if_modified_since
777
- * @return bool|array
777
+ * @return string
778 778
  *   int status
779 779
  *   string headers
780 780
  *   int last_modified
@@ -1251,9 +1251,9 @@  discard block
 block discarded – undo
1251 1251
  *   donnees postees
1252 1252
  * @param string $vers
1253 1253
  *   version HTTP
1254
- * @param int|string $date
1254
+ * @param string $date
1255 1255
  *   timestamp pour entente If-Modified-Since
1256
- * @return bool|resource
1256
+ * @return string
1257 1257
  *   false|int si echec
1258 1258
  *   resource socket vers l'url demandee
1259 1259
  */
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1256,8 +1256,9 @@
 block discarded – undo
1256 1256
 	$http_noproxy = " $http_noproxy ";
1257 1257
 	$domain = $host;
1258 1258
 	// si le domaine exact www.example.org est dans les exceptions
1259
-	if (strpos($http_noproxy, " $domain ") !== false)
1260
-		return '';
1259
+	if (strpos($http_noproxy, " $domain ") !== false) {
1260
+			return '';
1261
+	}
1261 1262
 
1262 1263
 	while (strpos($domain, '.') !== false) {
1263 1264
 		$domain = explode('.', $domain);
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32 32
 	define('_INC_DISTANT_MAX_SIZE', 2097152);
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38
-define('_REGEXP_COPIE_LOCALE', ',' 	.
38
+define('_REGEXP_COPIE_LOCALE', ','.
39 39
 	preg_replace(
40 40
 		'@^https?:@',
41 41
 		'https?:',
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 
71 71
 	// si c'est la protection de soi-meme, retourner le path
72 72
 	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
73
+		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)).urldecode($match[1]);
74 74
 
75 75
 		return @file_exists($source) ? $source : false;
76 76
 	}
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 		return false;
91 91
 	}
92 92
 
93
-	$localrac = _DIR_RACINE . $local;
93
+	$localrac = _DIR_RACINE.$local;
94 94
 	$t = ($mode == 'force') ? false : @file_exists($localrac);
95 95
 
96 96
 	// test d'existence du fichier
@@ -115,13 +115,13 @@  discard block
 block discarded – undo
115 115
 			array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116 116
 		);
117 117
 		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
118
+			spip_log("copie_locale : Echec recuperation $source sur $localrac status : ".$res['status'], 'distant'._LOG_INFO_IMPORTANTE);
119 119
 		}
120 120
 		if (!$res['length']) {
121 121
 			// si $t c'est sans doute juste un not-modified-since
122 122
 			return $t ? $local : false;
123 123
 		}
124
-		spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
124
+		spip_log("copie_locale : recuperation $source sur $localrac taille ".$res['length'].' OK', 'distant');
125 125
 
126 126
 		// pour une eventuelle indexation
127 127
 		pipeline(
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
  *   url ou false en cas d'echec
154 154
  */
155 155
 function valider_url_distante($url, $known_hosts = array()) {
156
-	if (!function_exists('protocole_verifier')){
156
+	if (!function_exists('protocole_verifier')) {
157 157
 		include_spip('inc/filtres_mini');
158 158
 	}
159 159
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 	}
163 163
 	
164 164
 	$parsed_url = parse_url($url);
165
-	if (!$parsed_url or empty($parsed_url['host']) ) {
165
+	if (!$parsed_url or empty($parsed_url['host'])) {
166 166
 		return false;
167 167
 	}
168 168
 
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
 			}
204 204
 		}
205 205
 		if ($ip) {
206
-			$parts = array_map('intval', explode( '.', $ip ));
206
+			$parts = array_map('intval', explode('.', $ip));
207 207
 			if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
-			  or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
-			  or ( 192 === $parts[0] && 168 === $parts[1] )
208
+			  or (172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1])
209
+			  or (192 === $parts[0] && 168 === $parts[1])
210 210
 			) {
211 211
 				return false;
212 212
 			}
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	}
219 219
 
220 220
 	$port = $parsed_url['port'];
221
-	if ($port === 80  or $port === 443  or $port === 8080) {
221
+	if ($port === 80 or $port === 443 or $port === 8080) {
222 222
 		return $url;
223 223
 	}
224 224
 
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 				}
286 286
 			}
287 287
 			if ($taille > 500) {
288
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
288
+				$boundary = substr(md5(rand().'spip'), 0, 8);
289 289
 			}
290 290
 		}
291 291
 
@@ -313,16 +313,16 @@  discard block
 block discarded – undo
313 313
 			}
314 314
 		} else {
315 315
 			// fabrique une chaine HTTP simple pour un POST
316
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
316
+			$entete = 'Content-Type: application/x-www-form-urlencoded'."\r\n";
317 317
 			$chaine = array();
318 318
 			if (is_array($donnees)) {
319 319
 				foreach ($donnees as $cle => $valeur) {
320 320
 					if (is_array($valeur)) {
321 321
 						foreach ($valeur as $val2) {
322
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
322
+							$chaine[] = rawurlencode($cle).'[]='.rawurlencode($val2);
323 323
 						}
324 324
 					} else {
325
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
325
+						$chaine[] = rawurlencode($cle).'='.rawurlencode($valeur);
326 326
 					}
327 327
 				}
328 328
 				$chaine = implode('&', $chaine);
@@ -423,9 +423,9 @@  discard block
 block discarded – undo
423 423
 	if (!empty($options['datas'])) {
424 424
 		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
425 425
 		if (stripos($head, 'Content-Length:') === false) {
426
-			$head .= 'Content-Length: ' . strlen($postdata);
426
+			$head .= 'Content-Length: '.strlen($postdata);
427 427
 		}
428
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
428
+		$options['datas'] = $head."\r\n\r\n".$postdata;
429 429
 		if (strlen($postdata)) {
430 430
 			$options['methode'] = 'POST';
431 431
 		}
@@ -434,9 +434,9 @@  discard block
 block discarded – undo
434 434
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
435 435
 	$url = preg_replace(',^feed://,i', 'http://', $url);
436 436
 	if (!tester_url_absolue($url)) {
437
-		$url = 'http://' . $url;
437
+		$url = 'http://'.$url;
438 438
 	} elseif (strncmp($url, '//', 2) == 0) {
439
-		$url = 'http:' . $url;
439
+		$url = 'http:'.$url;
440 440
 	}
441 441
 
442 442
 	$url = url_to_ascii($url);
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 		$options['if_modified_since']
466 466
 	);
467 467
 	if (!$handle) {
468
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
468
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
469 469
 
470 470
 		return false;
471 471
 	}
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 					'status' => 200,
495 495
 				);
496 496
 			} else {
497
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
497
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
498 498
 				return false;
499 499
 			}
500 500
 		} elseif ($res['location'] and $options['follow_location']) {
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 
507 507
 			return recuperer_url($url, $options);
508 508
 		} elseif ($res['status'] !== 200) {
509
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
509
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
510 510
 		}
511 511
 		$result['status'] = $res['status'];
512 512
 		if (isset($res['headers'])) {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 	$gz = false;
533 533
 	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
534
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
534
+		$gz = (_DIR_TMP.md5(uniqid(mt_rand())).'.tmp.gz');
535 535
 	}
536 536
 
537 537
 	// si on a pas deja recuperer le contenu par une methode detournee
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 	$sig['url'] = $url;
618 618
 
619 619
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
620
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
620
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
621 621
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
622 622
 	$cache = "$sub$cache";
623 623
 
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		return false;
727 727
 	}
728 728
 	if ($get_headers) {
729
-		return $res['headers'] . "\n" . $res['page'];
729
+		return $res['headers']."\n".$res['page'];
730 730
 	}
731 731
 
732 732
 	return $res['page'];
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 	$fp = false;
831 831
 	if ($fichier) {
832 832
 		include_spip('inc/acces');
833
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
833
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
834 834
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
835 835
 		if (!$fp and file_exists($fichier)) {
836 836
 			return filesize($fichier);
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 	}
890 890
 	$result['status'] = intval($r[1]);
891 891
 	while ($s = trim(fgets($handle, 16384))) {
892
-		$result['headers'][] = $s . "\n";
892
+		$result['headers'][] = $s."\n";
893 893
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
894 894
 		list(, $d, $v) = $r;
895 895
 		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
@@ -972,13 +972,13 @@  discard block
 block discarded – undo
972 972
 
973 973
 	// on se place tout le temps comme si on etait a la racine
974 974
 	if (_DIR_RACINE) {
975
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
975
+		$d = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $d);
976 976
 	}
977 977
 
978 978
 	$m = md5($source);
979 979
 
980 980
 	return $d
981
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
981
+	. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
982 982
 	. substr($m, 0, 4)
983 983
 	. ".$extension";
984 984
 }
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 	// Si c'est deja local pas de souci
1002 1002
 	if (!tester_url_absolue($source)) {
1003 1003
 		if (_DIR_RACINE) {
1004
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1004
+			$source = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $source);
1005 1005
 		}
1006 1006
 
1007 1007
 		return $source;
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 	if ($ext
1019 1019
 		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1020 1020
 		and $f = nom_fichier_copie_locale($source, $ext)
1021
-		and file_exists(_DIR_RACINE . $f)
1021
+		and file_exists(_DIR_RACINE.$f)
1022 1022
 	) {
1023 1023
 		return $f;
1024 1024
 	}
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
 
1027 1027
 	// Si c'est deja dans la table des documents,
1028 1028
 	// ramener le nom de sa copie potentielle
1029
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1029
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
1030 1030
 
1031 1031
 	if ($ext) {
1032 1032
 		return nom_fichier_copie_locale($source, $ext);
@@ -1037,9 +1037,9 @@  discard block
 block discarded – undo
1037 1037
 
1038 1038
 	$ext = $path_parts ? $path_parts['extension'] : '';
1039 1039
 
1040
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1040
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
1041 1041
 		$f = nom_fichier_copie_locale($source, $ext);
1042
-		if (file_exists(_DIR_RACINE . $f)) {
1042
+		if (file_exists(_DIR_RACINE.$f)) {
1043 1043
 			return $f;
1044 1044
 		}
1045 1045
 	}
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
 	// Ping  pour voir si son extension est connue et autorisee
1048 1048
 	// avec mise en cache du resultat du ping
1049 1049
 
1050
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1050
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
1051 1051
 	if (!@file_exists($cache)
1052 1052
 		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1053 1053
 		or _request('var_mode') == 'recalcul'
@@ -1056,10 +1056,10 @@  discard block
 block discarded – undo
1056 1056
 		ecrire_fichier($cache, serialize($path_parts));
1057 1057
 	}
1058 1058
 	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1059
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1059
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
1060 1060
 		return nom_fichier_copie_locale($source, $ext);
1061 1061
 	}
1062
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1062
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
1063 1063
 }
1064 1064
 
1065 1065
 
@@ -1124,19 +1124,19 @@  discard block
 block discarded – undo
1124 1124
 			if (!$t
1125 1125
 				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1126 1126
 			) {
1127
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1127
+				$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1128 1128
 			}
1129 1129
 			if (!$t
1130 1130
 				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1131 1131
 				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1132 1132
 			) {
1133
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1133
+				$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1134 1134
 			}
1135 1135
 		}
1136 1136
 
1137 1137
 		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1138 1138
 		if (!$t) {
1139
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1139
+			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1140 1140
 		}
1141 1141
 
1142 1142
 		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1146,11 +1146,11 @@  discard block
 block discarded – undo
1146 1146
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1147 1147
 		) {
1148 1148
 			# eviter xxx.3 => 3gp (> SPIP 3)
1149
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1149
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote($rext[1], '', 'text'));
1150 1150
 		}
1151 1151
 
1152 1152
 		if ($t) {
1153
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1153
+			spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1154 1154
 			$a['extension'] = $t['extension'];
1155 1155
 		} else {
1156 1156
 			# par defaut on retombe sur '.bin' si c'est autorise
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
 		} else {
1193 1193
 			if ($a['body']) {
1194 1194
 				$a['extension'] = $extension;
1195
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1195
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1196 1196
 				ecrire_fichier($a['fichier'], $a['body']);
1197 1197
 				$size_image = @spip_getimagesize($a['fichier']);
1198 1198
 				$a['largeur'] = intval($size_image[0]);
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
 		}
1318 1318
 	} else {
1319 1319
 		$scheme = $t['scheme'];
1320
-		$noproxy = $scheme . '://';
1320
+		$noproxy = $scheme.'://';
1321 1321
 	}
1322 1322
 	if (isset($t['user'])) {
1323 1323
 		$user = array($t['user'], $t['pass']);
@@ -1331,7 +1331,7 @@  discard block
 block discarded – undo
1331 1331
 	}
1332 1332
 
1333 1333
 	if (!empty($t['query'])) {
1334
-		$path .= '?' . $t['query'];
1334
+		$path .= '?'.$t['query'];
1335 1335
 	}
1336 1336
 
1337 1337
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1404,20 +1404,20 @@  discard block
 block discarded – undo
1404 1404
 	$proxy_user = '';
1405 1405
 	$http_proxy = need_proxy($host);
1406 1406
 	if ($user) {
1407
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1407
+		$user = urlencode($user[0]).':'.urlencode($user[1]);
1408 1408
 	}
1409 1409
 
1410 1410
 	$connect = '';
1411 1411
 	if ($http_proxy) {
1412
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1413
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1414
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1412
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, array('tls', 'ssl'))) {
1413
+			$path_host = (!$user ? '' : "$user@").$host.(($port != 80) ? ":$port" : '');
1414
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1415 1415
 				. "Host: $path_host\r\n"
1416 1416
 				. "Proxy-Connection: Keep-Alive\r\n";
1417 1417
 		} else {
1418
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1418
+			$path = (in_array($scheme, array('tls', 'ssl')) ? 'https://' : "$scheme://")
1419 1419
 				. (!$user ? '' : "$user@")
1420
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1420
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1421 1421
 		}
1422 1422
 		$t2 = @parse_url($http_proxy);
1423 1423
 		$first_host = $t2['host'];
@@ -1425,10 +1425,10 @@  discard block
 block discarded – undo
1425 1425
 			$port = 80;
1426 1426
 		}
1427 1427
 		if ($t2['user']) {
1428
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1428
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1429 1429
 		}
1430 1430
 	} else {
1431
-		$first_host = $noproxy . $host;
1431
+		$first_host = $noproxy.$host;
1432 1432
 	}
1433 1433
 
1434 1434
 	if ($connect) {
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
 		);
1454 1454
 		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1455 1455
 		if (!$f) {
1456
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1456
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1457 1457
 			return $errno;
1458 1458
 		}
1459 1459
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
 			or !count($res = explode(' ', $res))
1466 1466
 			or $res[1] !== '200'
1467 1467
 		) {
1468
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1468
+			spip_log("Echec CONNECT sur $first_host:$port", 'connect'._LOG_INFO_IMPORTANTE);
1469 1469
 			fclose($f);
1470 1470
 
1471 1471
 			return false;
@@ -1482,7 +1482,7 @@  discard block
 block discarded – undo
1482 1482
 		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1483 1483
 		spip_log("Recuperer $path sur $first_host:$port par $f");
1484 1484
 		if (!$f) {
1485
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1485
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1486 1486
 
1487 1487
 			return $errno;
1488 1488
 		}
@@ -1492,16 +1492,16 @@  discard block
 block discarded – undo
1492 1492
 	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1493 1493
 
1494 1494
 	$host_port = $host;
1495
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1495
+	if ($port != (in_array($scheme, array('tls', 'ssl')) ? 443 : 80)) {
1496 1496
 		$host_port .= ":$port";
1497 1497
 	}
1498 1498
 	$req = "$method $path $vers\r\n"
1499 1499
 		. "Host: $host_port\r\n"
1500
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1501
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1500
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1501
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1502 1502
 		. (!$site ? '' : "Referer: $site/$referer\r\n")
1503
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1504
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1503
+		. (!$date ? '' : 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n"))
1504
+		. (!$user ? '' : ('Authorization: Basic '.base64_encode($user)."\r\n"))
1505 1505
 		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1506 1506
 		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1507 1507
 
Please login to merge, or discard this patch.
Indentation   +1074 added lines, -1074 removed lines patch added patch discarded remove patch
@@ -16,32 +16,32 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Distant
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
23
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
23
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24 24
 }
25 25
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
26
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
26
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32
-	define('_INC_DISTANT_MAX_SIZE', 2097152);
32
+    define('_INC_DISTANT_MAX_SIZE', 2097152);
33 33
 }
34 34
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
35
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
35
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38 38
 define('_REGEXP_COPIE_LOCALE', ',' 	.
39
-	preg_replace(
40
-		'@^https?:@',
41
-		'https?:',
42
-		(isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
-	)
44
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
39
+    preg_replace(
40
+        '@^https?:@',
41
+        'https?:',
42
+        (isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
+    )
44
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
45 45
 
46 46
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
47 47
 
@@ -68,77 +68,77 @@  discard block
 block discarded – undo
68 68
  */
69 69
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null) {
70 70
 
71
-	// si c'est la protection de soi-meme, retourner le path
72
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
-
75
-		return @file_exists($source) ? $source : false;
76
-	}
77
-
78
-	if (is_null($local)) {
79
-		$local = fichier_copie_locale($source);
80
-	} else {
81
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
-			$local = substr($local, strlen(_DIR_RACINE));
83
-		}
84
-	}
85
-
86
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
-	// par exemple un fichier qui ne figure pas dans nos documents ;
88
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
-	if (!$local) {
90
-		return false;
91
-	}
92
-
93
-	$localrac = _DIR_RACINE . $local;
94
-	$t = ($mode == 'force') ? false : @file_exists($localrac);
95
-
96
-	// test d'existence du fichier
97
-	if ($mode == 'test') {
98
-		return $t ? $local : '';
99
-	}
100
-
101
-	// sinon voir si on doit/peut le telecharger
102
-	if ($local == $source or !tester_url_absolue($source)) {
103
-		return $local;
104
-	}
105
-
106
-	if ($mode == 'modif' or !$t) {
107
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
-		// et des eventuelles recuperations concurantes
109
-		include_spip('inc/acces');
110
-		if (!$taille_max) {
111
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
112
-		}
113
-		$res = recuperer_url(
114
-			$source,
115
-			array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
-		);
117
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
-		}
120
-		if (!$res['length']) {
121
-			// si $t c'est sans doute juste un not-modified-since
122
-			return $t ? $local : false;
123
-		}
124
-		spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
-
126
-		// pour une eventuelle indexation
127
-		pipeline(
128
-			'post_edition',
129
-			array(
130
-				'args' => array(
131
-					'operation' => 'copie_locale',
132
-					'source' => $source,
133
-					'fichier' => $local,
134
-					'http_res' => $res['length'],
135
-				),
136
-				'data' => null
137
-			)
138
-		);
139
-	}
140
-
141
-	return $local;
71
+    // si c'est la protection de soi-meme, retourner le path
72
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
+
75
+        return @file_exists($source) ? $source : false;
76
+    }
77
+
78
+    if (is_null($local)) {
79
+        $local = fichier_copie_locale($source);
80
+    } else {
81
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
+            $local = substr($local, strlen(_DIR_RACINE));
83
+        }
84
+    }
85
+
86
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
+    // par exemple un fichier qui ne figure pas dans nos documents ;
88
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
+    if (!$local) {
90
+        return false;
91
+    }
92
+
93
+    $localrac = _DIR_RACINE . $local;
94
+    $t = ($mode == 'force') ? false : @file_exists($localrac);
95
+
96
+    // test d'existence du fichier
97
+    if ($mode == 'test') {
98
+        return $t ? $local : '';
99
+    }
100
+
101
+    // sinon voir si on doit/peut le telecharger
102
+    if ($local == $source or !tester_url_absolue($source)) {
103
+        return $local;
104
+    }
105
+
106
+    if ($mode == 'modif' or !$t) {
107
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
+        // et des eventuelles recuperations concurantes
109
+        include_spip('inc/acces');
110
+        if (!$taille_max) {
111
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
112
+        }
113
+        $res = recuperer_url(
114
+            $source,
115
+            array('file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '')
116
+        );
117
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
+            spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . $res['status'], 'distant' . _LOG_INFO_IMPORTANTE);
119
+        }
120
+        if (!$res['length']) {
121
+            // si $t c'est sans doute juste un not-modified-since
122
+            return $t ? $local : false;
123
+        }
124
+        spip_log("copie_locale : recuperation $source sur $localrac taille " . $res['length'] . ' OK', 'distant');
125
+
126
+        // pour une eventuelle indexation
127
+        pipeline(
128
+            'post_edition',
129
+            array(
130
+                'args' => array(
131
+                    'operation' => 'copie_locale',
132
+                    'source' => $source,
133
+                    'fichier' => $local,
134
+                    'http_res' => $res['length'],
135
+                ),
136
+                'data' => null
137
+            )
138
+        );
139
+    }
140
+
141
+    return $local;
142 142
 }
143 143
 
144 144
 /**
@@ -153,88 +153,88 @@  discard block
 block discarded – undo
153 153
  *   url ou false en cas d'echec
154 154
  */
155 155
 function valider_url_distante($url, $known_hosts = array()) {
156
-	if (!function_exists('protocole_verifier')){
157
-		include_spip('inc/filtres_mini');
158
-	}
156
+    if (!function_exists('protocole_verifier')){
157
+        include_spip('inc/filtres_mini');
158
+    }
159 159
 
160
-	if (!protocole_verifier($url, array('http', 'https'))) {
161
-		return false;
162
-	}
160
+    if (!protocole_verifier($url, array('http', 'https'))) {
161
+        return false;
162
+    }
163 163
 	
164
-	$parsed_url = parse_url($url);
165
-	if (!$parsed_url or empty($parsed_url['host']) ) {
166
-		return false;
167
-	}
168
-
169
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
-		return false;
171
-	}
172
-
173
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
-		return false;
175
-	}
176
-
177
-	if (!is_array($known_hosts)) {
178
-		$known_hosts = array($known_hosts);
179
-	}
180
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
-	$known_hosts[] = url_de_base();
182
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
-
184
-	$is_known_host = false;
185
-	foreach ($known_hosts as $known_host) {
186
-		$parse_known = parse_url($known_host);
187
-		if ($parse_known
188
-		  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
-			$is_known_host = true;
190
-			break;
191
-		}
192
-	}
193
-
194
-	if (!$is_known_host) {
195
-		$host = trim($parsed_url['host'], '.');
196
-		if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
-			$ip = $host;
198
-		} else {
199
-			$ip = gethostbyname($host);
200
-			if ($ip === $host) {
201
-				// Error condition for gethostbyname()
202
-				$ip = false;
203
-			}
204
-		}
205
-		if ($ip) {
206
-			$parts = array_map('intval', explode( '.', $ip ));
207
-			if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
-			  or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
-			  or ( 192 === $parts[0] && 168 === $parts[1] )
210
-			) {
211
-				return false;
212
-			}
213
-		}
214
-	}
215
-
216
-	if (empty($parsed_url['port'])) {
217
-		return $url;
218
-	}
219
-
220
-	$port = $parsed_url['port'];
221
-	if ($port === 80  or $port === 443  or $port === 8080) {
222
-		return $url;
223
-	}
224
-
225
-	if ($is_known_host) {
226
-		foreach ($known_hosts as $known_host) {
227
-			$parse_known = parse_url($known_host);
228
-			if ($parse_known
229
-				and !empty($parse_known['port'])
230
-			  and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
-			  and $parse_known['port'] == $port) {
232
-				return $url;
233
-			}
234
-		}
235
-	}
236
-
237
-	return false;
164
+    $parsed_url = parse_url($url);
165
+    if (!$parsed_url or empty($parsed_url['host']) ) {
166
+        return false;
167
+    }
168
+
169
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
170
+        return false;
171
+    }
172
+
173
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
174
+        return false;
175
+    }
176
+
177
+    if (!is_array($known_hosts)) {
178
+        $known_hosts = array($known_hosts);
179
+    }
180
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
181
+    $known_hosts[] = url_de_base();
182
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
183
+
184
+    $is_known_host = false;
185
+    foreach ($known_hosts as $known_host) {
186
+        $parse_known = parse_url($known_host);
187
+        if ($parse_known
188
+          and strtolower($parse_known['host']) === strtolower($parsed_url['host'])) {
189
+            $is_known_host = true;
190
+            break;
191
+        }
192
+    }
193
+
194
+    if (!$is_known_host) {
195
+        $host = trim($parsed_url['host'], '.');
196
+        if (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $host)) {
197
+            $ip = $host;
198
+        } else {
199
+            $ip = gethostbyname($host);
200
+            if ($ip === $host) {
201
+                // Error condition for gethostbyname()
202
+                $ip = false;
203
+            }
204
+        }
205
+        if ($ip) {
206
+            $parts = array_map('intval', explode( '.', $ip ));
207
+            if (127 === $parts[0] or 10 === $parts[0] or 0 === $parts[0]
208
+              or ( 172 === $parts[0] and 16 <= $parts[1] and 31 >= $parts[1] )
209
+              or ( 192 === $parts[0] && 168 === $parts[1] )
210
+            ) {
211
+                return false;
212
+            }
213
+        }
214
+    }
215
+
216
+    if (empty($parsed_url['port'])) {
217
+        return $url;
218
+    }
219
+
220
+    $port = $parsed_url['port'];
221
+    if ($port === 80  or $port === 443  or $port === 8080) {
222
+        return $url;
223
+    }
224
+
225
+    if ($is_known_host) {
226
+        foreach ($known_hosts as $known_host) {
227
+            $parse_known = parse_url($known_host);
228
+            if ($parse_known
229
+                and !empty($parse_known['port'])
230
+              and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
231
+              and $parse_known['port'] == $port) {
232
+                return $url;
233
+            }
234
+        }
235
+    }
236
+
237
+    return false;
238 238
 }
239 239
 
240 240
 /**
@@ -254,86 +254,86 @@  discard block
 block discarded – undo
254 254
  */
255 255
 function prepare_donnees_post($donnees, $boundary = '') {
256 256
 
257
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
258
-	// pour un appel soap par exemple
259
-	// l'entete est separe des donnees par un double retour a la ligne
260
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
261
-	if (is_string($donnees) && strlen($donnees)) {
262
-		$entete = '';
263
-		// on repasse tous les \r\n et \r en simples \n
264
-		$donnees = str_replace("\r\n", "\n", $donnees);
265
-		$donnees = str_replace("\r", "\n", $donnees);
266
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
267
-		$p = strpos($donnees, "\n\n");
268
-		if ($p !== false) {
269
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
270
-			$donnees = substr($donnees, $p + 2);
271
-		}
272
-		$chaine = str_replace("\n", "\r\n", $donnees);
273
-	} else {
274
-		/* boundary automatique */
275
-		// Si on a plus de 500 octects de donnees, on "boundarise"
276
-		if ($boundary === '') {
277
-			$taille = 0;
278
-			foreach ($donnees as $cle => $valeur) {
279
-				if (is_array($valeur)) {
280
-					foreach ($valeur as $val2) {
281
-						$taille += strlen($val2);
282
-					}
283
-				} else {
284
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
285
-					$taille += strlen($valeur);
286
-				}
287
-			}
288
-			if ($taille > 500) {
289
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
290
-			}
291
-		}
292
-
293
-		if (is_string($boundary) and strlen($boundary)) {
294
-			// fabrique une chaine HTTP pour un POST avec boundary
295
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
296
-			$chaine = '';
297
-			if (is_array($donnees)) {
298
-				foreach ($donnees as $cle => $valeur) {
299
-					if (is_array($valeur)) {
300
-						foreach ($valeur as $val2) {
301
-							$chaine .= "\r\n--$boundary\r\n";
302
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
303
-							$chaine .= "\r\n";
304
-							$chaine .= $val2;
305
-						}
306
-					} else {
307
-						$chaine .= "\r\n--$boundary\r\n";
308
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
309
-						$chaine .= "\r\n";
310
-						$chaine .= $valeur;
311
-					}
312
-				}
313
-				$chaine .= "\r\n--$boundary\r\n";
314
-			}
315
-		} else {
316
-			// fabrique une chaine HTTP simple pour un POST
317
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
318
-			$chaine = array();
319
-			if (is_array($donnees)) {
320
-				foreach ($donnees as $cle => $valeur) {
321
-					if (is_array($valeur)) {
322
-						foreach ($valeur as $val2) {
323
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
324
-						}
325
-					} else {
326
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
327
-					}
328
-				}
329
-				$chaine = implode('&', $chaine);
330
-			} else {
331
-				$chaine = $donnees;
332
-			}
333
-		}
334
-	}
335
-
336
-	return array($entete, $chaine);
257
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
258
+    // pour un appel soap par exemple
259
+    // l'entete est separe des donnees par un double retour a la ligne
260
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
261
+    if (is_string($donnees) && strlen($donnees)) {
262
+        $entete = '';
263
+        // on repasse tous les \r\n et \r en simples \n
264
+        $donnees = str_replace("\r\n", "\n", $donnees);
265
+        $donnees = str_replace("\r", "\n", $donnees);
266
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
267
+        $p = strpos($donnees, "\n\n");
268
+        if ($p !== false) {
269
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
270
+            $donnees = substr($donnees, $p + 2);
271
+        }
272
+        $chaine = str_replace("\n", "\r\n", $donnees);
273
+    } else {
274
+        /* boundary automatique */
275
+        // Si on a plus de 500 octects de donnees, on "boundarise"
276
+        if ($boundary === '') {
277
+            $taille = 0;
278
+            foreach ($donnees as $cle => $valeur) {
279
+                if (is_array($valeur)) {
280
+                    foreach ($valeur as $val2) {
281
+                        $taille += strlen($val2);
282
+                    }
283
+                } else {
284
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
285
+                    $taille += strlen($valeur);
286
+                }
287
+            }
288
+            if ($taille > 500) {
289
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
290
+            }
291
+        }
292
+
293
+        if (is_string($boundary) and strlen($boundary)) {
294
+            // fabrique une chaine HTTP pour un POST avec boundary
295
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
296
+            $chaine = '';
297
+            if (is_array($donnees)) {
298
+                foreach ($donnees as $cle => $valeur) {
299
+                    if (is_array($valeur)) {
300
+                        foreach ($valeur as $val2) {
301
+                            $chaine .= "\r\n--$boundary\r\n";
302
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
303
+                            $chaine .= "\r\n";
304
+                            $chaine .= $val2;
305
+                        }
306
+                    } else {
307
+                        $chaine .= "\r\n--$boundary\r\n";
308
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
309
+                        $chaine .= "\r\n";
310
+                        $chaine .= $valeur;
311
+                    }
312
+                }
313
+                $chaine .= "\r\n--$boundary\r\n";
314
+            }
315
+        } else {
316
+            // fabrique une chaine HTTP simple pour un POST
317
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
318
+            $chaine = array();
319
+            if (is_array($donnees)) {
320
+                foreach ($donnees as $cle => $valeur) {
321
+                    if (is_array($valeur)) {
322
+                        foreach ($valeur as $val2) {
323
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
324
+                        }
325
+                    } else {
326
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
327
+                    }
328
+                }
329
+                $chaine = implode('&', $chaine);
330
+            } else {
331
+                $chaine = $donnees;
332
+            }
333
+        }
334
+    }
335
+
336
+    return array($entete, $chaine);
337 337
 }
338 338
 
339 339
 /**
@@ -347,20 +347,20 @@  discard block
 block discarded – undo
347 347
  */
348 348
 function url_to_ascii($url_idn) {
349 349
 
350
-	if ($parts = parse_url($url_idn)) {
351
-		$host = $parts['host'];
352
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
353
-			include_spip('inc/idna_convert.class');
354
-			$IDN = new idna_convert();
355
-			$host_ascii = $IDN->encode($host);
356
-			$url_idn = explode($host, $url_idn, 2);
357
-			$url_idn = implode($host_ascii, $url_idn);
358
-		}
359
-		// et on urlencode les char utf si besoin dans le path
360
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
361
-	}
362
-
363
-	return $url_idn;
350
+    if ($parts = parse_url($url_idn)) {
351
+        $host = $parts['host'];
352
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
353
+            include_spip('inc/idna_convert.class');
354
+            $IDN = new idna_convert();
355
+            $host_ascii = $IDN->encode($host);
356
+            $url_idn = explode($host, $url_idn, 2);
357
+            $url_idn = implode($host_ascii, $url_idn);
358
+        }
359
+        // et on urlencode les char utf si besoin dans le path
360
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) { return urlencode($match[0]); }, $url_idn);
361
+    }
362
+
363
+    return $url_idn;
364 364
 }
365 365
 
366 366
 /**
@@ -400,176 +400,176 @@  discard block
 block discarded – undo
400 400
  *     string file : nom du fichier si enregistre dans un fichier
401 401
  */
402 402
 function recuperer_url($url, $options = array()) {
403
-	$default = array(
404
-		'transcoder' => false,
405
-		'methode' => 'GET',
406
-		'taille_max' => null,
407
-		'datas' => '',
408
-		'boundary' => '',
409
-		'refuser_gz' => false,
410
-		'if_modified_since' => '',
411
-		'uri_referer' => '',
412
-		'file' => '',
413
-		'follow_location' => 10,
414
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
415
-	);
416
-	$options = array_merge($default, $options);
417
-	// copier directement dans un fichier ?
418
-	$copy = $options['file'];
419
-
420
-	if ($options['methode'] == 'HEAD') {
421
-		$options['taille_max'] = 0;
422
-	}
423
-	if (is_null($options['taille_max'])) {
424
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
425
-	}
426
-
427
-	if (!empty($options['datas'])) {
428
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
429
-		if (stripos($head, 'Content-Length:') === false) {
430
-			$head .= 'Content-Length: ' . strlen($postdata);
431
-		}
432
-		$options['datas'] = $head . "\r\n\r\n" . $postdata;
433
-		if (strlen($postdata)) {
434
-			$options['methode'] = 'POST';
435
-		}
436
-	}
437
-
438
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
439
-	$url = preg_replace(',^feed://,i', 'http://', $url);
440
-	if (!tester_url_absolue($url)) {
441
-		$url = 'http://' . $url;
442
-	} elseif (strncmp($url, '//', 2) == 0) {
443
-		$url = 'http:' . $url;
444
-	}
445
-
446
-	$url = url_to_ascii($url);
447
-
448
-	$result = array(
449
-		'status' => 0,
450
-		'headers' => '',
451
-		'page' => '',
452
-		'length' => 0,
453
-		'last_modified' => '',
454
-		'location' => '',
455
-		'url' => $url
456
-	);
457
-
458
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
459
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
460
-
461
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
462
-	list($handle, $fopen) = init_http(
463
-		$options['methode'],
464
-		$url,
465
-		$refuser_gz,
466
-		$options['uri_referer'],
467
-		$options['datas'],
468
-		$options['version_http'],
469
-		$options['if_modified_since']
470
-	);
471
-	if (!$handle) {
472
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
473
-
474
-		return false;
475
-	}
476
-
477
-	// Sauf en fopen, envoyer le flux d'entree
478
-	// et recuperer les en-tetes de reponses
479
-	if (!$fopen) {
480
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
481
-		if (!$res) {
482
-			fclose($handle);
483
-			$t = @parse_url($url);
484
-			$host = $t['host'];
485
-			// Chinoisierie inexplicable pour contrer
486
-			// les actions liberticides de l'empire du milieu
487
-			if (!need_proxy($host)
488
-				and $res = @file_get_contents($url)
489
-			) {
490
-				$result['length'] = strlen($res);
491
-				if ($copy) {
492
-					ecrire_fichier($copy, $res);
493
-					$result['file'] = $copy;
494
-				} else {
495
-					$result['page'] = $res;
496
-				}
497
-				$res = array(
498
-					'status' => 200,
499
-				);
500
-			} else {
501
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
502
-				return false;
503
-			}
504
-		} elseif ($res['location'] and $options['follow_location']) {
505
-			$options['follow_location']--;
506
-			fclose($handle);
507
-			include_spip('inc/filtres');
508
-			$url = suivre_lien($url, $res['location']);
509
-			spip_log("recuperer_url recommence sur $url", 'distant');
510
-
511
-			return recuperer_url($url, $options);
512
-		} elseif ($res['status'] !== 200) {
513
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
514
-		}
515
-		$result['status'] = $res['status'];
516
-		if (isset($res['headers'])) {
517
-			$result['headers'] = $res['headers'];
518
-		}
519
-		if (isset($res['last_modified'])) {
520
-			$result['last_modified'] = $res['last_modified'];
521
-		}
522
-		if (isset($res['location'])) {
523
-			$result['location'] = $res['location'];
524
-		}
525
-	}
526
-
527
-	// on ne veut que les entetes
528
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
529
-		return $result;
530
-	}
531
-
532
-
533
-	// s'il faut deballer, le faire via un fichier temporaire
534
-	// sinon la memoire explose pour les gros flux
535
-
536
-	$gz = false;
537
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
538
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
539
-	}
540
-
541
-	// si on a pas deja recuperer le contenu par une methode detournee
542
-	if (!$result['length']) {
543
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
544
-		fclose($handle);
545
-		if ($copy) {
546
-			$result['length'] = $res;
547
-			$result['file'] = $copy;
548
-		} elseif ($res) {
549
-			$result['page'] = &$res;
550
-			$result['length'] = strlen($result['page']);
551
-		}
552
-		if (!$result['status']) {
553
-			$result['status'] = 200; // on a reussi, donc !
554
-		}
555
-	}
556
-	if (!$result['page']) {
557
-		return $result;
558
-	}
559
-
560
-	// Decompresser au besoin
561
-	if ($gz) {
562
-		$result['page'] = implode('', gzfile($gz));
563
-		supprimer_fichier($gz);
564
-	}
565
-
566
-	// Faut-il l'importer dans notre charset local ?
567
-	if ($options['transcoder']) {
568
-		include_spip('inc/charsets');
569
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
570
-	}
571
-
572
-	return $result;
403
+    $default = array(
404
+        'transcoder' => false,
405
+        'methode' => 'GET',
406
+        'taille_max' => null,
407
+        'datas' => '',
408
+        'boundary' => '',
409
+        'refuser_gz' => false,
410
+        'if_modified_since' => '',
411
+        'uri_referer' => '',
412
+        'file' => '',
413
+        'follow_location' => 10,
414
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
415
+    );
416
+    $options = array_merge($default, $options);
417
+    // copier directement dans un fichier ?
418
+    $copy = $options['file'];
419
+
420
+    if ($options['methode'] == 'HEAD') {
421
+        $options['taille_max'] = 0;
422
+    }
423
+    if (is_null($options['taille_max'])) {
424
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
425
+    }
426
+
427
+    if (!empty($options['datas'])) {
428
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
429
+        if (stripos($head, 'Content-Length:') === false) {
430
+            $head .= 'Content-Length: ' . strlen($postdata);
431
+        }
432
+        $options['datas'] = $head . "\r\n\r\n" . $postdata;
433
+        if (strlen($postdata)) {
434
+            $options['methode'] = 'POST';
435
+        }
436
+    }
437
+
438
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
439
+    $url = preg_replace(',^feed://,i', 'http://', $url);
440
+    if (!tester_url_absolue($url)) {
441
+        $url = 'http://' . $url;
442
+    } elseif (strncmp($url, '//', 2) == 0) {
443
+        $url = 'http:' . $url;
444
+    }
445
+
446
+    $url = url_to_ascii($url);
447
+
448
+    $result = array(
449
+        'status' => 0,
450
+        'headers' => '',
451
+        'page' => '',
452
+        'length' => 0,
453
+        'last_modified' => '',
454
+        'location' => '',
455
+        'url' => $url
456
+    );
457
+
458
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
459
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
460
+
461
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
462
+    list($handle, $fopen) = init_http(
463
+        $options['methode'],
464
+        $url,
465
+        $refuser_gz,
466
+        $options['uri_referer'],
467
+        $options['datas'],
468
+        $options['version_http'],
469
+        $options['if_modified_since']
470
+    );
471
+    if (!$handle) {
472
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
473
+
474
+        return false;
475
+    }
476
+
477
+    // Sauf en fopen, envoyer le flux d'entree
478
+    // et recuperer les en-tetes de reponses
479
+    if (!$fopen) {
480
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
481
+        if (!$res) {
482
+            fclose($handle);
483
+            $t = @parse_url($url);
484
+            $host = $t['host'];
485
+            // Chinoisierie inexplicable pour contrer
486
+            // les actions liberticides de l'empire du milieu
487
+            if (!need_proxy($host)
488
+                and $res = @file_get_contents($url)
489
+            ) {
490
+                $result['length'] = strlen($res);
491
+                if ($copy) {
492
+                    ecrire_fichier($copy, $res);
493
+                    $result['file'] = $copy;
494
+                } else {
495
+                    $result['page'] = $res;
496
+                }
497
+                $res = array(
498
+                    'status' => 200,
499
+                );
500
+            } else {
501
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
502
+                return false;
503
+            }
504
+        } elseif ($res['location'] and $options['follow_location']) {
505
+            $options['follow_location']--;
506
+            fclose($handle);
507
+            include_spip('inc/filtres');
508
+            $url = suivre_lien($url, $res['location']);
509
+            spip_log("recuperer_url recommence sur $url", 'distant');
510
+
511
+            return recuperer_url($url, $options);
512
+        } elseif ($res['status'] !== 200) {
513
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
514
+        }
515
+        $result['status'] = $res['status'];
516
+        if (isset($res['headers'])) {
517
+            $result['headers'] = $res['headers'];
518
+        }
519
+        if (isset($res['last_modified'])) {
520
+            $result['last_modified'] = $res['last_modified'];
521
+        }
522
+        if (isset($res['location'])) {
523
+            $result['location'] = $res['location'];
524
+        }
525
+    }
526
+
527
+    // on ne veut que les entetes
528
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
529
+        return $result;
530
+    }
531
+
532
+
533
+    // s'il faut deballer, le faire via un fichier temporaire
534
+    // sinon la memoire explose pour les gros flux
535
+
536
+    $gz = false;
537
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
538
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
539
+    }
540
+
541
+    // si on a pas deja recuperer le contenu par une methode detournee
542
+    if (!$result['length']) {
543
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
544
+        fclose($handle);
545
+        if ($copy) {
546
+            $result['length'] = $res;
547
+            $result['file'] = $copy;
548
+        } elseif ($res) {
549
+            $result['page'] = &$res;
550
+            $result['length'] = strlen($result['page']);
551
+        }
552
+        if (!$result['status']) {
553
+            $result['status'] = 200; // on a reussi, donc !
554
+        }
555
+    }
556
+    if (!$result['page']) {
557
+        return $result;
558
+    }
559
+
560
+    // Decompresser au besoin
561
+    if ($gz) {
562
+        $result['page'] = implode('', gzfile($gz));
563
+        supprimer_fichier($gz);
564
+    }
565
+
566
+    // Faut-il l'importer dans notre charset local ?
567
+    if ($options['transcoder']) {
568
+        include_spip('inc/charsets');
569
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
570
+    }
571
+
572
+    return $result;
573 573
 }
574 574
 
575 575
 /**
@@ -585,72 +585,72 @@  discard block
 block discarded – undo
585 585
  * @return array|bool|mixed
586 586
  */
587 587
 function recuperer_url_cache($url, $options = array()) {
588
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
589
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
590
-	}
591
-	$default = array(
592
-		'transcoder' => false,
593
-		'methode' => 'GET',
594
-		'taille_max' => null,
595
-		'datas' => '',
596
-		'boundary' => '',
597
-		'refuser_gz' => false,
598
-		'if_modified_since' => '',
599
-		'uri_referer' => '',
600
-		'file' => '',
601
-		'follow_location' => 10,
602
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
603
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
604
-	);
605
-	$options = array_merge($default, $options);
606
-
607
-	// cas ou il n'est pas possible de cacher
608
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
609
-		return recuperer_url($url, $options);
610
-	}
611
-
612
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
613
-	static $errors = array();
614
-	if (isset($errors[$url])) {
615
-		return $errors[$url];
616
-	}
617
-
618
-	$sig = $options;
619
-	unset($sig['if_modified_since']);
620
-	unset($sig['delai_cache']);
621
-	$sig['url'] = $url;
622
-
623
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
624
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
625
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
626
-	$cache = "$sub$cache";
627
-
628
-	$res = false;
629
-	$is_cached = file_exists($cache);
630
-	if ($is_cached
631
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
632
-	) {
633
-		lire_fichier($cache, $res);
634
-		if ($res = unserialize($res)) {
635
-			// mettre le last_modified et le status=304 ?
636
-		}
637
-	}
638
-	if (!$res) {
639
-		$res = recuperer_url($url, $options);
640
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
641
-		if (!$res) {
642
-			if ($is_cached) {
643
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
644
-				lire_fichier($cache, $res);
645
-				$res = unserialize($res);
646
-			}
647
-
648
-			return $errors[$url] = $res;
649
-		}
650
-		ecrire_fichier($cache, serialize($res));
651
-	}
652
-
653
-	return $res;
588
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
589
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
590
+    }
591
+    $default = array(
592
+        'transcoder' => false,
593
+        'methode' => 'GET',
594
+        'taille_max' => null,
595
+        'datas' => '',
596
+        'boundary' => '',
597
+        'refuser_gz' => false,
598
+        'if_modified_since' => '',
599
+        'uri_referer' => '',
600
+        'file' => '',
601
+        'follow_location' => 10,
602
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
603
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
604
+    );
605
+    $options = array_merge($default, $options);
606
+
607
+    // cas ou il n'est pas possible de cacher
608
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
609
+        return recuperer_url($url, $options);
610
+    }
611
+
612
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
613
+    static $errors = array();
614
+    if (isset($errors[$url])) {
615
+        return $errors[$url];
616
+    }
617
+
618
+    $sig = $options;
619
+    unset($sig['if_modified_since']);
620
+    unset($sig['delai_cache']);
621
+    $sig['url'] = $url;
622
+
623
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
624
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
625
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
626
+    $cache = "$sub$cache";
627
+
628
+    $res = false;
629
+    $is_cached = file_exists($cache);
630
+    if ($is_cached
631
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
632
+    ) {
633
+        lire_fichier($cache, $res);
634
+        if ($res = unserialize($res)) {
635
+            // mettre le last_modified et le status=304 ?
636
+        }
637
+    }
638
+    if (!$res) {
639
+        $res = recuperer_url($url, $options);
640
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
641
+        if (!$res) {
642
+            if ($is_cached) {
643
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
644
+                lire_fichier($cache, $res);
645
+                $res = unserialize($res);
646
+            }
647
+
648
+            return $errors[$url] = $res;
649
+        }
650
+        ecrire_fichier($cache, serialize($res));
651
+    }
652
+
653
+    return $res;
654 654
 }
655 655
 
656 656
 /**
@@ -688,52 +688,52 @@  discard block
 block discarded – undo
688 688
  *     - false si la page n'a pu être récupérée (status different de 200)
689 689
  **/
690 690
 function recuperer_page(
691
-	$url,
692
-	$trans = false,
693
-	$get_headers = false,
694
-	$taille_max = null,
695
-	$datas = '',
696
-	$boundary = '',
697
-	$refuser_gz = false,
698
-	$date_verif = '',
699
-	$uri_referer = ''
691
+    $url,
692
+    $trans = false,
693
+    $get_headers = false,
694
+    $taille_max = null,
695
+    $datas = '',
696
+    $boundary = '',
697
+    $refuser_gz = false,
698
+    $date_verif = '',
699
+    $uri_referer = ''
700 700
 ) {
701
-	// $copy = copier le fichier ?
702
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
703
-
704
-	if (!is_null($taille_max) and ($taille_max == 0)) {
705
-		$get = 'HEAD';
706
-	} else {
707
-		$get = 'GET';
708
-	}
709
-
710
-	$options = array(
711
-		'transcoder' => $trans === true,
712
-		'methode' => $get,
713
-		'datas' => $datas,
714
-		'boundary' => $boundary,
715
-		'refuser_gz' => $refuser_gz,
716
-		'if_modified_since' => $date_verif,
717
-		'uri_referer' => $uri_referer,
718
-		'file' => $copy ? $trans : '',
719
-		'follow_location' => 10,
720
-	);
721
-	if (!is_null($taille_max)) {
722
-		$options['taille_max'] = $taille_max;
723
-	}
724
-	// dix tentatives maximum en cas d'entetes 301...
725
-	$res = recuperer_url($url, $options);
726
-	if (!$res) {
727
-		return false;
728
-	}
729
-	if ($res['status'] !== 200) {
730
-		return false;
731
-	}
732
-	if ($get_headers) {
733
-		return $res['headers'] . "\n" . $res['page'];
734
-	}
735
-
736
-	return $res['page'];
701
+    // $copy = copier le fichier ?
702
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
703
+
704
+    if (!is_null($taille_max) and ($taille_max == 0)) {
705
+        $get = 'HEAD';
706
+    } else {
707
+        $get = 'GET';
708
+    }
709
+
710
+    $options = array(
711
+        'transcoder' => $trans === true,
712
+        'methode' => $get,
713
+        'datas' => $datas,
714
+        'boundary' => $boundary,
715
+        'refuser_gz' => $refuser_gz,
716
+        'if_modified_since' => $date_verif,
717
+        'uri_referer' => $uri_referer,
718
+        'file' => $copy ? $trans : '',
719
+        'follow_location' => 10,
720
+    );
721
+    if (!is_null($taille_max)) {
722
+        $options['taille_max'] = $taille_max;
723
+    }
724
+    // dix tentatives maximum en cas d'entetes 301...
725
+    $res = recuperer_url($url, $options);
726
+    if (!$res) {
727
+        return false;
728
+    }
729
+    if ($res['status'] !== 200) {
730
+        return false;
731
+    }
732
+    if ($get_headers) {
733
+        return $res['headers'] . "\n" . $res['page'];
734
+    }
735
+
736
+    return $res['page'];
737 737
 }
738 738
 
739 739
 
@@ -770,48 +770,48 @@  discard block
 block discarded – undo
770 770
  *     - false sinon
771 771
  **/
772 772
 function recuperer_lapage(
773
-	$url,
774
-	$trans = false,
775
-	$get = 'GET',
776
-	$taille_max = 1048576,
777
-	$datas = '',
778
-	$refuser_gz = false,
779
-	$date_verif = '',
780
-	$uri_referer = ''
773
+    $url,
774
+    $trans = false,
775
+    $get = 'GET',
776
+    $taille_max = 1048576,
777
+    $datas = '',
778
+    $refuser_gz = false,
779
+    $date_verif = '',
780
+    $uri_referer = ''
781 781
 ) {
782
-	// $copy = copier le fichier ?
783
-	$copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
784
-
785
-	// si on ecrit directement dans un fichier, pour ne pas manipuler
786
-	// en memoire refuser gz
787
-	if ($copy) {
788
-		$refuser_gz = true;
789
-	}
790
-
791
-	$options = array(
792
-		'transcoder' => $trans === true,
793
-		'methode' => $get,
794
-		'datas' => $datas,
795
-		'refuser_gz' => $refuser_gz,
796
-		'if_modified_since' => $date_verif,
797
-		'uri_referer' => $uri_referer,
798
-		'file' => $copy ? $trans : '',
799
-		'follow_location' => false,
800
-	);
801
-	if (!is_null($taille_max)) {
802
-		$options['taille_max'] = $taille_max;
803
-	}
804
-	// dix tentatives maximum en cas d'entetes 301...
805
-	$res = recuperer_url($url, $options);
806
-
807
-	if (!$res) {
808
-		return false;
809
-	}
810
-	if ($res['status'] !== 200) {
811
-		return false;
812
-	}
813
-
814
-	return array($res['headers'], $res['page']);
782
+    // $copy = copier le fichier ?
783
+    $copy = (is_string($trans) and strlen($trans) > 5); // eviter "false" :-)
784
+
785
+    // si on ecrit directement dans un fichier, pour ne pas manipuler
786
+    // en memoire refuser gz
787
+    if ($copy) {
788
+        $refuser_gz = true;
789
+    }
790
+
791
+    $options = array(
792
+        'transcoder' => $trans === true,
793
+        'methode' => $get,
794
+        'datas' => $datas,
795
+        'refuser_gz' => $refuser_gz,
796
+        'if_modified_since' => $date_verif,
797
+        'uri_referer' => $uri_referer,
798
+        'file' => $copy ? $trans : '',
799
+        'follow_location' => false,
800
+    );
801
+    if (!is_null($taille_max)) {
802
+        $options['taille_max'] = $taille_max;
803
+    }
804
+    // dix tentatives maximum en cas d'entetes 301...
805
+    $res = recuperer_url($url, $options);
806
+
807
+    if (!$res) {
808
+        return false;
809
+    }
810
+    if ($res['status'] !== 200) {
811
+        return false;
812
+    }
813
+
814
+    return array($res['headers'], $res['page']);
815 815
 }
816 816
 
817 817
 /**
@@ -829,41 +829,41 @@  discard block
 block discarded – undo
829 829
  *   string contenu de la resource
830 830
  */
831 831
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
832
-	$taille = 0;
833
-	$result = '';
834
-	$fp = false;
835
-	if ($fichier) {
836
-		include_spip('inc/acces');
837
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
838
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
839
-		if (!$fp and file_exists($fichier)) {
840
-			return filesize($fichier);
841
-		}
842
-		if (!$fp) {
843
-			return false;
844
-		}
845
-		$result = 0; // on renvoie la taille du fichier
846
-	}
847
-	while (!feof($handle) and $taille < $taille_max) {
848
-		$res = fread($handle, 16384);
849
-		$taille += strlen($res);
850
-		if ($fp) {
851
-			fwrite($fp, $res);
852
-			$result = $taille;
853
-		} else {
854
-			$result .= $res;
855
-		}
856
-	}
857
-	if ($fp) {
858
-		spip_fclose_unlock($fp);
859
-		spip_unlink($fichier);
860
-		@rename($tmpfile, $fichier);
861
-		if (!file_exists($fichier)) {
862
-			return false;
863
-		}
864
-	}
865
-
866
-	return $result;
832
+    $taille = 0;
833
+    $result = '';
834
+    $fp = false;
835
+    if ($fichier) {
836
+        include_spip('inc/acces');
837
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
838
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
839
+        if (!$fp and file_exists($fichier)) {
840
+            return filesize($fichier);
841
+        }
842
+        if (!$fp) {
843
+            return false;
844
+        }
845
+        $result = 0; // on renvoie la taille du fichier
846
+    }
847
+    while (!feof($handle) and $taille < $taille_max) {
848
+        $res = fread($handle, 16384);
849
+        $taille += strlen($res);
850
+        if ($fp) {
851
+            fwrite($fp, $res);
852
+            $result = $taille;
853
+        } else {
854
+            $result .= $res;
855
+        }
856
+    }
857
+    if ($fp) {
858
+        spip_fclose_unlock($fp);
859
+        spip_unlink($fichier);
860
+        @rename($tmpfile, $fichier);
861
+        if (!file_exists($fichier)) {
862
+            return false;
863
+        }
864
+    }
865
+
866
+    return $result;
867 867
 }
868 868
 
869 869
 /**
@@ -885,34 +885,34 @@  discard block
 block discarded – undo
885 885
  *   string location
886 886
  */
887 887
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
888
-	$result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
889
-
890
-	$s = @trim(fgets($handle, 16384));
891
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
892
-		return false;
893
-	}
894
-	$result['status'] = intval($r[1]);
895
-	while ($s = trim(fgets($handle, 16384))) {
896
-		$result['headers'][] = $s . "\n";
897
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
898
-		list(, $d, $v) = $r;
899
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
900
-			$result['location'] = $v;
901
-		} elseif ($d == 'Last-Modified') {
902
-			$result['last_modified'] = strtotime($v);
903
-		}
904
-	}
905
-	if ($if_modified_since
906
-		and $result['last_modified']
907
-		and $if_modified_since > $result['last_modified']
908
-		and $result['status'] == 200
909
-	) {
910
-		$result['status'] = 304;
911
-	}
912
-
913
-	$result['headers'] = implode('', $result['headers']);
914
-
915
-	return $result;
888
+    $result = array('status' => 0, 'headers' => array(), 'last_modified' => 0, 'location' => '');
889
+
890
+    $s = @trim(fgets($handle, 16384));
891
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
892
+        return false;
893
+    }
894
+    $result['status'] = intval($r[1]);
895
+    while ($s = trim(fgets($handle, 16384))) {
896
+        $result['headers'][] = $s . "\n";
897
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
898
+        list(, $d, $v) = $r;
899
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
900
+            $result['location'] = $v;
901
+        } elseif ($d == 'Last-Modified') {
902
+            $result['last_modified'] = strtotime($v);
903
+        }
904
+    }
905
+    if ($if_modified_since
906
+        and $result['last_modified']
907
+        and $if_modified_since > $result['last_modified']
908
+        and $result['status'] == 200
909
+    ) {
910
+        $result['status'] = 304;
911
+    }
912
+
913
+    $result['headers'] = implode('', $result['headers']);
914
+
915
+    return $result;
916 916
 }
917 917
 
918 918
 /**
@@ -934,20 +934,20 @@  discard block
 block discarded – undo
934 934
  *     - le tableau des entetes dans tous les autres cas
935 935
  **/
936 936
 function recuperer_entetes($f, $date_verif = '') {
937
-	//Cas ou la page distante n'a pas bouge depuis
938
-	//la derniere visite
939
-	$res = recuperer_entetes_complets($f, $date_verif);
940
-	if (!$res) {
941
-		return false;
942
-	}
943
-	if ($res['location']) {
944
-		return $res['location'];
945
-	}
946
-	if ($res['status'] != 200) {
947
-		return $res['status'];
948
-	}
949
-
950
-	return explode("\n", $res['headers']);
937
+    //Cas ou la page distante n'a pas bouge depuis
938
+    //la derniere visite
939
+    $res = recuperer_entetes_complets($f, $date_verif);
940
+    if (!$res) {
941
+        return false;
942
+    }
943
+    if ($res['location']) {
944
+        return $res['location'];
945
+    }
946
+    if ($res['status'] != 200) {
947
+        return $res['status'];
948
+    }
949
+
950
+    return explode("\n", $res['headers']);
951 951
 }
952 952
 
953 953
 /**
@@ -969,22 +969,22 @@  discard block
 block discarded – undo
969 969
  *     Nom du fichier pour copie locale
970 970
  **/
971 971
 function nom_fichier_copie_locale($source, $extension) {
972
-	include_spip('inc/documents');
972
+    include_spip('inc/documents');
973 973
 
974
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
975
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
974
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
975
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
976 976
 
977
-	// on se place tout le temps comme si on etait a la racine
978
-	if (_DIR_RACINE) {
979
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
980
-	}
977
+    // on se place tout le temps comme si on etait a la racine
978
+    if (_DIR_RACINE) {
979
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
980
+    }
981 981
 
982
-	$m = md5($source);
982
+    $m = md5($source);
983 983
 
984
-	return $d
985
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
986
-	. substr($m, 0, 4)
987
-	. ".$extension";
984
+    return $d
985
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
986
+    . substr($m, 0, 4)
987
+    . ".$extension";
988 988
 }
989 989
 
990 990
 /**
@@ -1002,68 +1002,68 @@  discard block
 block discarded – undo
1002 1002
  *      Nom du fichier calculé
1003 1003
  **/
1004 1004
 function fichier_copie_locale($source) {
1005
-	// Si c'est deja local pas de souci
1006
-	if (!tester_url_absolue($source)) {
1007
-		if (_DIR_RACINE) {
1008
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1009
-		}
1010
-
1011
-		return $source;
1012
-	}
1013
-
1014
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1015
-	// a deja ete copie en local avec cette extension
1016
-	// dans ce cas elle est fiable, pas la peine de requeter en base
1017
-	$path_parts = pathinfo($source);
1018
-	if (!isset($path_parts['extension'])) {
1019
-		$path_parts['extension'] = '';
1020
-	}
1021
-	$ext = $path_parts ? $path_parts['extension'] : '';
1022
-	if ($ext
1023
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1024
-		and $f = nom_fichier_copie_locale($source, $ext)
1025
-		and file_exists(_DIR_RACINE . $f)
1026
-	) {
1027
-		return $f;
1028
-	}
1029
-
1030
-
1031
-	// Si c'est deja dans la table des documents,
1032
-	// ramener le nom de sa copie potentielle
1033
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1034
-
1035
-	if ($ext) {
1036
-		return nom_fichier_copie_locale($source, $ext);
1037
-	}
1038
-
1039
-	// voir si l'extension indiquee dans le nom du fichier est ok
1040
-	// et si il n'aurait pas deja ete rapatrie
1041
-
1042
-	$ext = $path_parts ? $path_parts['extension'] : '';
1043
-
1044
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1045
-		$f = nom_fichier_copie_locale($source, $ext);
1046
-		if (file_exists(_DIR_RACINE . $f)) {
1047
-			return $f;
1048
-		}
1049
-	}
1050
-
1051
-	// Ping  pour voir si son extension est connue et autorisee
1052
-	// avec mise en cache du resultat du ping
1053
-
1054
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1055
-	if (!@file_exists($cache)
1056
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
1057
-		or _request('var_mode') == 'recalcul'
1058
-	) {
1059
-		$path_parts = recuperer_infos_distantes($source, 0, false);
1060
-		ecrire_fichier($cache, serialize($path_parts));
1061
-	}
1062
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1063
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1064
-		return nom_fichier_copie_locale($source, $ext);
1065
-	}
1066
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1005
+    // Si c'est deja local pas de souci
1006
+    if (!tester_url_absolue($source)) {
1007
+        if (_DIR_RACINE) {
1008
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
1009
+        }
1010
+
1011
+        return $source;
1012
+    }
1013
+
1014
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
1015
+    // a deja ete copie en local avec cette extension
1016
+    // dans ce cas elle est fiable, pas la peine de requeter en base
1017
+    $path_parts = pathinfo($source);
1018
+    if (!isset($path_parts['extension'])) {
1019
+        $path_parts['extension'] = '';
1020
+    }
1021
+    $ext = $path_parts ? $path_parts['extension'] : '';
1022
+    if ($ext
1023
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
1024
+        and $f = nom_fichier_copie_locale($source, $ext)
1025
+        and file_exists(_DIR_RACINE . $f)
1026
+    ) {
1027
+        return $f;
1028
+    }
1029
+
1030
+
1031
+    // Si c'est deja dans la table des documents,
1032
+    // ramener le nom de sa copie potentielle
1033
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
1034
+
1035
+    if ($ext) {
1036
+        return nom_fichier_copie_locale($source, $ext);
1037
+    }
1038
+
1039
+    // voir si l'extension indiquee dans le nom du fichier est ok
1040
+    // et si il n'aurait pas deja ete rapatrie
1041
+
1042
+    $ext = $path_parts ? $path_parts['extension'] : '';
1043
+
1044
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1045
+        $f = nom_fichier_copie_locale($source, $ext);
1046
+        if (file_exists(_DIR_RACINE . $f)) {
1047
+            return $f;
1048
+        }
1049
+    }
1050
+
1051
+    // Ping  pour voir si son extension est connue et autorisee
1052
+    // avec mise en cache du resultat du ping
1053
+
1054
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
1055
+    if (!@file_exists($cache)
1056
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
1057
+        or _request('var_mode') == 'recalcul'
1058
+    ) {
1059
+        $path_parts = recuperer_infos_distantes($source, 0, false);
1060
+        ecrire_fichier($cache, serialize($path_parts));
1061
+    }
1062
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
1063
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
1064
+        return nom_fichier_copie_locale($source, $ext);
1065
+    }
1066
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
1067 1067
 }
1068 1068
 
1069 1069
 
@@ -1091,144 +1091,144 @@  discard block
 block discarded – undo
1091 1091
  **/
1092 1092
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
1093 1093
 
1094
-	// pas la peine de perdre son temps
1095
-	if (!tester_url_absolue($source)) {
1096
-		return false;
1097
-	}
1098
-
1099
-	# charger les alias des types mime
1100
-	include_spip('base/typedoc');
1101
-
1102
-	$a = array();
1103
-	$mime_type = '';
1104
-	// On va directement charger le debut des images et des fichiers html,
1105
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1106
-	// ca echoue l'utilisateur devra les entrer...
1107
-	if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1108
-		list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1109
-
1110
-		if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1111
-			$mime_type = (trim($regs[1]));
1112
-		} else {
1113
-			$mime_type = '';
1114
-		} // inconnu
1115
-
1116
-		// Appliquer les alias
1117
-		while (isset($GLOBALS['mime_alias'][$mime_type])) {
1118
-			$mime_type = $GLOBALS['mime_alias'][$mime_type];
1119
-		}
1120
-
1121
-		// Si on a un mime-type insignifiant
1122
-		// text/plain,application/octet-stream ou vide
1123
-		// c'est peut-etre que le serveur ne sait pas
1124
-		// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1125
-		// ou le Content-Disposition: attachment; filename=...
1126
-		$t = null;
1127
-		if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1128
-			if (!$t
1129
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1130
-			) {
1131
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1132
-			}
1133
-			if (!$t
1134
-				and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1135
-				and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1136
-			) {
1137
-				$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1138
-			}
1139
-		}
1140
-
1141
-		// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1142
-		if (!$t) {
1143
-			$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1144
-		}
1145
-
1146
-		// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1147
-		// On essaie de nouveau avec l'extension
1148
-		if (!$t
1149
-			and $mime_type != 'text/plain'
1150
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1151
-		) {
1152
-			# eviter xxx.3 => 3gp (> SPIP 3)
1153
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1154
-		}
1155
-
1156
-		if ($t) {
1157
-			spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1158
-			$a['extension'] = $t['extension'];
1159
-		} else {
1160
-			# par defaut on retombe sur '.bin' si c'est autorise
1161
-			spip_log("mime-type $mime_type inconnu", 'distant');
1162
-			$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1163
-			if (!$t) {
1164
-				return false;
1165
-			}
1166
-			$a['extension'] = $t['extension'];
1167
-		}
1168
-
1169
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1170
-			$a['taille'] = intval($regs[1]);
1171
-		}
1172
-	}
1173
-
1174
-	// Echec avec HEAD, on tente avec GET
1175
-	if (!$a and !$max) {
1176
-		spip_log("tenter GET $source", 'distant');
1177
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1178
-	}
1179
-
1180
-	// si on a rien trouve pas la peine d'insister
1181
-	if (!$a) {
1182
-		return false;
1183
-	}
1184
-
1185
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1186
-	// recharger le document en GET et recuperer des donnees supplementaires...
1187
-	include_spip('inc/filtres_images_lib_mini');
1188
-	if (strpos($mime_type, "image/") === 0
1189
-	  and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1190
-		if ($max == 0
1191
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1192
-			and in_array($extension, formats_image_acceptables())
1193
-			and $charger_si_petite_image
1194
-		) {
1195
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1196
-		} else {
1197
-			if ($a['body']) {
1198
-				$a['extension'] = $extension;
1199
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1200
-				ecrire_fichier($a['fichier'], $a['body']);
1201
-				$size_image = @spip_getimagesize($a['fichier']);
1202
-				$a['largeur'] = intval($size_image[0]);
1203
-				$a['hauteur'] = intval($size_image[1]);
1204
-				$a['type_image'] = true;
1205
-			}
1206
-		}
1207
-	}
1208
-
1209
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1210
-	// ce sera mieux que 0x0
1211
-	// Flash is dead!
1212
-	if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1213
-		and empty($a['largeur'])
1214
-	) {
1215
-		$a['largeur'] = 425;
1216
-		$a['hauteur'] = 350;
1217
-	}
1218
-
1219
-	if ($mime_type == 'text/html') {
1220
-		include_spip('inc/filtres');
1221
-		$page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1222
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1223
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1224
-		}
1225
-		if (!isset($a['taille']) or !$a['taille']) {
1226
-			$a['taille'] = strlen($page); # a peu pres
1227
-		}
1228
-	}
1229
-	$a['mime_type'] = $mime_type;
1230
-
1231
-	return $a;
1094
+    // pas la peine de perdre son temps
1095
+    if (!tester_url_absolue($source)) {
1096
+        return false;
1097
+    }
1098
+
1099
+    # charger les alias des types mime
1100
+    include_spip('base/typedoc');
1101
+
1102
+    $a = array();
1103
+    $mime_type = '';
1104
+    // On va directement charger le debut des images et des fichiers html,
1105
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
1106
+    // ca echoue l'utilisateur devra les entrer...
1107
+    if ($headers = recuperer_page($source, false, true, $max, '', '', true)) {
1108
+        list($headers, $a['body']) = preg_split(',\n\n,', $headers, 2);
1109
+
1110
+        if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1111
+            $mime_type = (trim($regs[1]));
1112
+        } else {
1113
+            $mime_type = '';
1114
+        } // inconnu
1115
+
1116
+        // Appliquer les alias
1117
+        while (isset($GLOBALS['mime_alias'][$mime_type])) {
1118
+            $mime_type = $GLOBALS['mime_alias'][$mime_type];
1119
+        }
1120
+
1121
+        // Si on a un mime-type insignifiant
1122
+        // text/plain,application/octet-stream ou vide
1123
+        // c'est peut-etre que le serveur ne sait pas
1124
+        // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1125
+        // ou le Content-Disposition: attachment; filename=...
1126
+        $t = null;
1127
+        if (in_array($mime_type, array('text/plain', '', 'application/octet-stream'))) {
1128
+            if (!$t
1129
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1130
+            ) {
1131
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1132
+            }
1133
+            if (!$t
1134
+                and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1135
+                and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1136
+            ) {
1137
+                $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1138
+            }
1139
+        }
1140
+
1141
+        // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1142
+        if (!$t) {
1143
+            $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1144
+        }
1145
+
1146
+        // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1147
+        // On essaie de nouveau avec l'extension
1148
+        if (!$t
1149
+            and $mime_type != 'text/plain'
1150
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1151
+        ) {
1152
+            # eviter xxx.3 => 3gp (> SPIP 3)
1153
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($rext[1], '', 'text'));
1154
+        }
1155
+
1156
+        if ($t) {
1157
+            spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1158
+            $a['extension'] = $t['extension'];
1159
+        } else {
1160
+            # par defaut on retombe sur '.bin' si c'est autorise
1161
+            spip_log("mime-type $mime_type inconnu", 'distant');
1162
+            $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1163
+            if (!$t) {
1164
+                return false;
1165
+            }
1166
+            $a['extension'] = $t['extension'];
1167
+        }
1168
+
1169
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1170
+            $a['taille'] = intval($regs[1]);
1171
+        }
1172
+    }
1173
+
1174
+    // Echec avec HEAD, on tente avec GET
1175
+    if (!$a and !$max) {
1176
+        spip_log("tenter GET $source", 'distant');
1177
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1178
+    }
1179
+
1180
+    // si on a rien trouve pas la peine d'insister
1181
+    if (!$a) {
1182
+        return false;
1183
+    }
1184
+
1185
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1186
+    // recharger le document en GET et recuperer des donnees supplementaires...
1187
+    include_spip('inc/filtres_images_lib_mini');
1188
+    if (strpos($mime_type, "image/") === 0
1189
+      and $extension = _image_trouver_extension_depuis_mime($mime_type)) {
1190
+        if ($max == 0
1191
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1192
+            and in_array($extension, formats_image_acceptables())
1193
+            and $charger_si_petite_image
1194
+        ) {
1195
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1196
+        } else {
1197
+            if ($a['body']) {
1198
+                $a['extension'] = $extension;
1199
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1200
+                ecrire_fichier($a['fichier'], $a['body']);
1201
+                $size_image = @spip_getimagesize($a['fichier']);
1202
+                $a['largeur'] = intval($size_image[0]);
1203
+                $a['hauteur'] = intval($size_image[1]);
1204
+                $a['type_image'] = true;
1205
+            }
1206
+        }
1207
+    }
1208
+
1209
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1210
+    // ce sera mieux que 0x0
1211
+    // Flash is dead!
1212
+    if ($a and isset($a['extension']) and $a['extension'] == 'swf'
1213
+        and empty($a['largeur'])
1214
+    ) {
1215
+        $a['largeur'] = 425;
1216
+        $a['hauteur'] = 350;
1217
+    }
1218
+
1219
+    if ($mime_type == 'text/html') {
1220
+        include_spip('inc/filtres');
1221
+        $page = recuperer_page($source, true, false, _INC_DISTANT_MAX_SIZE);
1222
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1223
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1224
+        }
1225
+        if (!isset($a['taille']) or !$a['taille']) {
1226
+            $a['taille'] = strlen($page); # a peu pres
1227
+        }
1228
+    }
1229
+    $a['mime_type'] = $mime_type;
1230
+
1231
+    return $a;
1232 1232
 }
1233 1233
 
1234 1234
 
@@ -1244,45 +1244,45 @@  discard block
 block discarded – undo
1244 1244
  * @return string
1245 1245
  */
1246 1246
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1247
-	if (is_null($http_proxy)) {
1248
-		$http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1249
-	}
1250
-	// rien a faire si pas de proxy :)
1251
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1252
-		return '';
1253
-	}
1254
-
1255
-	if (is_null($http_noproxy)) {
1256
-		$http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1257
-	}
1258
-	// si pas d'exception, on retourne le proxy
1259
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1260
-		return $http_proxy;
1261
-	}
1262
-
1263
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1264
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1265
-	$http_noproxy = str_replace("\n", " ", $http_noproxy);
1266
-	$http_noproxy = str_replace("\r", " ", $http_noproxy);
1267
-	$http_noproxy = " $http_noproxy ";
1268
-	$domain = $host;
1269
-	// si le domaine exact www.example.org est dans les exceptions
1270
-	if (strpos($http_noproxy, " $domain ") !== false)
1271
-		return '';
1272
-
1273
-	while (strpos($domain, '.') !== false) {
1274
-		$domain = explode('.', $domain);
1275
-		array_shift($domain);
1276
-		$domain = implode('.', $domain);
1277
-
1278
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1279
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1280
-			return '';
1281
-		}
1282
-	}
1283
-
1284
-	// ok c'est pas une exception
1285
-	return $http_proxy;
1247
+    if (is_null($http_proxy)) {
1248
+        $http_proxy = isset($GLOBALS['meta']['http_proxy']) ? $GLOBALS['meta']['http_proxy'] : null;
1249
+    }
1250
+    // rien a faire si pas de proxy :)
1251
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1252
+        return '';
1253
+    }
1254
+
1255
+    if (is_null($http_noproxy)) {
1256
+        $http_noproxy = isset($GLOBALS['meta']['http_noproxy']) ? $GLOBALS['meta']['http_noproxy'] : null;
1257
+    }
1258
+    // si pas d'exception, on retourne le proxy
1259
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1260
+        return $http_proxy;
1261
+    }
1262
+
1263
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1264
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1265
+    $http_noproxy = str_replace("\n", " ", $http_noproxy);
1266
+    $http_noproxy = str_replace("\r", " ", $http_noproxy);
1267
+    $http_noproxy = " $http_noproxy ";
1268
+    $domain = $host;
1269
+    // si le domaine exact www.example.org est dans les exceptions
1270
+    if (strpos($http_noproxy, " $domain ") !== false)
1271
+        return '';
1272
+
1273
+    while (strpos($domain, '.') !== false) {
1274
+        $domain = explode('.', $domain);
1275
+        array_shift($domain);
1276
+        $domain = implode('.', $domain);
1277
+
1278
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1279
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1280
+            return '';
1281
+        }
1282
+    }
1283
+
1284
+    // ok c'est pas une exception
1285
+    return $http_proxy;
1286 1286
 }
1287 1287
 
1288 1288
 
@@ -1305,58 +1305,58 @@  discard block
 block discarded – undo
1305 1305
  * @return array
1306 1306
  */
1307 1307
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1308
-	$user = $via_proxy = $proxy_user = '';
1309
-	$fopen = false;
1310
-
1311
-	$t = @parse_url($url);
1312
-	$host = $t['host'];
1313
-	if ($t['scheme'] == 'http') {
1314
-		$scheme = 'http';
1315
-		$noproxy = '';
1316
-	} elseif ($t['scheme'] == 'https') {
1317
-		$scheme = 'ssl';
1318
-		$noproxy = 'ssl://';
1319
-		if (!isset($t['port']) || !($port = $t['port'])) {
1320
-			$t['port'] = 443;
1321
-		}
1322
-	} else {
1323
-		$scheme = $t['scheme'];
1324
-		$noproxy = $scheme . '://';
1325
-	}
1326
-	if (isset($t['user'])) {
1327
-		$user = array($t['user'], $t['pass']);
1328
-	}
1329
-
1330
-	if (!isset($t['port']) || !($port = $t['port'])) {
1331
-		$port = 80;
1332
-	}
1333
-	if (!isset($t['path']) || !($path = $t['path'])) {
1334
-		$path = '/';
1335
-	}
1336
-
1337
-	if (!empty($t['query'])) {
1338
-		$path .= '?' . $t['query'];
1339
-	}
1340
-
1341
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1342
-	if (!$f or !is_resource($f)) {
1343
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1344
-		// ce qui correspond a $f===110
1345
-		if ($f !== 110
1346
-			and !need_proxy($host)
1347
-			and !_request('tester_proxy')
1348
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1349
-		) {
1350
-			$f = @fopen($url, 'rb');
1351
-			spip_log("connexion vers $url par simple fopen", 'distant');
1352
-			$fopen = true;
1353
-		} else {
1354
-			// echec total
1355
-			$f = false;
1356
-		}
1357
-	}
1358
-
1359
-	return array($f, $fopen);
1308
+    $user = $via_proxy = $proxy_user = '';
1309
+    $fopen = false;
1310
+
1311
+    $t = @parse_url($url);
1312
+    $host = $t['host'];
1313
+    if ($t['scheme'] == 'http') {
1314
+        $scheme = 'http';
1315
+        $noproxy = '';
1316
+    } elseif ($t['scheme'] == 'https') {
1317
+        $scheme = 'ssl';
1318
+        $noproxy = 'ssl://';
1319
+        if (!isset($t['port']) || !($port = $t['port'])) {
1320
+            $t['port'] = 443;
1321
+        }
1322
+    } else {
1323
+        $scheme = $t['scheme'];
1324
+        $noproxy = $scheme . '://';
1325
+    }
1326
+    if (isset($t['user'])) {
1327
+        $user = array($t['user'], $t['pass']);
1328
+    }
1329
+
1330
+    if (!isset($t['port']) || !($port = $t['port'])) {
1331
+        $port = 80;
1332
+    }
1333
+    if (!isset($t['path']) || !($path = $t['path'])) {
1334
+        $path = '/';
1335
+    }
1336
+
1337
+    if (!empty($t['query'])) {
1338
+        $path .= '?' . $t['query'];
1339
+    }
1340
+
1341
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1342
+    if (!$f or !is_resource($f)) {
1343
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1344
+        // ce qui correspond a $f===110
1345
+        if ($f !== 110
1346
+            and !need_proxy($host)
1347
+            and !_request('tester_proxy')
1348
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1349
+        ) {
1350
+            $f = @fopen($url, 'rb');
1351
+            spip_log("connexion vers $url par simple fopen", 'distant');
1352
+            $fopen = true;
1353
+        } else {
1354
+            // echec total
1355
+            $f = false;
1356
+        }
1357
+    }
1358
+
1359
+    return array($f, $fopen);
1360 1360
 }
1361 1361
 
1362 1362
 /**
@@ -1391,124 +1391,124 @@  discard block
 block discarded – undo
1391 1391
  *   resource socket vers l'url demandee
1392 1392
  */
1393 1393
 function lance_requete(
1394
-	$method,
1395
-	$scheme,
1396
-	$user,
1397
-	$host,
1398
-	$path,
1399
-	$port,
1400
-	$noproxy,
1401
-	$refuse_gz = false,
1402
-	$referer = '',
1403
-	$datas = '',
1404
-	$vers = 'HTTP/1.0',
1405
-	$date = ''
1394
+    $method,
1395
+    $scheme,
1396
+    $user,
1397
+    $host,
1398
+    $path,
1399
+    $port,
1400
+    $noproxy,
1401
+    $refuse_gz = false,
1402
+    $referer = '',
1403
+    $datas = '',
1404
+    $vers = 'HTTP/1.0',
1405
+    $date = ''
1406 1406
 ) {
1407 1407
 
1408
-	$proxy_user = '';
1409
-	$http_proxy = need_proxy($host);
1410
-	if ($user) {
1411
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1412
-	}
1413
-
1414
-	$connect = '';
1415
-	if ($http_proxy) {
1416
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1417
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1418
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1419
-				. "Host: $path_host\r\n"
1420
-				. "Proxy-Connection: Keep-Alive\r\n";
1421
-		} else {
1422
-			$path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1423
-				. (!$user ? '' : "$user@")
1424
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1425
-		}
1426
-		$t2 = @parse_url($http_proxy);
1427
-		$first_host = $t2['host'];
1428
-		if (!($port = $t2['port'])) {
1429
-			$port = 80;
1430
-		}
1431
-		if ($t2['user']) {
1432
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1433
-		}
1434
-	} else {
1435
-		$first_host = $noproxy . $host;
1436
-	}
1437
-
1438
-	if ($connect) {
1439
-		$streamContext = stream_context_create(array(
1440
-			'ssl' => array(
1441
-				'verify_peer' => false,
1442
-				'allow_self_signed' => true,
1443
-				'SNI_enabled' => true,
1444
-				'peer_name' => $host,
1445
-			)
1446
-		));
1447
-		$f = @stream_socket_client(
1448
-			"tcp://$first_host:$port",
1449
-			$errno,
1450
-			$errstr,
1451
-			_INC_DISTANT_CONNECT_TIMEOUT,
1452
-			STREAM_CLIENT_CONNECT,
1453
-			$streamContext
1454
-		);
1455
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1456
-		if (!$f) {
1457
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1458
-			return $errno;
1459
-		}
1460
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1461
-
1462
-		fputs($f, $connect);
1463
-		fputs($f, "\r\n");
1464
-		$res = fread($f, 1024);
1465
-		if (!$res
1466
-			or !count($res = explode(' ', $res))
1467
-			or $res[1] !== '200'
1468
-		) {
1469
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1470
-			fclose($f);
1471
-
1472
-			return false;
1473
-		}
1474
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1475
-		stream_set_blocking($f, true);
1476
-		// envoyer le handshake
1477
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1478
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1479
-	} else {
1480
-		$ntry = 3;
1481
-		do {
1482
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1483
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1484
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1485
-		if (!$f) {
1486
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1487
-
1488
-			return $errno;
1489
-		}
1490
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1491
-	}
1492
-
1493
-	$site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1494
-
1495
-	$host_port = $host;
1496
-	if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1497
-		$host_port .= ":$port";
1498
-	}
1499
-	$req = "$method $path $vers\r\n"
1500
-		. "Host: $host_port\r\n"
1501
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1502
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1503
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1504
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1505
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1506
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1507
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1408
+    $proxy_user = '';
1409
+    $http_proxy = need_proxy($host);
1410
+    if ($user) {
1411
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1412
+    }
1413
+
1414
+    $connect = '';
1415
+    if ($http_proxy) {
1416
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme , array('tls','ssl'))) {
1417
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1418
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1419
+                . "Host: $path_host\r\n"
1420
+                . "Proxy-Connection: Keep-Alive\r\n";
1421
+        } else {
1422
+            $path = (in_array($scheme , array('tls','ssl')) ? 'https://' : "$scheme://")
1423
+                . (!$user ? '' : "$user@")
1424
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1425
+        }
1426
+        $t2 = @parse_url($http_proxy);
1427
+        $first_host = $t2['host'];
1428
+        if (!($port = $t2['port'])) {
1429
+            $port = 80;
1430
+        }
1431
+        if ($t2['user']) {
1432
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1433
+        }
1434
+    } else {
1435
+        $first_host = $noproxy . $host;
1436
+    }
1437
+
1438
+    if ($connect) {
1439
+        $streamContext = stream_context_create(array(
1440
+            'ssl' => array(
1441
+                'verify_peer' => false,
1442
+                'allow_self_signed' => true,
1443
+                'SNI_enabled' => true,
1444
+                'peer_name' => $host,
1445
+            )
1446
+        ));
1447
+        $f = @stream_socket_client(
1448
+            "tcp://$first_host:$port",
1449
+            $errno,
1450
+            $errstr,
1451
+            _INC_DISTANT_CONNECT_TIMEOUT,
1452
+            STREAM_CLIENT_CONNECT,
1453
+            $streamContext
1454
+        );
1455
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1456
+        if (!$f) {
1457
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1458
+            return $errno;
1459
+        }
1460
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1461
+
1462
+        fputs($f, $connect);
1463
+        fputs($f, "\r\n");
1464
+        $res = fread($f, 1024);
1465
+        if (!$res
1466
+            or !count($res = explode(' ', $res))
1467
+            or $res[1] !== '200'
1468
+        ) {
1469
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1470
+            fclose($f);
1471
+
1472
+            return false;
1473
+        }
1474
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1475
+        stream_set_blocking($f, true);
1476
+        // envoyer le handshake
1477
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1478
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1479
+    } else {
1480
+        $ntry = 3;
1481
+        do {
1482
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1483
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1484
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1485
+        if (!$f) {
1486
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1487
+
1488
+            return $errno;
1489
+        }
1490
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1491
+    }
1492
+
1493
+    $site = isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '';
1494
+
1495
+    $host_port = $host;
1496
+    if ($port != (in_array($scheme , array('tls','ssl')) ? 443 : 80)) {
1497
+        $host_port .= ":$port";
1498
+    }
1499
+    $req = "$method $path $vers\r\n"
1500
+        . "Host: $host_port\r\n"
1501
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1502
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1503
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1504
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1505
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1506
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1507
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1508 1508
 
1509 1509
 #	spip_log("Requete\n$req", 'distant');
1510
-	fputs($f, $req);
1511
-	fputs($f, $datas ? $datas : "\r\n");
1510
+    fputs($f, $req);
1511
+    fputs($f, $datas ? $datas : "\r\n");
1512 1512
 
1513
-	return $f;
1513
+    return $f;
1514 1514
 }
Please login to merge, or discard this patch.
ecrire/inc/editer.php 4 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
  * utile pour les textes > 32ko
315 315
  *
316 316
  * @param  string $texte
317
- * @return array
317
+ * @return string[]
318 318
  */
319 319
 function coupe_trop_long($texte) {
320 320
 	$aider = charger_fonction('aider', 'inc');
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
  *
348 348
  * @param string $texte
349 349
  * @param string $att_text
350
- * @return array
350
+ * @return string[]
351 351
  */
352 352
 function editer_texte_recolle($texte, $att_text) {
353 353
 	if ((strlen($texte) < 29 * 1024)
@@ -373,8 +373,8 @@  discard block
 block discarded – undo
373 373
 /**
374 374
  * auto-renseigner le titre si il n'existe pas
375 375
  *
376
- * @param $champ_titre
377
- * @param $champs_contenu
376
+ * @param string $champ_titre
377
+ * @param string[] $champs_contenu
378 378
  * @param int $longueur
379 379
  */
380 380
 function titre_automatique($champ_titre, $champs_contenu, $longueur = null) {
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -329,8 +329,7 @@
 block discarded – undo
329 329
 		if (!autoriser('modifier', $type, intval($id))){
330 330
 			$valeurs['editable'] = '';
331 331
 		}
332
-	}
333
-	else {
332
+	} else {
334 333
 		if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
335 334
 			$valeurs['editable'] = '';
336 335
 		}
Please login to merge, or discard this patch.
Indentation   +486 added lines, -486 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('base/abstract_sql');
23 23
 
@@ -59,56 +59,56 @@  discard block
 block discarded – undo
59 59
  *     Retour des traitements.
60 60
  **/
61 61
 function formulaires_editer_objet_traiter(
62
-	$type,
63
-	$id = 'new',
64
-	$id_parent = 0,
65
-	$lier_trad = 0,
66
-	$retour = '',
67
-	$config_fonc = 'articles_edit_config',
68
-	$row = array(),
69
-	$hidden = ''
62
+    $type,
63
+    $id = 'new',
64
+    $id_parent = 0,
65
+    $lier_trad = 0,
66
+    $retour = '',
67
+    $config_fonc = 'articles_edit_config',
68
+    $row = array(),
69
+    $hidden = ''
70 70
 ) {
71 71
 
72
-	$res = array();
73
-	// eviter la redirection forcee par l'action...
74
-	set_request('redirect');
75
-	if ($action_editer = charger_fonction("editer_$type", 'action', true)) {
76
-		list($id, $err) = $action_editer($id);
77
-	} else {
78
-		$action_editer = charger_fonction('editer_objet', 'action');
79
-		list($id, $err) = $action_editer($id, $type);
80
-	}
81
-	$id_table_objet = id_table_objet($type);
82
-	$res[$id_table_objet] = $id;
83
-	if ($err or !$id) {
84
-		$res['message_erreur'] = ($err ? $err : _T('erreur'));
85
-	} else {
86
-		// Un lien de trad a prendre en compte
87
-		if ($lier_trad) {
88
-			// referencer la traduction
89
-			$referencer_traduction = charger_fonction('referencer_traduction', 'action');
90
-			$referencer_traduction($type, $id, $lier_trad);
91
-			// actions de recopie de champs / liens sur le nouvel objet créé
92
-			$completer_traduction = charger_fonction('completer_traduction', 'inc');
93
-			$err = $completer_traduction($type, $id, $lier_trad);
94
-			if ($err) {
95
-				$res['message_erreur'] = $err;
96
-				return $res;
97
-			}
98
-		}
99
-
100
-		$res['message_ok'] = _T('info_modification_enregistree');
101
-		if ($retour) {
102
-			if (strncmp($retour, 'javascript:', 11) == 0) {
103
-				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
104
-				$res['editable'] = true;
105
-			} else {
106
-				$res['redirect'] = parametre_url($retour, $id_table_objet, $id);
107
-			}
108
-		}
109
-	}
110
-
111
-	return $res;
72
+    $res = array();
73
+    // eviter la redirection forcee par l'action...
74
+    set_request('redirect');
75
+    if ($action_editer = charger_fonction("editer_$type", 'action', true)) {
76
+        list($id, $err) = $action_editer($id);
77
+    } else {
78
+        $action_editer = charger_fonction('editer_objet', 'action');
79
+        list($id, $err) = $action_editer($id, $type);
80
+    }
81
+    $id_table_objet = id_table_objet($type);
82
+    $res[$id_table_objet] = $id;
83
+    if ($err or !$id) {
84
+        $res['message_erreur'] = ($err ? $err : _T('erreur'));
85
+    } else {
86
+        // Un lien de trad a prendre en compte
87
+        if ($lier_trad) {
88
+            // referencer la traduction
89
+            $referencer_traduction = charger_fonction('referencer_traduction', 'action');
90
+            $referencer_traduction($type, $id, $lier_trad);
91
+            // actions de recopie de champs / liens sur le nouvel objet créé
92
+            $completer_traduction = charger_fonction('completer_traduction', 'inc');
93
+            $err = $completer_traduction($type, $id, $lier_trad);
94
+            if ($err) {
95
+                $res['message_erreur'] = $err;
96
+                return $res;
97
+            }
98
+        }
99
+
100
+        $res['message_ok'] = _T('info_modification_enregistree');
101
+        if ($retour) {
102
+            if (strncmp($retour, 'javascript:', 11) == 0) {
103
+                $res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
104
+                $res['editable'] = true;
105
+            } else {
106
+                $res['redirect'] = parametre_url($retour, $id_table_objet, $id);
107
+            }
108
+        }
109
+    }
110
+
111
+    return $res;
112 112
 }
113 113
 
114 114
 /**
@@ -132,29 +132,29 @@  discard block
 block discarded – undo
132 132
  *     Tableau des erreurs
133 133
  **/
134 134
 function formulaires_editer_objet_verifier($type, $id = 'new', $oblis = array()) {
135
-	$erreurs = array();
136
-	if (intval($id)) {
137
-		$conflits = controler_contenu($type, $id);
138
-		if ($conflits and count($conflits)) {
139
-			foreach ($conflits as $champ => $conflit) {
140
-				if (!isset($erreurs[$champ])) {
141
-					$erreurs[$champ] = '';
142
-				}
143
-				$erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
144
-			}
145
-		}
146
-	}
147
-	foreach ($oblis as $obli) {
148
-		$value = _request($obli);
149
-		if (is_null($value) or !(is_array($value) ? count($value) : strlen($value))) {
150
-			if (!isset($erreurs[$obli])) {
151
-				$erreurs[$obli] = '';
152
-			}
153
-			$erreurs[$obli] .= _T('info_obligatoire');
154
-		}
155
-	}
156
-
157
-	return $erreurs;
135
+    $erreurs = array();
136
+    if (intval($id)) {
137
+        $conflits = controler_contenu($type, $id);
138
+        if ($conflits and count($conflits)) {
139
+            foreach ($conflits as $champ => $conflit) {
140
+                if (!isset($erreurs[$champ])) {
141
+                    $erreurs[$champ] = '';
142
+                }
143
+                $erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
144
+            }
145
+        }
146
+    }
147
+    foreach ($oblis as $obli) {
148
+        $value = _request($obli);
149
+        if (is_null($value) or !(is_array($value) ? count($value) : strlen($value))) {
150
+            if (!isset($erreurs[$obli])) {
151
+                $erreurs[$obli] = '';
152
+            }
153
+            $erreurs[$obli] .= _T('info_obligatoire');
154
+        }
155
+    }
156
+
157
+    return $erreurs;
158 158
 }
159 159
 
160 160
 /**
@@ -198,145 +198,145 @@  discard block
 block discarded – undo
198 198
  *     Environnement du formulaire.
199 199
  **/
200 200
 function formulaires_editer_objet_charger(
201
-	$type,
202
-	$id = 'new',
203
-	$id_parent = 0,
204
-	$lier_trad = 0,
205
-	$retour = '',
206
-	$config_fonc = 'articles_edit_config',
207
-	$row = array(),
208
-	$hidden = ''
201
+    $type,
202
+    $id = 'new',
203
+    $id_parent = 0,
204
+    $lier_trad = 0,
205
+    $retour = '',
206
+    $config_fonc = 'articles_edit_config',
207
+    $row = array(),
208
+    $hidden = ''
209 209
 ) {
210 210
 
211
-	$table_objet = table_objet($type);
212
-	$table_objet_sql = table_objet_sql($type);
213
-	$id_table_objet = id_table_objet($type);
214
-
215
-	// on accepte pas une fonction de config inconnue si elle vient d'un modele
216
-	if ($config_fonc
217
-	  and !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
218
-	  and $config_fonc !== $table_objet . '_edit_config') {
219
-		if ($args = test_formulaire_inclus_par_modele()
220
-		  and in_array($config_fonc, $args)) {
221
-			$config_fonc = '';
222
-		}
223
-	}
224
-
225
-	$new = !is_numeric($id);
226
-	$lang_default = '';
227
-	// Appel direct dans un squelette
228
-	if (!$row) {
229
-		if (!$new or $lier_trad) {
230
-			if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
231
-				$row = $select($id, $id_parent, $lier_trad);
232
-				// si on a une fonction precharger, elle pu faire un reglage de langue
233
-				$lang_default = (!empty($row['lang']) ? $row['lang'] : null);
234
-			} else {
235
-				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . intval($id));
236
-			}
237
-			if (!$new) {
238
-				$md5 = controles_md5($row);
239
-			}
240
-		}
241
-		if (!$row) {
242
-			$row = array();
243
-			$trouver_table = charger_fonction('trouver_table', 'base');
244
-			if ($desc = $trouver_table($table_objet)) {
245
-				foreach ($desc['field'] as $k => $v) {
246
-					$row[$k] = '';
247
-				}
248
-			}
249
-		}
250
-	}
251
-
252
-	// Gaffe: sans ceci, on ecrase systematiquement l'article d'origine
253
-	// (et donc: pas de lien de traduction)
254
-	$id = ($new or $lier_trad)
255
-		? 'oui'
256
-		: $row[$id_table_objet];
257
-	$row[$id_table_objet] = $id;
258
-
259
-	$contexte = $row;
260
-	if (strlen($id_parent) && is_numeric($id_parent) && (!isset($contexte['id_parent']) or $new)) {
261
-		if (!isset($contexte['id_parent'])) {
262
-			unset($contexte['id_rubrique']);
263
-		}
264
-		$contexte['id_parent'] = $id_parent;
265
-	} elseif (!isset($contexte['id_parent'])) {
266
-		// id_rubrique dans id_parent si possible
267
-		if (isset($contexte['id_rubrique'])) {
268
-			$contexte['id_parent'] = $contexte['id_rubrique'];
269
-			unset($contexte['id_rubrique']);
270
-		} else {
271
-			$contexte['id_parent'] = '';
272
-		}
273
-		if (!$contexte['id_parent']
274
-			and $preselectionner_parent_nouvel_objet = charger_fonction('preselectionner_parent_nouvel_objet', 'inc', true)
275
-		) {
276
-			$contexte['id_parent'] = $preselectionner_parent_nouvel_objet($type, $row);
277
-		}
278
-	}
279
-
280
-	$config = array();
281
-	if ($config_fonc) {
282
-		$contexte['config'] = $config = $config_fonc($contexte);
283
-		if (!$lang_default) {
284
-			$lang_default = $config['langue'] ?? session_get('lang') ;
285
-		}
286
-	}
287
-	$config = $config + array(
288
-		'lignes' => 0,
289
-		'langue' => '',
290
-	);
291
-
292
-	$att_text = " class='textarea' "
293
-		. " rows='"
294
-		. ($config['lignes'] + 15)
295
-		. "' cols='40'";
296
-	if (isset($contexte['texte'])) {
297
-		list($contexte['texte'], $contexte['_texte_trop_long']) = editer_texte_recolle($contexte['texte'], $att_text);
298
-	}
299
-
300
-	// on veut conserver la langue de l'interface ;
301
-	// on passe cette donnee sous un autre nom, au cas ou le squelette
302
-	// voudrait l'exploiter
303
-	if (isset($contexte['lang'])) {
304
-		$contexte['langue'] = $contexte['lang'];
305
-		unset($contexte['lang']);
306
-	}
307
-
308
-	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
309
-		(!$lier_trad ? '' :
310
-			("\n<input type='hidden' name='lier_trad' value='" .
311
-				$lier_trad .
312
-				"' />" .
313
-				"\n<input type='hidden' name='changer_lang' value='" .
314
-				$lang_default .
315
-				"' />"))
316
-		. $hidden
317
-		. (isset($md5) ? $md5 : '');
318
-
319
-	// preciser que le formulaire doit passer dans un pipeline
320
-	$contexte['_pipeline'] = array('editer_contenu_objet', array('type' => $type, 'id' => $id));
321
-
322
-	// preciser que le formulaire doit etre securise auteur/action
323
-	// n'est plus utile lorsque l'action accepte l'id en argument direct
324
-	// on le garde pour compat
325
-	$contexte['_action'] = array("editer_$type", $id);
326
-
327
-	// et in fine placer l'autorisation
328
-	if (intval($id)){
329
-		if (!autoriser('modifier', $type, intval($id))){
330
-			$valeurs['editable'] = '';
331
-		}
332
-	}
333
-	else {
334
-		if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
335
-			$valeurs['editable'] = '';
336
-		}
337
-	}
338
-
339
-	return $contexte;
211
+    $table_objet = table_objet($type);
212
+    $table_objet_sql = table_objet_sql($type);
213
+    $id_table_objet = id_table_objet($type);
214
+
215
+    // on accepte pas une fonction de config inconnue si elle vient d'un modele
216
+    if ($config_fonc
217
+      and !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
218
+      and $config_fonc !== $table_objet . '_edit_config') {
219
+        if ($args = test_formulaire_inclus_par_modele()
220
+          and in_array($config_fonc, $args)) {
221
+            $config_fonc = '';
222
+        }
223
+    }
224
+
225
+    $new = !is_numeric($id);
226
+    $lang_default = '';
227
+    // Appel direct dans un squelette
228
+    if (!$row) {
229
+        if (!$new or $lier_trad) {
230
+            if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
231
+                $row = $select($id, $id_parent, $lier_trad);
232
+                // si on a une fonction precharger, elle pu faire un reglage de langue
233
+                $lang_default = (!empty($row['lang']) ? $row['lang'] : null);
234
+            } else {
235
+                $row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . intval($id));
236
+            }
237
+            if (!$new) {
238
+                $md5 = controles_md5($row);
239
+            }
240
+        }
241
+        if (!$row) {
242
+            $row = array();
243
+            $trouver_table = charger_fonction('trouver_table', 'base');
244
+            if ($desc = $trouver_table($table_objet)) {
245
+                foreach ($desc['field'] as $k => $v) {
246
+                    $row[$k] = '';
247
+                }
248
+            }
249
+        }
250
+    }
251
+
252
+    // Gaffe: sans ceci, on ecrase systematiquement l'article d'origine
253
+    // (et donc: pas de lien de traduction)
254
+    $id = ($new or $lier_trad)
255
+        ? 'oui'
256
+        : $row[$id_table_objet];
257
+    $row[$id_table_objet] = $id;
258
+
259
+    $contexte = $row;
260
+    if (strlen($id_parent) && is_numeric($id_parent) && (!isset($contexte['id_parent']) or $new)) {
261
+        if (!isset($contexte['id_parent'])) {
262
+            unset($contexte['id_rubrique']);
263
+        }
264
+        $contexte['id_parent'] = $id_parent;
265
+    } elseif (!isset($contexte['id_parent'])) {
266
+        // id_rubrique dans id_parent si possible
267
+        if (isset($contexte['id_rubrique'])) {
268
+            $contexte['id_parent'] = $contexte['id_rubrique'];
269
+            unset($contexte['id_rubrique']);
270
+        } else {
271
+            $contexte['id_parent'] = '';
272
+        }
273
+        if (!$contexte['id_parent']
274
+            and $preselectionner_parent_nouvel_objet = charger_fonction('preselectionner_parent_nouvel_objet', 'inc', true)
275
+        ) {
276
+            $contexte['id_parent'] = $preselectionner_parent_nouvel_objet($type, $row);
277
+        }
278
+    }
279
+
280
+    $config = array();
281
+    if ($config_fonc) {
282
+        $contexte['config'] = $config = $config_fonc($contexte);
283
+        if (!$lang_default) {
284
+            $lang_default = $config['langue'] ?? session_get('lang') ;
285
+        }
286
+    }
287
+    $config = $config + array(
288
+        'lignes' => 0,
289
+        'langue' => '',
290
+    );
291
+
292
+    $att_text = " class='textarea' "
293
+        . " rows='"
294
+        . ($config['lignes'] + 15)
295
+        . "' cols='40'";
296
+    if (isset($contexte['texte'])) {
297
+        list($contexte['texte'], $contexte['_texte_trop_long']) = editer_texte_recolle($contexte['texte'], $att_text);
298
+    }
299
+
300
+    // on veut conserver la langue de l'interface ;
301
+    // on passe cette donnee sous un autre nom, au cas ou le squelette
302
+    // voudrait l'exploiter
303
+    if (isset($contexte['lang'])) {
304
+        $contexte['langue'] = $contexte['lang'];
305
+        unset($contexte['lang']);
306
+    }
307
+
308
+    $contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
309
+        (!$lier_trad ? '' :
310
+            ("\n<input type='hidden' name='lier_trad' value='" .
311
+                $lier_trad .
312
+                "' />" .
313
+                "\n<input type='hidden' name='changer_lang' value='" .
314
+                $lang_default .
315
+                "' />"))
316
+        . $hidden
317
+        . (isset($md5) ? $md5 : '');
318
+
319
+    // preciser que le formulaire doit passer dans un pipeline
320
+    $contexte['_pipeline'] = array('editer_contenu_objet', array('type' => $type, 'id' => $id));
321
+
322
+    // preciser que le formulaire doit etre securise auteur/action
323
+    // n'est plus utile lorsque l'action accepte l'id en argument direct
324
+    // on le garde pour compat
325
+    $contexte['_action'] = array("editer_$type", $id);
326
+
327
+    // et in fine placer l'autorisation
328
+    if (intval($id)){
329
+        if (!autoriser('modifier', $type, intval($id))){
330
+            $valeurs['editable'] = '';
331
+        }
332
+    }
333
+    else {
334
+        if (!autoriser('creer', $type, 0, null, ['id_parent' => $id_parent])) {
335
+            $valeurs['editable'] = '';
336
+        }
337
+    }
338
+
339
+    return $contexte;
340 340
 }
341 341
 
342 342
 /**
@@ -347,29 +347,29 @@  discard block
 block discarded – undo
347 347
  * @return array
348 348
  */
349 349
 function coupe_trop_long($texte) {
350
-	$aider = charger_fonction('aider', 'inc');
351
-	if (strlen($texte) > 28 * 1024) {
352
-		$texte = str_replace("\r\n", "\n", $texte);
353
-		$pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
354
-		if ($pos > 0 and $pos < 32 * 1024) {
355
-			$debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
356
-			$suite = substr($texte, $pos + 2);
357
-		} else {
358
-			$pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
359
-			if (!($pos > 0 and $pos < 32 * 1024)) {
360
-				$pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
361
-				$decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
362
-			} else {
363
-				$decalage = 1;
364
-			}
365
-			$debut = substr($texte, 0, $pos + $decalage); // Il faut conserver l'espace s'il y en a un
366
-			$suite = substr($texte, $pos + $decalage);
367
-		}
368
-
369
-		return (array($debut, $suite));
370
-	} else {
371
-		return (array($texte, ''));
372
-	}
350
+    $aider = charger_fonction('aider', 'inc');
351
+    if (strlen($texte) > 28 * 1024) {
352
+        $texte = str_replace("\r\n", "\n", $texte);
353
+        $pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
354
+        if ($pos > 0 and $pos < 32 * 1024) {
355
+            $debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
356
+            $suite = substr($texte, $pos + 2);
357
+        } else {
358
+            $pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
359
+            if (!($pos > 0 and $pos < 32 * 1024)) {
360
+                $pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
361
+                $decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
362
+            } else {
363
+                $decalage = 1;
364
+            }
365
+            $debut = substr($texte, 0, $pos + $decalage); // Il faut conserver l'espace s'il y en a un
366
+            $suite = substr($texte, $pos + $decalage);
367
+        }
368
+
369
+        return (array($debut, $suite));
370
+    } else {
371
+        return (array($texte, ''));
372
+    }
373 373
 }
374 374
 
375 375
 /**
@@ -380,24 +380,24 @@  discard block
 block discarded – undo
380 380
  * @return array
381 381
  */
382 382
 function editer_texte_recolle($texte, $att_text) {
383
-	if ((strlen($texte) < 29 * 1024)
384
-		or (include_spip('inc/layer') and ($GLOBALS['browser_name'] != 'MSIE'))
385
-	) {
386
-		return array($texte, '');
387
-	}
388
-
389
-	include_spip('inc/barre');
390
-	$textes_supplement = "<br /><span style='color: red'>" . _T('info_texte_long') . "</span>\n";
391
-	$nombre = 0;
392
-
393
-	while (strlen($texte) > 29 * 1024) {
394
-		$nombre++;
395
-		list($texte1, $texte) = coupe_trop_long($texte);
396
-		$textes_supplement .= '<br />' .
397
-			"<textarea id='texte$nombre' name='texte_plus[$nombre]'$att_text>$texte1</textarea>\n";
398
-	}
399
-
400
-	return array($texte, $textes_supplement);
383
+    if ((strlen($texte) < 29 * 1024)
384
+        or (include_spip('inc/layer') and ($GLOBALS['browser_name'] != 'MSIE'))
385
+    ) {
386
+        return array($texte, '');
387
+    }
388
+
389
+    include_spip('inc/barre');
390
+    $textes_supplement = "<br /><span style='color: red'>" . _T('info_texte_long') . "</span>\n";
391
+    $nombre = 0;
392
+
393
+    while (strlen($texte) > 29 * 1024) {
394
+        $nombre++;
395
+        list($texte1, $texte) = coupe_trop_long($texte);
396
+        $textes_supplement .= '<br />' .
397
+            "<textarea id='texte$nombre' name='texte_plus[$nombre]'$att_text>$texte1</textarea>\n";
398
+    }
399
+
400
+    return array($texte, $textes_supplement);
401 401
 }
402 402
 
403 403
 /**
@@ -408,17 +408,17 @@  discard block
 block discarded – undo
408 408
  * @param int $longueur
409 409
  */
410 410
 function titre_automatique($champ_titre, $champs_contenu, $longueur = null) {
411
-	if (!_request($champ_titre)) {
412
-		$titrer_contenu = charger_fonction('titrer_contenu', 'inc');
413
-		if (!is_null($longueur)) {
414
-			$t = $titrer_contenu($champs_contenu, null, $longueur);
415
-		} else {
416
-			$t = $titrer_contenu($champs_contenu);
417
-		}
418
-		if ($t) {
419
-			set_request($champ_titre, $t);
420
-		}
421
-	}
411
+    if (!_request($champ_titre)) {
412
+        $titrer_contenu = charger_fonction('titrer_contenu', 'inc');
413
+        if (!is_null($longueur)) {
414
+            $t = $titrer_contenu($champs_contenu, null, $longueur);
415
+        } else {
416
+            $t = $titrer_contenu($champs_contenu);
417
+        }
418
+        if ($t) {
419
+            set_request($champ_titre, $t);
420
+        }
421
+    }
422 422
 }
423 423
 
424 424
 /**
@@ -438,20 +438,20 @@  discard block
 block discarded – undo
438 438
  * @return string
439 439
  */
440 440
 function inc_titrer_contenu_dist($champs_contenu, $c = null, $longueur = 50) {
441
-	// trouver un champ texte non vide
442
-	$t = '';
443
-	foreach ($champs_contenu as $champ) {
444
-		if ($t = _request($champ, $c)) {
445
-			break;
446
-		}
447
-	}
448
-
449
-	if ($t) {
450
-		include_spip('inc/texte_mini');
451
-		$t = couper($t, $longueur, '...');
452
-	}
453
-
454
-	return $t;
441
+    // trouver un champ texte non vide
442
+    $t = '';
443
+    foreach ($champs_contenu as $champ) {
444
+        if ($t = _request($champ, $c)) {
445
+            break;
446
+        }
447
+    }
448
+
449
+    if ($t) {
450
+        include_spip('inc/texte_mini');
451
+        $t = couper($t, $longueur, '...');
452
+    }
453
+
454
+    return $t;
455 455
 }
456 456
 
457 457
 /**
@@ -474,30 +474,30 @@  discard block
 block discarded – undo
474 474
  *      - array sinon couples ('$prefixe$colonne => md5)
475 475
  **/
476 476
 function controles_md5($data, $prefixe = 'ctr_', $format = 'html') {
477
-	if (!is_array($data)) {
478
-		return false;
479
-	}
480
-
481
-	$ctr = array();
482
-	foreach ($data as $key => $val) {
483
-		$m = md5($val);
484
-		$k = $prefixe . $key;
485
-
486
-		switch ($format) {
487
-			case 'html':
488
-				$ctr[$k] = "<input type='hidden' value='$m' name='$k' />";
489
-				break;
490
-			default:
491
-				$ctr[$k] = $m;
492
-				break;
493
-		}
494
-	}
495
-
496
-	if ($format == 'html') {
497
-		return "\n\n<!-- controles md5 -->\n" . join("\n", $ctr) . "\n\n";
498
-	} else {
499
-		return $ctr;
500
-	}
477
+    if (!is_array($data)) {
478
+        return false;
479
+    }
480
+
481
+    $ctr = array();
482
+    foreach ($data as $key => $val) {
483
+        $m = md5($val);
484
+        $k = $prefixe . $key;
485
+
486
+        switch ($format) {
487
+            case 'html':
488
+                $ctr[$k] = "<input type='hidden' value='$m' name='$k' />";
489
+                break;
490
+            default:
491
+                $ctr[$k] = $m;
492
+                break;
493
+        }
494
+    }
495
+
496
+    if ($format == 'html') {
497
+        return "\n\n<!-- controles md5 -->\n" . join("\n", $ctr) . "\n\n";
498
+    } else {
499
+        return $ctr;
500
+    }
501 501
 }
502 502
 
503 503
 /**
@@ -536,79 +536,79 @@  discard block
 block discarded – undo
536 536
  *     - post : le contenu posté
537 537
  **/
538 538
 function controler_contenu($type, $id, $options = array(), $c = false, $serveur = '') {
539
-	include_spip('inc/filtres');
540
-
541
-	$table_objet = table_objet($type);
542
-	$spip_table_objet = table_objet_sql($type);
543
-	$trouver_table = charger_fonction('trouver_table', 'base');
544
-	$desc = $trouver_table($table_objet, $serveur);
545
-
546
-	// Appels incomplets (sans $c)
547
-	if (!is_array($c)) {
548
-		foreach ($desc['field'] as $champ => $ignore) {
549
-			if (_request($champ)) {
550
-				$c[$champ] = _request($champ);
551
-			}
552
-		}
553
-	}
554
-
555
-	// Securite : certaines variables ne sont jamais acceptees ici
556
-	// car elles ne relevent pas de autoriser(article, modifier) ;
557
-	// il faut passer par instituer_XX()
558
-	// TODO: faut-il passer ces variables interdites
559
-	// dans un fichier de description separe ?
560
-	unset($c['statut']);
561
-	unset($c['id_parent']);
562
-	unset($c['id_rubrique']);
563
-	unset($c['id_secteur']);
564
-
565
-	// Gerer les champs non vides
566
-	if (isset($options['nonvide']) and is_array($options['nonvide'])) {
567
-		foreach ($options['nonvide'] as $champ => $sinon) {
568
-			if ($c[$champ] === '') {
569
-				$c[$champ] = $sinon;
570
-			}
571
-		}
572
-	}
573
-
574
-	// N'accepter que les champs qui existent
575
-	// [TODO] ici aussi on peut valider les contenus en fonction du type
576
-	$champs = array();
577
-	foreach ($desc['field'] as $champ => $ignore) {
578
-		if (isset($c[$champ])) {
579
-			$champs[$champ] = $c[$champ];
580
-		}
581
-	}
582
-
583
-	// Nettoyer les valeurs
584
-	$champs = array_map('corriger_caracteres', $champs);
585
-
586
-	// Envoyer aux plugins
587
-	$champs = pipeline(
588
-		'pre_edition',
589
-		array(
590
-			'args' => array(
591
-				'table' => $spip_table_objet, // compatibilite
592
-				'table_objet' => $table_objet,
593
-				'spip_table_objet' => $spip_table_objet,
594
-				'type' => $type,
595
-				'id_objet' => $id,
596
-				'champs' => isset($options['champs']) ? $options['champs'] : array(), // [doc] c'est quoi ?
597
-				'action' => 'controler',
598
-				'serveur' => $serveur,
599
-			),
600
-			'data' => $champs
601
-		)
602
-	);
603
-
604
-	if (!$champs) {
605
-		return false;
606
-	}
607
-
608
-	// Verifier si les mises a jour sont pertinentes, datees, en conflit etc
609
-	$conflits = controler_md5($champs, $_POST, $type, $id, $serveur, isset($options['prefix']) ? $options['prefix'] : 'ctr_');
610
-
611
-	return $conflits;
539
+    include_spip('inc/filtres');
540
+
541
+    $table_objet = table_objet($type);
542
+    $spip_table_objet = table_objet_sql($type);
543
+    $trouver_table = charger_fonction('trouver_table', 'base');
544
+    $desc = $trouver_table($table_objet, $serveur);
545
+
546
+    // Appels incomplets (sans $c)
547
+    if (!is_array($c)) {
548
+        foreach ($desc['field'] as $champ => $ignore) {
549
+            if (_request($champ)) {
550
+                $c[$champ] = _request($champ);
551
+            }
552
+        }
553
+    }
554
+
555
+    // Securite : certaines variables ne sont jamais acceptees ici
556
+    // car elles ne relevent pas de autoriser(article, modifier) ;
557
+    // il faut passer par instituer_XX()
558
+    // TODO: faut-il passer ces variables interdites
559
+    // dans un fichier de description separe ?
560
+    unset($c['statut']);
561
+    unset($c['id_parent']);
562
+    unset($c['id_rubrique']);
563
+    unset($c['id_secteur']);
564
+
565
+    // Gerer les champs non vides
566
+    if (isset($options['nonvide']) and is_array($options['nonvide'])) {
567
+        foreach ($options['nonvide'] as $champ => $sinon) {
568
+            if ($c[$champ] === '') {
569
+                $c[$champ] = $sinon;
570
+            }
571
+        }
572
+    }
573
+
574
+    // N'accepter que les champs qui existent
575
+    // [TODO] ici aussi on peut valider les contenus en fonction du type
576
+    $champs = array();
577
+    foreach ($desc['field'] as $champ => $ignore) {
578
+        if (isset($c[$champ])) {
579
+            $champs[$champ] = $c[$champ];
580
+        }
581
+    }
582
+
583
+    // Nettoyer les valeurs
584
+    $champs = array_map('corriger_caracteres', $champs);
585
+
586
+    // Envoyer aux plugins
587
+    $champs = pipeline(
588
+        'pre_edition',
589
+        array(
590
+            'args' => array(
591
+                'table' => $spip_table_objet, // compatibilite
592
+                'table_objet' => $table_objet,
593
+                'spip_table_objet' => $spip_table_objet,
594
+                'type' => $type,
595
+                'id_objet' => $id,
596
+                'champs' => isset($options['champs']) ? $options['champs'] : array(), // [doc] c'est quoi ?
597
+                'action' => 'controler',
598
+                'serveur' => $serveur,
599
+            ),
600
+            'data' => $champs
601
+        )
602
+    );
603
+
604
+    if (!$champs) {
605
+        return false;
606
+    }
607
+
608
+    // Verifier si les mises a jour sont pertinentes, datees, en conflit etc
609
+    $conflits = controler_md5($champs, $_POST, $type, $id, $serveur, isset($options['prefix']) ? $options['prefix'] : 'ctr_');
610
+
611
+    return $conflits;
612 612
 }
613 613
 
614 614
 
@@ -638,63 +638,63 @@  discard block
 block discarded – undo
638 638
  *     - post : le contenu posté
639 639
  **/
640 640
 function controler_md5(&$champs, $ctr, $type, $id, $serveur, $prefix = 'ctr_') {
641
-	$spip_table_objet = table_objet_sql($type);
642
-	$id_table_objet = id_table_objet($type);
643
-
644
-	// Controle des MD5 envoyes
645
-	// On elimine les donnees non modifiees par le formulaire (mais
646
-	// potentiellement modifiees entre temps par un autre utilisateur)
647
-	foreach ($champs as $key => $val) {
648
-		if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
649
-			if (is_scalar($val) and $m == md5($val)) {
650
-				unset($champs[$key]);
651
-			}
652
-		}
653
-	}
654
-	if (!$champs) {
655
-		return;
656
-	}
657
-
658
-	// On veut savoir si notre modif va avoir un impact
659
-	// par rapport aux donnees contenues dans la base
660
-	// (qui peuvent etre differentes de celles ayant servi a calculer le ctr)
661
-	$s = sql_fetsel(array_keys($champs), $spip_table_objet, "$id_table_objet=$id", $serveur);
662
-	$intact = true;
663
-	foreach ($champs as $ch => $val) {
664
-		$intact &= ($s[$ch] == $val);
665
-	}
666
-	if ($intact) {
667
-		return;
668
-	}
669
-
670
-	// Detection de conflits :
671
-	// On verifie si notre modif ne provient pas d'un formulaire
672
-	// genere a partir de donnees modifiees dans l'intervalle ; ici
673
-	// on compare a ce qui est dans la base, et on bloque en cas
674
-	// de conflit.
675
-	$ctrh = $ctrq = $conflits = array();
676
-	foreach (array_keys($champs) as $key) {
677
-		if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
678
-			$ctrh[$key] = $m;
679
-			$ctrq[] = $key;
680
-		}
681
-	}
682
-	if ($ctrq) {
683
-		$ctrq = sql_fetsel($ctrq, $spip_table_objet, "$id_table_objet=$id", $serveur);
684
-		foreach ($ctrh as $key => $m) {
685
-			if ($m != md5($ctrq[$key])
686
-				and $champs[$key] !== $ctrq[$key]
687
-			) {
688
-				$conflits[$key] = array(
689
-					'base' => $ctrq[$key],
690
-					'post' => $champs[$key]
691
-				);
692
-				unset($champs[$key]); # stocker quand meme les modifs ?
693
-			}
694
-		}
695
-	}
696
-
697
-	return $conflits;
641
+    $spip_table_objet = table_objet_sql($type);
642
+    $id_table_objet = id_table_objet($type);
643
+
644
+    // Controle des MD5 envoyes
645
+    // On elimine les donnees non modifiees par le formulaire (mais
646
+    // potentiellement modifiees entre temps par un autre utilisateur)
647
+    foreach ($champs as $key => $val) {
648
+        if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
649
+            if (is_scalar($val) and $m == md5($val)) {
650
+                unset($champs[$key]);
651
+            }
652
+        }
653
+    }
654
+    if (!$champs) {
655
+        return;
656
+    }
657
+
658
+    // On veut savoir si notre modif va avoir un impact
659
+    // par rapport aux donnees contenues dans la base
660
+    // (qui peuvent etre differentes de celles ayant servi a calculer le ctr)
661
+    $s = sql_fetsel(array_keys($champs), $spip_table_objet, "$id_table_objet=$id", $serveur);
662
+    $intact = true;
663
+    foreach ($champs as $ch => $val) {
664
+        $intact &= ($s[$ch] == $val);
665
+    }
666
+    if ($intact) {
667
+        return;
668
+    }
669
+
670
+    // Detection de conflits :
671
+    // On verifie si notre modif ne provient pas d'un formulaire
672
+    // genere a partir de donnees modifiees dans l'intervalle ; ici
673
+    // on compare a ce qui est dans la base, et on bloque en cas
674
+    // de conflit.
675
+    $ctrh = $ctrq = $conflits = array();
676
+    foreach (array_keys($champs) as $key) {
677
+        if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
678
+            $ctrh[$key] = $m;
679
+            $ctrq[] = $key;
680
+        }
681
+    }
682
+    if ($ctrq) {
683
+        $ctrq = sql_fetsel($ctrq, $spip_table_objet, "$id_table_objet=$id", $serveur);
684
+        foreach ($ctrh as $key => $m) {
685
+            if ($m != md5($ctrq[$key])
686
+                and $champs[$key] !== $ctrq[$key]
687
+            ) {
688
+                $conflits[$key] = array(
689
+                    'base' => $ctrq[$key],
690
+                    'post' => $champs[$key]
691
+                );
692
+                unset($champs[$key]); # stocker quand meme les modifs ?
693
+            }
694
+        }
695
+    }
696
+
697
+    return $conflits;
698 698
 }
699 699
 
700 700
 /**
@@ -706,11 +706,11 @@  discard block
 block discarded – undo
706 706
  * @return string
707 707
  */
708 708
 function display_conflit_champ($x) {
709
-	if (strstr($x, "\n") or strlen($x) > 80) {
710
-		return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
711
-	} else {
712
-		return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
713
-	}
709
+    if (strstr($x, "\n") or strlen($x) > 80) {
710
+        return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
711
+    } else {
712
+        return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
713
+    }
714 714
 }
715 715
 
716 716
 /**
@@ -728,57 +728,57 @@  discard block
 block discarded – undo
728 728
  * @return string
729 729
  */
730 730
 function signaler_conflits_edition($conflits, $redirect = '') {
731
-	include_spip('inc/minipres');
732
-	include_spip('inc/revisions');
733
-	include_spip('afficher_diff/champ');
734
-	include_spip('inc/suivi_versions');
735
-	include_spip('inc/diff');
736
-	$diffs = array();
737
-	foreach ($conflits as $champ => $a) {
738
-		// probleme de stockage ou conflit d'edition ?
739
-		$base = isset($a['save']) ? $a['save'] : $a['base'];
740
-
741
-		$diff = new Diff(new DiffTexte);
742
-		$n = preparer_diff($a['post']);
743
-		$o = preparer_diff($base);
744
-		$d = propre_diff(afficher_para_modifies(afficher_diff($diff->comparer($n, $o))));
745
-
746
-		$titre = isset($a['save']) ? _L(
747
-			'Echec lors de l\'enregistrement du champ @champ@',
748
-			array('champ' => $champ)
749
-		) : $champ;
750
-
751
-		$diffs[] = "<h2>$titre</h2>\n"
752
-			. '<h3>' . _T('info_conflit_edition_differences') . "</h3>\n"
753
-			. "<div style='max-height:8em; overflow: auto; width:99%;'>" . $d . "</div>\n"
754
-			. '<h4>' . _T('info_conflit_edition_votre_version') . '</h4>'
755
-			. display_conflit_champ($a['post'])
756
-			. '<h4>' . _T('info_conflit_edition_version_enregistree') . '</h4>'
757
-			. display_conflit_champ($base);
758
-	}
759
-
760
-	if ($redirect) {
761
-		$id = uniqid(rand());
762
-		$redirect = "<form action='$redirect' method='get'
731
+    include_spip('inc/minipres');
732
+    include_spip('inc/revisions');
733
+    include_spip('afficher_diff/champ');
734
+    include_spip('inc/suivi_versions');
735
+    include_spip('inc/diff');
736
+    $diffs = array();
737
+    foreach ($conflits as $champ => $a) {
738
+        // probleme de stockage ou conflit d'edition ?
739
+        $base = isset($a['save']) ? $a['save'] : $a['base'];
740
+
741
+        $diff = new Diff(new DiffTexte);
742
+        $n = preparer_diff($a['post']);
743
+        $o = preparer_diff($base);
744
+        $d = propre_diff(afficher_para_modifies(afficher_diff($diff->comparer($n, $o))));
745
+
746
+        $titre = isset($a['save']) ? _L(
747
+            'Echec lors de l\'enregistrement du champ @champ@',
748
+            array('champ' => $champ)
749
+        ) : $champ;
750
+
751
+        $diffs[] = "<h2>$titre</h2>\n"
752
+            . '<h3>' . _T('info_conflit_edition_differences') . "</h3>\n"
753
+            . "<div style='max-height:8em; overflow: auto; width:99%;'>" . $d . "</div>\n"
754
+            . '<h4>' . _T('info_conflit_edition_votre_version') . '</h4>'
755
+            . display_conflit_champ($a['post'])
756
+            . '<h4>' . _T('info_conflit_edition_version_enregistree') . '</h4>'
757
+            . display_conflit_champ($base);
758
+    }
759
+
760
+    if ($redirect) {
761
+        $id = uniqid(rand());
762
+        $redirect = "<form action='$redirect' method='get'
763 763
 			id='$id'
764 764
 			style='float:" . $GLOBALS['spip_lang_right'] . "; margin-top:2em;'>\n"
765
-			. form_hidden($redirect)
766
-			. "<input type='submit' value='" . _T('icone_retour') . "' />
765
+            . form_hidden($redirect)
766
+            . "<input type='submit' value='" . _T('icone_retour') . "' />
767 767
 		</form>\n";
768 768
 
769
-		// pour les documents, on est probablement en ajax : il faut ajaxer
770
-		if (_AJAX) {
771
-			$redirect .= '<script type="text/javascript">'
772
-				. 'setTimeout(function(){$("#' . $id . '")
769
+        // pour les documents, on est probablement en ajax : il faut ajaxer
770
+        if (_AJAX) {
771
+            $redirect .= '<script type="text/javascript">'
772
+                . 'setTimeout(function(){$("#' . $id . '")
773 773
 			.ajaxForm({target:$("#' . $id . '").parent()});
774 774
 			}, 200);'
775
-				. "</script>\n";
776
-		}
777
-	}
775
+                . "</script>\n";
776
+        }
777
+    }
778 778
 
779
-	echo minipres(
780
-		_T('titre_conflit_edition'),
781
-		'<style>
779
+    echo minipres(
780
+        _T('titre_conflit_edition'),
781
+        '<style>
782 782
 .diff-para-deplace { background: #e8e8ff; }
783 783
 .diff-para-ajoute { background: #d0ffc0; color: #000; }
784 784
 .diff-para-supprime { background: #ffd0c0; color: #904040; text-decoration: line-through; }
@@ -789,12 +789,12 @@  discard block
 block discarded – undo
789 789
 .diff-para-deplace .diff-supprime { background: #ffb8b8; border: 1px solid #808080; }
790 790
 .diff-para-deplace .diff-deplace { background: #b8b8ff; border: 1px solid #808080; }
791 791
 </style>'
792
-		. '<p>' . _T('info_conflit_edition_avis_non_sauvegarde') . '</p>'
793
-		. '<p>' . _T('texte_conflit_edition_correction') . '</p>'
794
-		. "<div style='text-align:" . $GLOBALS['spip_lang_left'] . ";'>"
795
-		. join("\n", $diffs)
796
-		. "</div>\n"
797
-
798
-		. $redirect
799
-	);
792
+        . '<p>' . _T('info_conflit_edition_avis_non_sauvegarde') . '</p>'
793
+        . '<p>' . _T('texte_conflit_edition_correction') . '</p>'
794
+        . "<div style='text-align:" . $GLOBALS['spip_lang_left'] . ";'>"
795
+        . join("\n", $diffs)
796
+        . "</div>\n"
797
+
798
+        . $redirect
799
+    );
800 800
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -38 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 		$res['message_ok'] = _T('info_modification_enregistree');
101 101
 		if ($retour) {
102 102
 			if (strncmp($retour, 'javascript:', 11) == 0) {
103
-				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/' . substr($retour, 11) . '/*]]>*/</script>';
103
+				$res['message_ok'] .= '<script type="text/javascript">/*<![CDATA[*/'.substr($retour, 11).'/*]]>*/</script>';
104 104
 				$res['editable'] = true;
105 105
 			} else {
106 106
 				$res['redirect'] = parametre_url($retour, $id_table_objet, $id);
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 				if (!isset($erreurs[$champ])) {
141 141
 					$erreurs[$champ] = '';
142 142
 				}
143
-				$erreurs[$champ] .= _T('alerte_modif_info_concourante') . "<br /><textarea readonly='readonly' class='forml'>" . entites_html($conflit['base']) . '</textarea>';
143
+				$erreurs[$champ] .= _T('alerte_modif_info_concourante')."<br /><textarea readonly='readonly' class='forml'>".entites_html($conflit['base']).'</textarea>';
144 144
 			}
145 145
 		}
146 146
 	}
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 	// on accepte pas une fonction de config inconnue si elle vient d'un modele
216 216
 	if ($config_fonc
217 217
 	  and !in_array($config_fonc, ['articles_edit_config', 'rubriques_edit_config', 'auteurs_edit_config'])
218
-	  and $config_fonc !== $table_objet . '_edit_config') {
218
+	  and $config_fonc !== $table_objet.'_edit_config') {
219 219
 		if ($args = test_formulaire_inclus_par_modele()
220 220
 		  and in_array($config_fonc, $args)) {
221 221
 			$config_fonc = '';
@@ -227,12 +227,12 @@  discard block
 block discarded – undo
227 227
 	// Appel direct dans un squelette
228 228
 	if (!$row) {
229 229
 		if (!$new or $lier_trad) {
230
-			if ($select = charger_fonction('precharger_' . $type, 'inc', true)) {
230
+			if ($select = charger_fonction('precharger_'.$type, 'inc', true)) {
231 231
 				$row = $select($id, $id_parent, $lier_trad);
232 232
 				// si on a une fonction precharger, elle pu faire un reglage de langue
233 233
 				$lang_default = (!empty($row['lang']) ? $row['lang'] : null);
234 234
 			} else {
235
-				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet . '=' . intval($id));
235
+				$row = sql_fetsel('*', $table_objet_sql, $id_table_objet.'='.intval($id));
236 236
 			}
237 237
 			if (!$new) {
238 238
 				$md5 = controles_md5($row);
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 	if ($config_fonc) {
282 282
 		$contexte['config'] = $config = $config_fonc($contexte);
283 283
 		if (!$lang_default) {
284
-			$lang_default = $config['langue'] ?? session_get('lang') ;
284
+			$lang_default = $config['langue'] ?? session_get('lang');
285 285
 		}
286 286
 	}
287 287
 	$config = $config + array(
@@ -305,13 +305,12 @@  discard block
 block discarded – undo
305 305
 		unset($contexte['lang']);
306 306
 	}
307 307
 
308
-	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n" .
309
-		(!$lier_trad ? '' :
310
-			("\n<input type='hidden' name='lier_trad' value='" .
311
-				$lier_trad .
312
-				"' />" .
313
-				"\n<input type='hidden' name='changer_lang' value='" .
314
-				$lang_default .
308
+	$contexte['_hidden'] = "<input type='hidden' name='editer_$type' value='oui' />\n".
309
+		(!$lier_trad ? '' : ("\n<input type='hidden' name='lier_trad' value='".
310
+				$lier_trad.
311
+				"' />".
312
+				"\n<input type='hidden' name='changer_lang' value='".
313
+				$lang_default.
315 314
 				"' />"))
316 315
 		. $hidden
317 316
 		. (isset($md5) ? $md5 : '');
@@ -325,8 +324,8 @@  discard block
 block discarded – undo
325 324
 	$contexte['_action'] = array("editer_$type", $id);
326 325
 
327 326
 	// et in fine placer l'autorisation
328
-	if (intval($id)){
329
-		if (!autoriser('modifier', $type, intval($id))){
327
+	if (intval($id)) {
328
+		if (!autoriser('modifier', $type, intval($id))) {
330 329
 			$valeurs['editable'] = '';
331 330
 		}
332 331
 	}
@@ -350,14 +349,14 @@  discard block
 block discarded – undo
350 349
 	$aider = charger_fonction('aider', 'inc');
351 350
 	if (strlen($texte) > 28 * 1024) {
352 351
 		$texte = str_replace("\r\n", "\n", $texte);
353
-		$pos = strpos($texte, "\n\n", 28 * 1024);  // coupe para > 28 ko
352
+		$pos = strpos($texte, "\n\n", 28 * 1024); // coupe para > 28 ko
354 353
 		if ($pos > 0 and $pos < 32 * 1024) {
355
-			$debut = substr($texte, 0, $pos) . "\n\n<!--SPIP-->\n";
354
+			$debut = substr($texte, 0, $pos)."\n\n<!--SPIP-->\n";
356 355
 			$suite = substr($texte, $pos + 2);
357 356
 		} else {
358
-			$pos = strpos($texte, ' ', 28 * 1024);  // sinon coupe espace
357
+			$pos = strpos($texte, ' ', 28 * 1024); // sinon coupe espace
359 358
 			if (!($pos > 0 and $pos < 32 * 1024)) {
360
-				$pos = 28 * 1024;  // au pire (pas d'espace trouv'e)
359
+				$pos = 28 * 1024; // au pire (pas d'espace trouv'e)
361 360
 				$decalage = 0; // si y'a pas d'espace, il ne faut pas perdre le caract`ere
362 361
 			} else {
363 362
 				$decalage = 1;
@@ -387,13 +386,13 @@  discard block
 block discarded – undo
387 386
 	}
388 387
 
389 388
 	include_spip('inc/barre');
390
-	$textes_supplement = "<br /><span style='color: red'>" . _T('info_texte_long') . "</span>\n";
389
+	$textes_supplement = "<br /><span style='color: red'>"._T('info_texte_long')."</span>\n";
391 390
 	$nombre = 0;
392 391
 
393 392
 	while (strlen($texte) > 29 * 1024) {
394 393
 		$nombre++;
395 394
 		list($texte1, $texte) = coupe_trop_long($texte);
396
-		$textes_supplement .= '<br />' .
395
+		$textes_supplement .= '<br />'.
397 396
 			"<textarea id='texte$nombre' name='texte_plus[$nombre]'$att_text>$texte1</textarea>\n";
398 397
 	}
399 398
 
@@ -481,7 +480,7 @@  discard block
 block discarded – undo
481 480
 	$ctr = array();
482 481
 	foreach ($data as $key => $val) {
483 482
 		$m = md5($val);
484
-		$k = $prefixe . $key;
483
+		$k = $prefixe.$key;
485 484
 
486 485
 		switch ($format) {
487 486
 			case 'html':
@@ -494,7 +493,7 @@  discard block
 block discarded – undo
494 493
 	}
495 494
 
496 495
 	if ($format == 'html') {
497
-		return "\n\n<!-- controles md5 -->\n" . join("\n", $ctr) . "\n\n";
496
+		return "\n\n<!-- controles md5 -->\n".join("\n", $ctr)."\n\n";
498 497
 	} else {
499 498
 		return $ctr;
500 499
 	}
@@ -645,7 +644,7 @@  discard block
 block discarded – undo
645 644
 	// On elimine les donnees non modifiees par le formulaire (mais
646 645
 	// potentiellement modifiees entre temps par un autre utilisateur)
647 646
 	foreach ($champs as $key => $val) {
648
-		if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
647
+		if (isset($ctr[$prefix.$key]) and $m = $ctr[$prefix.$key]) {
649 648
 			if (is_scalar($val) and $m == md5($val)) {
650 649
 				unset($champs[$key]);
651 650
 			}
@@ -674,7 +673,7 @@  discard block
 block discarded – undo
674 673
 	// de conflit.
675 674
 	$ctrh = $ctrq = $conflits = array();
676 675
 	foreach (array_keys($champs) as $key) {
677
-		if (isset($ctr[$prefix . $key]) and $m = $ctr[$prefix . $key]) {
676
+		if (isset($ctr[$prefix.$key]) and $m = $ctr[$prefix.$key]) {
678 677
 			$ctrh[$key] = $m;
679 678
 			$ctrq[] = $key;
680 679
 		}
@@ -707,9 +706,9 @@  discard block
 block discarded – undo
707 706
  */
708 707
 function display_conflit_champ($x) {
709 708
 	if (strstr($x, "\n") or strlen($x) > 80) {
710
-		return "<textarea style='width:99%; height:10em;'>" . entites_html($x) . "</textarea>\n";
709
+		return "<textarea style='width:99%; height:10em;'>".entites_html($x)."</textarea>\n";
711 710
 	} else {
712
-		return "<input type='text' size='40' style='width:99%' value=\"" . entites_html($x) . "\" />\n";
711
+		return "<input type='text' size='40' style='width:99%' value=\"".entites_html($x)."\" />\n";
713 712
 	}
714 713
 }
715 714
 
@@ -749,11 +748,11 @@  discard block
 block discarded – undo
749 748
 		) : $champ;
750 749
 
751 750
 		$diffs[] = "<h2>$titre</h2>\n"
752
-			. '<h3>' . _T('info_conflit_edition_differences') . "</h3>\n"
753
-			. "<div style='max-height:8em; overflow: auto; width:99%;'>" . $d . "</div>\n"
754
-			. '<h4>' . _T('info_conflit_edition_votre_version') . '</h4>'
751
+			. '<h3>'._T('info_conflit_edition_differences')."</h3>\n"
752
+			. "<div style='max-height:8em; overflow: auto; width:99%;'>".$d."</div>\n"
753
+			. '<h4>'._T('info_conflit_edition_votre_version').'</h4>'
755 754
 			. display_conflit_champ($a['post'])
756
-			. '<h4>' . _T('info_conflit_edition_version_enregistree') . '</h4>'
755
+			. '<h4>'._T('info_conflit_edition_version_enregistree').'</h4>'
757 756
 			. display_conflit_champ($base);
758 757
 	}
759 758
 
@@ -761,16 +760,16 @@  discard block
 block discarded – undo
761 760
 		$id = uniqid(rand());
762 761
 		$redirect = "<form action='$redirect' method='get'
763 762
 			id='$id'
764
-			style='float:" . $GLOBALS['spip_lang_right'] . "; margin-top:2em;'>\n"
763
+			style='float:".$GLOBALS['spip_lang_right']."; margin-top:2em;'>\n"
765 764
 			. form_hidden($redirect)
766
-			. "<input type='submit' value='" . _T('icone_retour') . "' />
765
+			. "<input type='submit' value='"._T('icone_retour')."' />
767 766
 		</form>\n";
768 767
 
769 768
 		// pour les documents, on est probablement en ajax : il faut ajaxer
770 769
 		if (_AJAX) {
771 770
 			$redirect .= '<script type="text/javascript">'
772
-				. 'setTimeout(function(){$("#' . $id . '")
773
-			.ajaxForm({target:$("#' . $id . '").parent()});
771
+				. 'setTimeout(function(){$("#'.$id.'")
772
+			.ajaxForm({target:$("#' . $id.'").parent()});
774 773
 			}, 200);'
775 774
 				. "</script>\n";
776 775
 		}
@@ -789,9 +788,9 @@  discard block
 block discarded – undo
789 788
 .diff-para-deplace .diff-supprime { background: #ffb8b8; border: 1px solid #808080; }
790 789
 .diff-para-deplace .diff-deplace { background: #b8b8ff; border: 1px solid #808080; }
791 790
 </style>'
792
-		. '<p>' . _T('info_conflit_edition_avis_non_sauvegarde') . '</p>'
793
-		. '<p>' . _T('texte_conflit_edition_correction') . '</p>'
794
-		. "<div style='text-align:" . $GLOBALS['spip_lang_left'] . ";'>"
791
+		. '<p>'._T('info_conflit_edition_avis_non_sauvegarde').'</p>'
792
+		. '<p>'._T('texte_conflit_edition_correction').'</p>'
793
+		. "<div style='text-align:".$GLOBALS['spip_lang_left'].";'>"
795 794
 		. join("\n", $diffs)
796 795
 		. "</div>\n"
797 796
 
Please login to merge, or discard this patch.
ecrire/inc/envoyer_mail.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -187,7 +187,7 @@
 block discarded – undo
187 187
  * @param string $to
188 188
  * @param string $texte
189 189
  * @param string $parts
190
- * @return array
190
+ * @return string[]
191 191
  */
192 192
 function mail_normaliser_headers($headers, $from, $to, $texte, $parts = '') {
193 193
 	$charset = $GLOBALS['meta']['charset'];
Please login to merge, or discard this patch.
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Mail
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 include_spip('inc/charsets');
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
  * @return string
33 33
  */
34 34
 function nettoyer_titre_email($titre) {
35
-	return str_replace("\n", ' ', nettoyer_caracteres_mail(textebrut(corriger_typo($titre))));
35
+    return str_replace("\n", ' ', nettoyer_caracteres_mail(textebrut(corriger_typo($titre))));
36 36
 }
37 37
 
38 38
 /**
@@ -48,23 +48,23 @@  discard block
 block discarded – undo
48 48
  */
49 49
 function nettoyer_caracteres_mail($t) {
50 50
 
51
-	$t = filtrer_entites($t);
51
+    $t = filtrer_entites($t);
52 52
 
53
-	if ($GLOBALS['meta']['charset'] <> 'utf-8') {
54
-		$t = str_replace(
55
-			array('&#8217;', '&#8220;', '&#8221;'),
56
-			array("'", '"', '"'),
57
-			$t
58
-		);
59
-	}
53
+    if ($GLOBALS['meta']['charset'] <> 'utf-8') {
54
+        $t = str_replace(
55
+            array('&#8217;', '&#8220;', '&#8221;'),
56
+            array("'", '"', '"'),
57
+            $t
58
+        );
59
+    }
60 60
 
61
-	$t = str_replace(
62
-		array('&mdash;', '&endash;'),
63
-		array('--', '-'),
64
-		$t
65
-	);
61
+    $t = str_replace(
62
+        array('&mdash;', '&endash;'),
63
+        array('--', '-'),
64
+        $t
65
+    );
66 66
 
67
-	return $t;
67
+    return $t;
68 68
 }
69 69
 
70 70
 /**
@@ -97,86 +97,86 @@  discard block
 block discarded – undo
97 97
  */
98 98
 function inc_envoyer_mail_dist($destinataire, $sujet, $corps, $from = '', $headers = '') {
99 99
 
100
-	if (!email_valide($destinataire)) {
101
-		return false;
102
-	}
103
-	if ($destinataire == _T('info_mail_fournisseur')) {
104
-		return false;
105
-	} // tres fort
106
-
107
-	// Fournir si possible un Message-Id: conforme au RFC1036,
108
-	// sinon SpamAssassin denoncera un MSGID_FROM_MTA_HEADER
109
-
110
-	$email_envoi = $GLOBALS['meta']['email_envoi'];
111
-	if (!email_valide($email_envoi)) {
112
-		spip_log('Meta email_envoi invalide. Le mail sera probablement vu comme spam.');
113
-		$email_envoi = $destinataire;
114
-	}
115
-
116
-	$parts = '';
117
-	if (is_array($corps)) {
118
-		$texte = $corps['texte'];
119
-		$from = (isset($corps['from']) ? $corps['from'] : $from);
120
-		$headers = (isset($corps['headers']) ? $corps['headers'] : $headers);
121
-		if (is_array($headers)) {
122
-			$headers = implode("\n", $headers);
123
-		}
124
-		if ($corps['pieces_jointes'] and function_exists('mail_embarquer_pieces_jointes')) {
125
-			$parts = mail_embarquer_pieces_jointes($corps['pieces_jointes']);
126
-		}
127
-	} else {
128
-		$texte = $corps;
129
-	}
130
-
131
-	if (!$from) {
132
-		$from = $email_envoi;
133
-	}
134
-
135
-	// ceci est la RegExp NO_REAL_NAME faisant hurler SpamAssassin
136
-	if (preg_match('/^["\s]*\<?\S+\@\S+\>?\s*$/', $from)) {
137
-		$from .= ' (' . str_replace(')', '', translitteration(str_replace('@', ' at ', $from))) . ')';
138
-	}
139
-
140
-	// nettoyer les &eacute; &#8217, &emdash; etc...
141
-	// les 'cliquer ici' etc sont a eviter;  voir:
142
-	// http://mta.org.ua/spamassassin-2.55/stuff/wiki.CustomRulesets/20050914/rules/french_rules.cf
143
-	$texte = nettoyer_caracteres_mail($texte);
144
-	$sujet = nettoyer_caracteres_mail($sujet);
145
-
146
-	// encoder le sujet si possible selon la RFC
147
-	if (init_mb_string()) {
148
-		# un bug de mb_string casse mb_encode_mimeheader si l'encoding interne
149
-		# est UTF-8 et le charset iso-8859-1 (constate php5-mac ; php4.3-debian)
150
-		$charset = $GLOBALS['meta']['charset'];
151
-		mb_internal_encoding($charset);
152
-		$sujet = mb_encode_mimeheader($sujet, $charset, 'Q', "\n");
153
-		mb_internal_encoding('utf-8');
154
-	}
155
-
156
-	if (function_exists('wordwrap') && (preg_match(',multipart/mixed,', $headers) == 0)) {
157
-		$texte = wordwrap($texte);
158
-	}
159
-
160
-	list($headers, $texte) = mail_normaliser_headers($headers, $from, $destinataire, $texte, $parts);
161
-
162
-	if (_OS_SERVEUR == 'windows') {
163
-		$texte = preg_replace("@\r*\n@", "\r\n", $texte);
164
-		$headers = preg_replace("@\r*\n@", "\r\n", $headers);
165
-		$sujet = preg_replace("@\r*\n@", "\r\n", $sujet);
166
-	}
167
-
168
-	spip_log("mail $destinataire\n$sujet\n$headers", 'mails');
169
-	// mode TEST : forcer l'email
170
-	if (defined('_TEST_EMAIL_DEST')) {
171
-		if (!_TEST_EMAIL_DEST) {
172
-			return false;
173
-		} else {
174
-			$texte = "Dest : $destinataire\r\n" . $texte;
175
-			$destinataire = _TEST_EMAIL_DEST;
176
-		}
177
-	}
178
-
179
-	return @mail($destinataire, $sujet, $texte, $headers);
100
+    if (!email_valide($destinataire)) {
101
+        return false;
102
+    }
103
+    if ($destinataire == _T('info_mail_fournisseur')) {
104
+        return false;
105
+    } // tres fort
106
+
107
+    // Fournir si possible un Message-Id: conforme au RFC1036,
108
+    // sinon SpamAssassin denoncera un MSGID_FROM_MTA_HEADER
109
+
110
+    $email_envoi = $GLOBALS['meta']['email_envoi'];
111
+    if (!email_valide($email_envoi)) {
112
+        spip_log('Meta email_envoi invalide. Le mail sera probablement vu comme spam.');
113
+        $email_envoi = $destinataire;
114
+    }
115
+
116
+    $parts = '';
117
+    if (is_array($corps)) {
118
+        $texte = $corps['texte'];
119
+        $from = (isset($corps['from']) ? $corps['from'] : $from);
120
+        $headers = (isset($corps['headers']) ? $corps['headers'] : $headers);
121
+        if (is_array($headers)) {
122
+            $headers = implode("\n", $headers);
123
+        }
124
+        if ($corps['pieces_jointes'] and function_exists('mail_embarquer_pieces_jointes')) {
125
+            $parts = mail_embarquer_pieces_jointes($corps['pieces_jointes']);
126
+        }
127
+    } else {
128
+        $texte = $corps;
129
+    }
130
+
131
+    if (!$from) {
132
+        $from = $email_envoi;
133
+    }
134
+
135
+    // ceci est la RegExp NO_REAL_NAME faisant hurler SpamAssassin
136
+    if (preg_match('/^["\s]*\<?\S+\@\S+\>?\s*$/', $from)) {
137
+        $from .= ' (' . str_replace(')', '', translitteration(str_replace('@', ' at ', $from))) . ')';
138
+    }
139
+
140
+    // nettoyer les &eacute; &#8217, &emdash; etc...
141
+    // les 'cliquer ici' etc sont a eviter;  voir:
142
+    // http://mta.org.ua/spamassassin-2.55/stuff/wiki.CustomRulesets/20050914/rules/french_rules.cf
143
+    $texte = nettoyer_caracteres_mail($texte);
144
+    $sujet = nettoyer_caracteres_mail($sujet);
145
+
146
+    // encoder le sujet si possible selon la RFC
147
+    if (init_mb_string()) {
148
+        # un bug de mb_string casse mb_encode_mimeheader si l'encoding interne
149
+        # est UTF-8 et le charset iso-8859-1 (constate php5-mac ; php4.3-debian)
150
+        $charset = $GLOBALS['meta']['charset'];
151
+        mb_internal_encoding($charset);
152
+        $sujet = mb_encode_mimeheader($sujet, $charset, 'Q', "\n");
153
+        mb_internal_encoding('utf-8');
154
+    }
155
+
156
+    if (function_exists('wordwrap') && (preg_match(',multipart/mixed,', $headers) == 0)) {
157
+        $texte = wordwrap($texte);
158
+    }
159
+
160
+    list($headers, $texte) = mail_normaliser_headers($headers, $from, $destinataire, $texte, $parts);
161
+
162
+    if (_OS_SERVEUR == 'windows') {
163
+        $texte = preg_replace("@\r*\n@", "\r\n", $texte);
164
+        $headers = preg_replace("@\r*\n@", "\r\n", $headers);
165
+        $sujet = preg_replace("@\r*\n@", "\r\n", $sujet);
166
+    }
167
+
168
+    spip_log("mail $destinataire\n$sujet\n$headers", 'mails');
169
+    // mode TEST : forcer l'email
170
+    if (defined('_TEST_EMAIL_DEST')) {
171
+        if (!_TEST_EMAIL_DEST) {
172
+            return false;
173
+        } else {
174
+            $texte = "Dest : $destinataire\r\n" . $texte;
175
+            $destinataire = _TEST_EMAIL_DEST;
176
+        }
177
+    }
178
+
179
+    return @mail($destinataire, $sujet, $texte, $headers);
180 180
 }
181 181
 
182 182
 /**
@@ -190,58 +190,58 @@  discard block
 block discarded – undo
190 190
  * @return array
191 191
  */
192 192
 function mail_normaliser_headers($headers, $from, $to, $texte, $parts = '') {
193
-	$charset = $GLOBALS['meta']['charset'];
194
-
195
-	// Ajouter le Content-Type et consort s'il n'y est pas deja
196
-	if (strpos($headers, 'Content-Type: ') === false) {
197
-		$type =
198
-			"Content-Type: text/plain;charset=\"$charset\";\n" .
199
-			"Content-Transfer-Encoding: 8bit\n";
200
-	} else {
201
-		$type = '';
202
-	}
203
-
204
-	// calculer un identifiant unique
205
-	// Marie Toto <[email protected]> => @toto.com
206
-	if (preg_match('/@[^\s>]+/', $from, $domain)) {
207
-		$domain = $domain[0];
208
-	}
209
-	else {
210
-		$domain = "@unknown-".md5($from).'.org';
211
-	}
212
-	$uniq = rand() . '_' . md5($to . $texte) . $domain;
213
-
214
-	// Si multi-part, s'en servir comme borne ...
215
-	if ($parts) {
216
-		$texte = "--$uniq\n$type\n" . $texte . "\n";
217
-		foreach ($parts as $part) {
218
-			$n = strlen($part[1]) . ($part[0] ? "\n" : '');
219
-			$e = join("\n", $part[0]);
220
-			$texte .= "\n--$uniq\nContent-Length: $n$e\n\n" . $part[1];
221
-		}
222
-		$texte .= "\n\n--$uniq--\n";
223
-		// Si boundary n'est pas entre guillemets,
224
-		// elle est comprise mais le charset est ignoree !
225
-		$type = "Content-Type: multipart/mixed; boundary=\"$uniq\"\n";
226
-	}
227
-
228
-	// .. et s'en servir pour plaire a SpamAssassin
229
-
230
-	$mid = 'Message-Id: <' . $uniq . '>';
231
-
232
-	// indispensable pour les sites qui collent d'office From: serveur-http
233
-	// sauf si deja mis par l'envoyeur
234
-	$rep = (strpos($headers, 'Reply-To:') !== false) ? '' : "Reply-To: $from\n";
235
-
236
-	// Nettoyer les en-tetes envoyees
237
-	// Ajouter le \n final
238
-	if (strlen($headers = trim($headers))) {
239
-		$headers .= "\n";
240
-	}
241
-
242
-	// Et mentionner l'indeboulonable nomenclature ratee
243
-
244
-	$headers .= "From: $from\n$type$rep$mid\nMIME-Version: 1.0\n";
245
-
246
-	return array($headers, $texte);
193
+    $charset = $GLOBALS['meta']['charset'];
194
+
195
+    // Ajouter le Content-Type et consort s'il n'y est pas deja
196
+    if (strpos($headers, 'Content-Type: ') === false) {
197
+        $type =
198
+            "Content-Type: text/plain;charset=\"$charset\";\n" .
199
+            "Content-Transfer-Encoding: 8bit\n";
200
+    } else {
201
+        $type = '';
202
+    }
203
+
204
+    // calculer un identifiant unique
205
+    // Marie Toto <[email protected]> => @toto.com
206
+    if (preg_match('/@[^\s>]+/', $from, $domain)) {
207
+        $domain = $domain[0];
208
+    }
209
+    else {
210
+        $domain = "@unknown-".md5($from).'.org';
211
+    }
212
+    $uniq = rand() . '_' . md5($to . $texte) . $domain;
213
+
214
+    // Si multi-part, s'en servir comme borne ...
215
+    if ($parts) {
216
+        $texte = "--$uniq\n$type\n" . $texte . "\n";
217
+        foreach ($parts as $part) {
218
+            $n = strlen($part[1]) . ($part[0] ? "\n" : '');
219
+            $e = join("\n", $part[0]);
220
+            $texte .= "\n--$uniq\nContent-Length: $n$e\n\n" . $part[1];
221
+        }
222
+        $texte .= "\n\n--$uniq--\n";
223
+        // Si boundary n'est pas entre guillemets,
224
+        // elle est comprise mais le charset est ignoree !
225
+        $type = "Content-Type: multipart/mixed; boundary=\"$uniq\"\n";
226
+    }
227
+
228
+    // .. et s'en servir pour plaire a SpamAssassin
229
+
230
+    $mid = 'Message-Id: <' . $uniq . '>';
231
+
232
+    // indispensable pour les sites qui collent d'office From: serveur-http
233
+    // sauf si deja mis par l'envoyeur
234
+    $rep = (strpos($headers, 'Reply-To:') !== false) ? '' : "Reply-To: $from\n";
235
+
236
+    // Nettoyer les en-tetes envoyees
237
+    // Ajouter le \n final
238
+    if (strlen($headers = trim($headers))) {
239
+        $headers .= "\n";
240
+    }
241
+
242
+    // Et mentionner l'indeboulonable nomenclature ratee
243
+
244
+    $headers .= "From: $from\n$type$rep$mid\nMIME-Version: 1.0\n";
245
+
246
+    return array($headers, $texte);
247 247
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 
135 135
 	// ceci est la RegExp NO_REAL_NAME faisant hurler SpamAssassin
136 136
 	if (preg_match('/^["\s]*\<?\S+\@\S+\>?\s*$/', $from)) {
137
-		$from .= ' (' . str_replace(')', '', translitteration(str_replace('@', ' at ', $from))) . ')';
137
+		$from .= ' ('.str_replace(')', '', translitteration(str_replace('@', ' at ', $from))).')';
138 138
 	}
139 139
 
140 140
 	// nettoyer les &eacute; &#8217, &emdash; etc...
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		if (!_TEST_EMAIL_DEST) {
172 172
 			return false;
173 173
 		} else {
174
-			$texte = "Dest : $destinataire\r\n" . $texte;
174
+			$texte = "Dest : $destinataire\r\n".$texte;
175 175
 			$destinataire = _TEST_EMAIL_DEST;
176 176
 		}
177 177
 	}
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	// Ajouter le Content-Type et consort s'il n'y est pas deja
196 196
 	if (strpos($headers, 'Content-Type: ') === false) {
197 197
 		$type =
198
-			"Content-Type: text/plain;charset=\"$charset\";\n" .
198
+			"Content-Type: text/plain;charset=\"$charset\";\n".
199 199
 			"Content-Transfer-Encoding: 8bit\n";
200 200
 	} else {
201 201
 		$type = '';
@@ -209,15 +209,15 @@  discard block
 block discarded – undo
209 209
 	else {
210 210
 		$domain = "@unknown-".md5($from).'.org';
211 211
 	}
212
-	$uniq = rand() . '_' . md5($to . $texte) . $domain;
212
+	$uniq = rand().'_'.md5($to.$texte).$domain;
213 213
 
214 214
 	// Si multi-part, s'en servir comme borne ...
215 215
 	if ($parts) {
216
-		$texte = "--$uniq\n$type\n" . $texte . "\n";
216
+		$texte = "--$uniq\n$type\n".$texte."\n";
217 217
 		foreach ($parts as $part) {
218
-			$n = strlen($part[1]) . ($part[0] ? "\n" : '');
218
+			$n = strlen($part[1]).($part[0] ? "\n" : '');
219 219
 			$e = join("\n", $part[0]);
220
-			$texte .= "\n--$uniq\nContent-Length: $n$e\n\n" . $part[1];
220
+			$texte .= "\n--$uniq\nContent-Length: $n$e\n\n".$part[1];
221 221
 		}
222 222
 		$texte .= "\n\n--$uniq--\n";
223 223
 		// Si boundary n'est pas entre guillemets,
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 
228 228
 	// .. et s'en servir pour plaire a SpamAssassin
229 229
 
230
-	$mid = 'Message-Id: <' . $uniq . '>';
230
+	$mid = 'Message-Id: <'.$uniq.'>';
231 231
 
232 232
 	// indispensable pour les sites qui collent d'office From: serveur-http
233 233
 	// sauf si deja mis par l'envoyeur
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -205,8 +205,7 @@
 block discarded – undo
205 205
 	// Marie Toto <[email protected]> => @toto.com
206 206
 	if (preg_match('/@[^\s>]+/', $from, $domain)) {
207 207
 		$domain = $domain[0];
208
-	}
209
-	else {
208
+	} else {
210 209
 		$domain = "@unknown-".md5($from).'.org';
211 210
 	}
212 211
 	$uniq = rand() . '_' . md5($to . $texte) . $domain;
Please login to merge, or discard this patch.
ecrire/inc/plugin.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -623,11 +623,11 @@
 block discarded – undo
623 623
  * 
624 624
  * @param $liste
625 625
  *    Liste de description des plugins
626
- * @param $nom
626
+ * @param string $nom
627 627
  *    Le plugin donc on cherche la presence
628 628
  * @param $intervalle
629 629
  *    L'éventuelle intervalle de compatibilité de la dépendance. ex: [1.1.0;]
630
- * @param $balise
630
+ * @param string $balise
631 631
  *    Permet de définir si on teste un utilise ou un nécessite
632 632
  * @return string.
633 633
  *    Vide si ok,
Please login to merge, or discard this patch.
Braces   +7 added lines, -9 removed lines patch added patch discarded remove patch
@@ -555,11 +555,9 @@  discard block
 block discarded – undo
555 555
 		if (!isset($msg[$p])) {
556 556
 			if (isset($resume['erreur']) and $resume['erreur']) {
557 557
 				$msg[$p] = array($resume['erreur']);
558
-			}
559
-			elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
558
+			} elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
560 559
 				$msg[$p] = array(plugin_message_incompatibilite($k['compatibilite'], $GLOBALS['spip_version_branche'], 'SPIP', 'necessite'));
561
-			}
562
-			elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
560
+			} elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
563 561
 				$msg[$p] = plugin_necessite($k['utilise'], $liste, 'utilise');
564 562
 			}
565 563
 		} else {
@@ -942,8 +940,7 @@  discard block
 block discarded – undo
942 940
 					if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
943 941
 						$chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
944 942
 					}
945
-				}
946
-				else{
943
+				} else{
947 944
 					foreach ($info['chemin'] as $chemin) {
948 945
 						if (!isset($chemin['version']) or plugin_version_compatible($chemin['version'],
949 946
 								$GLOBALS['spip_version_branche'], 'spip')
@@ -1166,10 +1163,12 @@  discard block
 block discarded – undo
1166 1163
 					}
1167 1164
 					$nom = $nomlower;
1168 1165
 					// une action vide est une declaration qui ne doit pas etre compilee !
1169
-					if (!isset($GLOBALS['spip_pipeline'][$nom])) // creer le pipeline eventuel
1166
+					if (!isset($GLOBALS['spip_pipeline'][$nom])) {
1167
+					    // creer le pipeline eventuel
1170 1168
 					{
1171 1169
 						$GLOBALS['spip_pipeline'][$nom] = "";
1172 1170
 					}
1171
+					}
1173 1172
 					if ($action) {
1174 1173
 						if (strpos($GLOBALS['spip_pipeline'][$nom], "|$prefix$action") === false) {
1175 1174
 							$GLOBALS['spip_pipeline'][$nom] = preg_replace(",(\|\||$),", "|$prefix$action\\1",
@@ -1430,8 +1429,7 @@  discard block
 block discarded – undo
1430 1429
 	if (file_exists($nom)) {
1431 1430
 		if (substr($nom, -4) == '.php') {
1432 1431
 			$fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1433
-		}
1434
-		else {
1432
+		} else {
1435 1433
 			$fichier_tmp = $nom . '.tmp';
1436 1434
 		}
1437 1435
 		file_put_contents($fichier_tmp, $contenu);
Please login to merge, or discard this patch.
Indentation   +946 added lines, -946 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  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
 /** l'adresse du repertoire de telechargement et de decompactage des plugins */
24 24
 if (!defined('_DIR_PLUGINS_AUTO')) {
25
-	define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS . 'auto/');
25
+    define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS . 'auto/');
26 26
 }
27 27
 
28 28
 #include_spip('inc/texte'); // ????? Appelle public/parametrer trop tot avant la reconstruction du chemin des plugins.
@@ -47,26 +47,26 @@  discard block
 block discarded – undo
47 47
  * @return array
48 48
 **/
49 49
 function liste_plugin_files($dir_plugins = null) {
50
-	static $plugin_files = array();
51
-	if (is_null($dir_plugins)) {
52
-		$dir_plugins = _DIR_PLUGINS;
53
-	}
54
-	if (!isset($plugin_files[$dir_plugins])
55
-		or count($plugin_files[$dir_plugins]) == 0
56
-	) {
57
-		$plugin_files[$dir_plugins] = array();
58
-		foreach (fast_find_plugin_dirs($dir_plugins) as $plugin) {
59
-			$plugin_files[$dir_plugins][] = substr($plugin, strlen($dir_plugins));
60
-		}
61
-
62
-		sort($plugin_files[$dir_plugins]);
63
-		// et on lit le XML de tous les plugins pour le mettre en cache
64
-		// et en profiter pour nettoyer ceux qui n'existent plus du cache
65
-		$get_infos = charger_fonction('get_infos', 'plugins');
66
-		$get_infos($plugin_files[$dir_plugins], false, $dir_plugins, true);
67
-	}
68
-
69
-	return $plugin_files[$dir_plugins];
50
+    static $plugin_files = array();
51
+    if (is_null($dir_plugins)) {
52
+        $dir_plugins = _DIR_PLUGINS;
53
+    }
54
+    if (!isset($plugin_files[$dir_plugins])
55
+        or count($plugin_files[$dir_plugins]) == 0
56
+    ) {
57
+        $plugin_files[$dir_plugins] = array();
58
+        foreach (fast_find_plugin_dirs($dir_plugins) as $plugin) {
59
+            $plugin_files[$dir_plugins][] = substr($plugin, strlen($dir_plugins));
60
+        }
61
+
62
+        sort($plugin_files[$dir_plugins]);
63
+        // et on lit le XML de tous les plugins pour le mettre en cache
64
+        // et en profiter pour nettoyer ceux qui n'existent plus du cache
65
+        $get_infos = charger_fonction('get_infos', 'plugins');
66
+        $get_infos($plugin_files[$dir_plugins], false, $dir_plugins, true);
67
+    }
68
+
69
+    return $plugin_files[$dir_plugins];
70 70
 }
71 71
 
72 72
 /**
@@ -82,44 +82,44 @@  discard block
 block discarded – undo
82 82
  *     Liste complète des répeertoires
83 83
 **/
84 84
 function fast_find_plugin_dirs($dir, $max_prof = 100) {
85
-	$fichiers = array();
86
-	// revenir au repertoire racine si on a recu dossier/truc
87
-	// pour regarder dossier/truc/ ne pas oublier le / final
88
-	$dir = preg_replace(',/[^/]*$,', '', $dir);
89
-	if ($dir == '') {
90
-		$dir = '.';
91
-	}
92
-
93
-	if (!is_dir($dir)) {
94
-		return $fichiers;
95
-	}
96
-	if (is_plugin_dir($dir, '')) {
97
-		$fichiers[] = $dir;
98
-
99
-		return $fichiers;
100
-	}
101
-	if ($max_prof <= 0) {
102
-		return $fichiers;
103
-	}
104
-
105
-	$subdirs = array();
106
-	if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
107
-		while (($f = readdir($d)) !== false) {
108
-			if ($f[0] != '.' # ignorer . .. .svn etc
109
-				and $f != 'CVS'
110
-				and is_dir($f = "$dir/$f")
111
-			) {
112
-				$subdirs[] = $f;
113
-			}
114
-		}
115
-		closedir($d);
116
-	}
117
-
118
-	foreach ($subdirs as $d) {
119
-		$fichiers = array_merge($fichiers, fast_find_plugin_dirs("$d/", $max_prof - 1));
120
-	}
121
-
122
-	return $fichiers;
85
+    $fichiers = array();
86
+    // revenir au repertoire racine si on a recu dossier/truc
87
+    // pour regarder dossier/truc/ ne pas oublier le / final
88
+    $dir = preg_replace(',/[^/]*$,', '', $dir);
89
+    if ($dir == '') {
90
+        $dir = '.';
91
+    }
92
+
93
+    if (!is_dir($dir)) {
94
+        return $fichiers;
95
+    }
96
+    if (is_plugin_dir($dir, '')) {
97
+        $fichiers[] = $dir;
98
+
99
+        return $fichiers;
100
+    }
101
+    if ($max_prof <= 0) {
102
+        return $fichiers;
103
+    }
104
+
105
+    $subdirs = array();
106
+    if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
107
+        while (($f = readdir($d)) !== false) {
108
+            if ($f[0] != '.' # ignorer . .. .svn etc
109
+                and $f != 'CVS'
110
+                and is_dir($f = "$dir/$f")
111
+            ) {
112
+                $subdirs[] = $f;
113
+            }
114
+        }
115
+        closedir($d);
116
+    }
117
+
118
+    foreach ($subdirs as $d) {
119
+        $fichiers = array_merge($fichiers, fast_find_plugin_dirs("$d/", $max_prof - 1));
120
+    }
121
+
122
+    return $fichiers;
123 123
 }
124 124
 
125 125
 /**
@@ -140,27 +140,27 @@  discard block
 block discarded – undo
140 140
 **/
141 141
 function is_plugin_dir($dir, $dir_plugins = null) {
142 142
 
143
-	if (is_array($dir)) {
144
-		foreach ($dir as $k => $d) {
145
-			if (!is_plugin_dir($d, $dir_plugins)) {
146
-				unset($dir[$k]);
147
-			}
148
-		}
149
-
150
-		return $dir;
151
-	}
152
-	if (is_null($dir_plugins)) {
153
-		$dir_plugins = _DIR_PLUGINS;
154
-	}
155
-	$search = array("$dir_plugins$dir/paquet.xml");
156
-
157
-	foreach ($search as $s) {
158
-		if (file_exists($s)) {
159
-			return $dir;
160
-		}
161
-	}
162
-
163
-	return '';
143
+    if (is_array($dir)) {
144
+        foreach ($dir as $k => $d) {
145
+            if (!is_plugin_dir($d, $dir_plugins)) {
146
+                unset($dir[$k]);
147
+            }
148
+        }
149
+
150
+        return $dir;
151
+    }
152
+    if (is_null($dir_plugins)) {
153
+        $dir_plugins = _DIR_PLUGINS;
154
+    }
155
+    $search = array("$dir_plugins$dir/paquet.xml");
156
+
157
+    foreach ($search as $s) {
158
+        if (file_exists($s)) {
159
+            return $dir;
160
+        }
161
+    }
162
+
163
+    return '';
164 164
 }
165 165
 
166 166
 /** Regexp d'extraction des informations d'un intervalle de compatibilité */
@@ -187,51 +187,51 @@  discard block
 block discarded – undo
187 187
  **/
188 188
 function plugin_version_compatible($intervalle, $version, $avec_quoi = '') {
189 189
 
190
-	if (!strlen($intervalle)) {
191
-		return true;
192
-	}
193
-	if (!preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
194
-		return false;
195
-	}
196
-	// Extraction des bornes et traitement de * pour la borne sup :
197
-	// -- on autorise uniquement les ecritures 3.0.*, 3.*
198
-	$minimum = $regs[1];
199
-	$maximum = $regs[2];
200
-
201
-	//  si une version SPIP de compatibilité a été définie (dans
202
-	//  mes_options.php, sous la forme : define('_DEV_VERSION_SPIP_COMPAT', '3.1.0');
203
-	//  on l'utilise (phase de dev, de test...) mais *que* en cas de comparaison
204
-	//  avec la version de SPIP (ne nuit donc pas aux tests de necessite
205
-	//  entre plugins)
206
-	if (defined('_DEV_VERSION_SPIP_COMPAT') and $avec_quoi == 'spip' and $version !== _DEV_VERSION_SPIP_COMPAT) {
207
-		if (plugin_version_compatible($intervalle, _DEV_VERSION_SPIP_COMPAT, $avec_quoi)) {
208
-			return true;
209
-		}
210
-		// si pas de compatibilite avec _DEV_VERSION_SPIP_COMPAT, on essaye quand meme avec la vrai version
211
-		// cas du plugin qui n'est compatible qu'avec cette nouvelle version
212
-	}
213
-
214
-	$minimum_inc = $intervalle[0] == "[";
215
-	$maximum_inc = substr($intervalle, -1) == "]";
216
-
217
-	if (strlen($minimum)) {
218
-		if ($minimum_inc and spip_version_compare($version, $minimum, '<')) {
219
-			return false;
220
-		}
221
-		if (!$minimum_inc and spip_version_compare($version, $minimum, '<=')) {
222
-			return false;
223
-		}
224
-	}
225
-	if (strlen($maximum)) {
226
-		if ($maximum_inc and spip_version_compare($version, $maximum, '>')) {
227
-			return false;
228
-		}
229
-		if (!$maximum_inc and spip_version_compare($version, $maximum, '>=')) {
230
-			return false;
231
-		}
232
-	}
233
-
234
-	return true;
190
+    if (!strlen($intervalle)) {
191
+        return true;
192
+    }
193
+    if (!preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
194
+        return false;
195
+    }
196
+    // Extraction des bornes et traitement de * pour la borne sup :
197
+    // -- on autorise uniquement les ecritures 3.0.*, 3.*
198
+    $minimum = $regs[1];
199
+    $maximum = $regs[2];
200
+
201
+    //  si une version SPIP de compatibilité a été définie (dans
202
+    //  mes_options.php, sous la forme : define('_DEV_VERSION_SPIP_COMPAT', '3.1.0');
203
+    //  on l'utilise (phase de dev, de test...) mais *que* en cas de comparaison
204
+    //  avec la version de SPIP (ne nuit donc pas aux tests de necessite
205
+    //  entre plugins)
206
+    if (defined('_DEV_VERSION_SPIP_COMPAT') and $avec_quoi == 'spip' and $version !== _DEV_VERSION_SPIP_COMPAT) {
207
+        if (plugin_version_compatible($intervalle, _DEV_VERSION_SPIP_COMPAT, $avec_quoi)) {
208
+            return true;
209
+        }
210
+        // si pas de compatibilite avec _DEV_VERSION_SPIP_COMPAT, on essaye quand meme avec la vrai version
211
+        // cas du plugin qui n'est compatible qu'avec cette nouvelle version
212
+    }
213
+
214
+    $minimum_inc = $intervalle[0] == "[";
215
+    $maximum_inc = substr($intervalle, -1) == "]";
216
+
217
+    if (strlen($minimum)) {
218
+        if ($minimum_inc and spip_version_compare($version, $minimum, '<')) {
219
+            return false;
220
+        }
221
+        if (!$minimum_inc and spip_version_compare($version, $minimum, '<=')) {
222
+            return false;
223
+        }
224
+    }
225
+    if (strlen($maximum)) {
226
+        if ($maximum_inc and spip_version_compare($version, $maximum, '>')) {
227
+            return false;
228
+        }
229
+        if (!$maximum_inc and spip_version_compare($version, $maximum, '>=')) {
230
+            return false;
231
+        }
232
+    }
233
+
234
+    return true;
235 235
 }
236 236
 
237 237
 /**
@@ -248,62 +248,62 @@  discard block
 block discarded – undo
248 248
  * @return array
249 249
  */
250 250
 function liste_plugin_valides($liste_plug, $force = false) {
251
-	$liste_ext = liste_plugin_files(_DIR_PLUGINS_DIST);
252
-	$get_infos = charger_fonction('get_infos', 'plugins');
253
-	$infos = array(
254
-		// lister les extensions qui sont automatiquement actives
255
-		'_DIR_PLUGINS_DIST' => $get_infos($liste_ext, $force, _DIR_PLUGINS_DIST),
256
-		'_DIR_PLUGINS' => $get_infos($liste_plug, $force, _DIR_PLUGINS)
257
-	);
258
-
259
-	// creer une premiere liste non ordonnee mais qui ne retient
260
-	// que les plugins valides, et dans leur derniere version en cas de doublon
261
-	$infos['_DIR_RESTREINT'][''] = $get_infos('./', $force, _DIR_RESTREINT);
262
-	$infos['_DIR_RESTREINT']['SPIP']['version'] = $GLOBALS['spip_version_branche'];
263
-	$infos['_DIR_RESTREINT']['SPIP']['chemin'] = array();
264
-	$liste_non_classee = array(
265
-		'SPIP' => array(
266
-			'nom' => 'SPIP',
267
-			'etat' => 'stable',
268
-			'version' => $GLOBALS['spip_version_branche'],
269
-			'dir_type' => '_DIR_RESTREINT',
270
-			'dir' => '',
271
-		)
272
-	);
273
-
274
-	$invalides = array();
275
-	foreach ($liste_ext as $plug) {
276
-		if (isset($infos['_DIR_PLUGINS_DIST'][$plug])) {
277
-			plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_DIST');
278
-		}
279
-	}
280
-	foreach ($liste_plug as $plug) {
281
-		if (isset($infos['_DIR_PLUGINS'][$plug])) {
282
-			$r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS');
283
-			if (is_array($r)) {
284
-				$invalides = array_merge($invalides, $r);
285
-			}
286
-		}
287
-	}
288
-
289
-	if (defined('_DIR_PLUGINS_SUPPL') and _DIR_PLUGINS_SUPPL) {
290
-		$infos['_DIR_PLUGINS_SUPPL'] = $get_infos($liste_plug, false, _DIR_PLUGINS_SUPPL);
291
-		foreach ($liste_plug as $plug) {
292
-			if (isset($infos['_DIR_PLUGINS_SUPPL'][$plug])) {
293
-				$r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_SUPPL');
294
-				if (is_array($r)) {
295
-					$invalides = array_merge($invalides, $r);
296
-				}
297
-			}
298
-		}
299
-	}
300
-
301
-	plugin_fixer_procure($liste_non_classee, $infos);
302
-
303
-	// les plugins qui sont dans $liste_non_classee ne sont pas invalides (on a trouve un autre version valide)
304
-	$invalides = array_diff_key($invalides, $liste_non_classee);
305
-
306
-	return array($infos, $liste_non_classee, $invalides);
251
+    $liste_ext = liste_plugin_files(_DIR_PLUGINS_DIST);
252
+    $get_infos = charger_fonction('get_infos', 'plugins');
253
+    $infos = array(
254
+        // lister les extensions qui sont automatiquement actives
255
+        '_DIR_PLUGINS_DIST' => $get_infos($liste_ext, $force, _DIR_PLUGINS_DIST),
256
+        '_DIR_PLUGINS' => $get_infos($liste_plug, $force, _DIR_PLUGINS)
257
+    );
258
+
259
+    // creer une premiere liste non ordonnee mais qui ne retient
260
+    // que les plugins valides, et dans leur derniere version en cas de doublon
261
+    $infos['_DIR_RESTREINT'][''] = $get_infos('./', $force, _DIR_RESTREINT);
262
+    $infos['_DIR_RESTREINT']['SPIP']['version'] = $GLOBALS['spip_version_branche'];
263
+    $infos['_DIR_RESTREINT']['SPIP']['chemin'] = array();
264
+    $liste_non_classee = array(
265
+        'SPIP' => array(
266
+            'nom' => 'SPIP',
267
+            'etat' => 'stable',
268
+            'version' => $GLOBALS['spip_version_branche'],
269
+            'dir_type' => '_DIR_RESTREINT',
270
+            'dir' => '',
271
+        )
272
+    );
273
+
274
+    $invalides = array();
275
+    foreach ($liste_ext as $plug) {
276
+        if (isset($infos['_DIR_PLUGINS_DIST'][$plug])) {
277
+            plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_DIST');
278
+        }
279
+    }
280
+    foreach ($liste_plug as $plug) {
281
+        if (isset($infos['_DIR_PLUGINS'][$plug])) {
282
+            $r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS');
283
+            if (is_array($r)) {
284
+                $invalides = array_merge($invalides, $r);
285
+            }
286
+        }
287
+    }
288
+
289
+    if (defined('_DIR_PLUGINS_SUPPL') and _DIR_PLUGINS_SUPPL) {
290
+        $infos['_DIR_PLUGINS_SUPPL'] = $get_infos($liste_plug, false, _DIR_PLUGINS_SUPPL);
291
+        foreach ($liste_plug as $plug) {
292
+            if (isset($infos['_DIR_PLUGINS_SUPPL'][$plug])) {
293
+                $r = plugin_valide_resume($liste_non_classee, $plug, $infos, '_DIR_PLUGINS_SUPPL');
294
+                if (is_array($r)) {
295
+                    $invalides = array_merge($invalides, $r);
296
+                }
297
+            }
298
+        }
299
+    }
300
+
301
+    plugin_fixer_procure($liste_non_classee, $infos);
302
+
303
+    // les plugins qui sont dans $liste_non_classee ne sont pas invalides (on a trouve un autre version valide)
304
+    $invalides = array_diff_key($invalides, $liste_non_classee);
305
+
306
+    return array($infos, $liste_non_classee, $invalides);
307 307
 }
308 308
 
309 309
 /**
@@ -323,29 +323,29 @@  discard block
 block discarded – undo
323 323
  *   array description short si on ne le retient pas (pour memorisation dans une table des erreurs)
324 324
  */
325 325
 function plugin_valide_resume(&$liste, $plug, $infos, $dir_type) {
326
-	$i = $infos[$dir_type][$plug];
327
-	$p = strtoupper($i['prefix']);
328
-	$short_desc = array(
329
-		'nom' => $i['nom'],
330
-		'etat' => $i['etat'],
331
-		'version' => $i['version'],
332
-		'dir' => $plug,
333
-		'dir_type' => $dir_type
334
-	);
335
-	if (isset($i['erreur']) and $i['erreur']) {
336
-		$short_desc['erreur'] = $i['erreur'];
337
-		return array($p=>$short_desc);
338
-	}
339
-	if (!plugin_version_compatible($i['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
340
-		return array($p=>$short_desc);
341
-	}
342
-	if (!isset($liste[$p])
343
-		or spip_version_compare($i['version'], $liste[$p]['version'], '>')
344
-	) {
345
-		$liste[$p] = $short_desc;
346
-	}
347
-	// ok le plugin etait deja dans la liste ou on a choisi une version plus recente
348
-	return $p;
326
+    $i = $infos[$dir_type][$plug];
327
+    $p = strtoupper($i['prefix']);
328
+    $short_desc = array(
329
+        'nom' => $i['nom'],
330
+        'etat' => $i['etat'],
331
+        'version' => $i['version'],
332
+        'dir' => $plug,
333
+        'dir_type' => $dir_type
334
+    );
335
+    if (isset($i['erreur']) and $i['erreur']) {
336
+        $short_desc['erreur'] = $i['erreur'];
337
+        return array($p=>$short_desc);
338
+    }
339
+    if (!plugin_version_compatible($i['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
340
+        return array($p=>$short_desc);
341
+    }
342
+    if (!isset($liste[$p])
343
+        or spip_version_compare($i['version'], $liste[$p]['version'], '>')
344
+    ) {
345
+        $liste[$p] = $short_desc;
346
+    }
347
+    // ok le plugin etait deja dans la liste ou on a choisi une version plus recente
348
+    return $p;
349 349
 }
350 350
 
351 351
 /**
@@ -361,46 +361,46 @@  discard block
 block discarded – undo
361 361
  * @param array $infos
362 362
  */
363 363
 function plugin_fixer_procure(&$liste, &$infos) {
364
-	foreach ($liste as $p => $resume) {
365
-		$i = $infos[$resume['dir_type']][$resume['dir']];
366
-		if (isset($i['procure']) and $i['procure']) {
367
-			foreach ($i['procure'] as $procure) {
368
-				$p = strtoupper($procure['nom']);
369
-				$dir = $resume['dir'];
370
-				if ($dir) {
371
-					$dir .= "/";
372
-				}
373
-				$dir .= "procure:" . $procure['nom'];
374
-
375
-				$procure['etat'] = '?';
376
-				$procure['dir_type'] = $resume['dir_type'];
377
-				$procure['dir'] = $dir;
378
-
379
-				// si ce plugin n'est pas deja procure, ou dans une version plus ancienne
380
-				// on ajoute cette version a la liste
381
-				if (!isset($liste[$p])
382
-					or spip_version_compare($procure['version'], $liste[$p]['version'], '>')
383
-				) {
384
-					$liste[$p] = $procure;
385
-
386
-					// on fournit une information minimale pour ne pas perturber la compilation
387
-					$infos[$resume['dir_type']][$dir] = array(
388
-						'prefix' => $procure['nom'],
389
-						'nom' => $procure['nom'],
390
-						'etat' => $procure['etat'],
391
-						'version' => $procure['version'],
392
-						'chemin' => array(),
393
-						'necessite' => array(),
394
-						'utilise' => array(),
395
-						'lib' => array(),
396
-						'menu' => array(),
397
-						'onglet' => array(),
398
-						'procure' => array(),
399
-					);
400
-				}
401
-			}
402
-		}
403
-	}
364
+    foreach ($liste as $p => $resume) {
365
+        $i = $infos[$resume['dir_type']][$resume['dir']];
366
+        if (isset($i['procure']) and $i['procure']) {
367
+            foreach ($i['procure'] as $procure) {
368
+                $p = strtoupper($procure['nom']);
369
+                $dir = $resume['dir'];
370
+                if ($dir) {
371
+                    $dir .= "/";
372
+                }
373
+                $dir .= "procure:" . $procure['nom'];
374
+
375
+                $procure['etat'] = '?';
376
+                $procure['dir_type'] = $resume['dir_type'];
377
+                $procure['dir'] = $dir;
378
+
379
+                // si ce plugin n'est pas deja procure, ou dans une version plus ancienne
380
+                // on ajoute cette version a la liste
381
+                if (!isset($liste[$p])
382
+                    or spip_version_compare($procure['version'], $liste[$p]['version'], '>')
383
+                ) {
384
+                    $liste[$p] = $procure;
385
+
386
+                    // on fournit une information minimale pour ne pas perturber la compilation
387
+                    $infos[$resume['dir_type']][$dir] = array(
388
+                        'prefix' => $procure['nom'],
389
+                        'nom' => $procure['nom'],
390
+                        'etat' => $procure['etat'],
391
+                        'version' => $procure['version'],
392
+                        'chemin' => array(),
393
+                        'necessite' => array(),
394
+                        'utilise' => array(),
395
+                        'lib' => array(),
396
+                        'menu' => array(),
397
+                        'onglet' => array(),
398
+                        'procure' => array(),
399
+                    );
400
+                }
401
+            }
402
+        }
403
+    }
404 404
 }
405 405
 
406 406
 /**
@@ -414,19 +414,19 @@  discard block
 block discarded – undo
414 414
  * @return array
415 415
  */
416 416
 function liste_chemin_plugin($liste, $dir_plugins = _DIR_PLUGINS) {
417
-	foreach ($liste as $prefix => $infos) {
418
-		if (!$dir_plugins
419
-			or (
420
-				defined($infos['dir_type'])
421
-				and constant($infos['dir_type']) == $dir_plugins)
422
-		) {
423
-			$liste[$prefix] = $infos['dir'];
424
-		} else {
425
-			unset($liste[$prefix]);
426
-		}
427
-	}
428
-
429
-	return $liste;
417
+    foreach ($liste as $prefix => $infos) {
418
+        if (!$dir_plugins
419
+            or (
420
+                defined($infos['dir_type'])
421
+                and constant($infos['dir_type']) == $dir_plugins)
422
+        ) {
423
+            $liste[$prefix] = $infos['dir'];
424
+        } else {
425
+            unset($liste[$prefix]);
426
+        }
427
+    }
428
+
429
+    return $liste;
430 430
 }
431 431
 
432 432
 /**
@@ -441,9 +441,9 @@  discard block
 block discarded – undo
441 441
  * @return array
442 442
  */
443 443
 function liste_chemin_plugin_actifs($dir_plugins = _DIR_PLUGINS) {
444
-	include_spip('plugins/installer');
444
+    include_spip('plugins/installer');
445 445
 
446
-	return liste_chemin_plugin(liste_plugin_actifs(), $dir_plugins);
446
+    return liste_chemin_plugin(liste_plugin_actifs(), $dir_plugins);
447 447
 }
448 448
 
449 449
 /**
@@ -474,53 +474,53 @@  discard block
 block discarded – undo
474 474
  *                qui n'ont pas satisfait leurs dépendances
475 475
 **/
476 476
 function plugin_trier($infos, $liste_non_classee) {
477
-	$toute_la_liste = $liste_non_classee;
478
-	$liste = $ordre = array();
479
-	$count = 0;
480
-
481
-	while ($c = count($liste_non_classee) and $c != $count) { // tant qu'il reste des plugins a classer, et qu'on ne stagne pas
482
-		#echo "tour::";var_dump($liste_non_classee);
483
-		$count = $c;
484
-		foreach ($liste_non_classee as $p => $resume) {
485
-			$plug = $resume['dir'];
486
-			$dir_type = $resume['dir_type'];
487
-			$info1 = $infos[$dir_type][$plug];
488
-			// si des plugins sont necessaires,
489
-			// on ne peut inserer qu'apres eux
490
-			foreach ($info1['necessite'] as $need) {
491
-				$nom = strtoupper($need['nom']);
492
-				$compat = isset($need['compatibilite']) ? $need['compatibilite'] : '';
493
-				if (!isset($liste[$nom]) or !plugin_version_compatible($compat, $liste[$nom]['version'])) {
494
-					$info1 = false;
495
-					break;
496
-				}
497
-			}
498
-			if (!$info1) {
499
-				continue;
500
-			}
501
-			// idem si des plugins sont utiles,
502
-			// sauf si ils sont de toute facon absents de la liste
503
-			foreach ($info1['utilise'] as $need) {
504
-				$nom = strtoupper($need['nom']);
505
-				$compat = isset($need['compatibilite']) ? $need['compatibilite'] : '';
506
-				if (isset($toute_la_liste[$nom])) {
507
-					if (!isset($liste[$nom]) or
508
-						!plugin_version_compatible($compat, $liste[$nom]['version'])
509
-					) {
510
-						$info1 = false;
511
-						break;
512
-					}
513
-				}
514
-			}
515
-			if ($info1) {
516
-				$ordre[$p] = $info1;
517
-				$liste[$p] = $liste_non_classee[$p];
518
-				unset($liste_non_classee[$p]);
519
-			}
520
-		}
521
-	}
522
-
523
-	return array($liste, $ordre, $liste_non_classee);
477
+    $toute_la_liste = $liste_non_classee;
478
+    $liste = $ordre = array();
479
+    $count = 0;
480
+
481
+    while ($c = count($liste_non_classee) and $c != $count) { // tant qu'il reste des plugins a classer, et qu'on ne stagne pas
482
+        #echo "tour::";var_dump($liste_non_classee);
483
+        $count = $c;
484
+        foreach ($liste_non_classee as $p => $resume) {
485
+            $plug = $resume['dir'];
486
+            $dir_type = $resume['dir_type'];
487
+            $info1 = $infos[$dir_type][$plug];
488
+            // si des plugins sont necessaires,
489
+            // on ne peut inserer qu'apres eux
490
+            foreach ($info1['necessite'] as $need) {
491
+                $nom = strtoupper($need['nom']);
492
+                $compat = isset($need['compatibilite']) ? $need['compatibilite'] : '';
493
+                if (!isset($liste[$nom]) or !plugin_version_compatible($compat, $liste[$nom]['version'])) {
494
+                    $info1 = false;
495
+                    break;
496
+                }
497
+            }
498
+            if (!$info1) {
499
+                continue;
500
+            }
501
+            // idem si des plugins sont utiles,
502
+            // sauf si ils sont de toute facon absents de la liste
503
+            foreach ($info1['utilise'] as $need) {
504
+                $nom = strtoupper($need['nom']);
505
+                $compat = isset($need['compatibilite']) ? $need['compatibilite'] : '';
506
+                if (isset($toute_la_liste[$nom])) {
507
+                    if (!isset($liste[$nom]) or
508
+                        !plugin_version_compatible($compat, $liste[$nom]['version'])
509
+                    ) {
510
+                        $info1 = false;
511
+                        break;
512
+                    }
513
+                }
514
+            }
515
+            if ($info1) {
516
+                $ordre[$p] = $info1;
517
+                $liste[$p] = $liste_non_classee[$p];
518
+                unset($liste_non_classee[$p]);
519
+            }
520
+        }
521
+    }
522
+
523
+    return array($liste, $ordre, $liste_non_classee);
524 524
 }
525 525
 
526 526
 /**
@@ -537,40 +537,40 @@  discard block
 block discarded – undo
537 537
  *     Répertoire (plugins, plugins-dist, ...) => Couples (prefixes => infos completes) des plugins qu'ils contiennent
538 538
 **/
539 539
 function plugins_erreurs($liste_non_classee, $liste, $infos, $msg = array()) {
540
-	static $erreurs = array();
541
-
542
-	if (!is_array($liste)) {
543
-		$liste = array();
544
-	}
545
-
546
-	// les plugins en erreur ne sont pas actifs ; ils ne doivent pas être dans la liste
547
-	$liste = array_diff_key($liste, $liste_non_classee);
548
-
549
-	foreach ($liste_non_classee as $p => $resume) {
550
-		$dir_type = $resume['dir_type'];
551
-		$plug = $resume['dir'];
552
-		$k = $infos[$dir_type][$plug];
553
-
554
-		$plug = constant($dir_type) . $plug;
555
-		if (!isset($msg[$p])) {
556
-			if (isset($resume['erreur']) and $resume['erreur']) {
557
-				$msg[$p] = array($resume['erreur']);
558
-			}
559
-			elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
560
-				$msg[$p] = array(plugin_message_incompatibilite($k['compatibilite'], $GLOBALS['spip_version_branche'], 'SPIP', 'necessite'));
561
-			}
562
-			elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
563
-				$msg[$p] = plugin_necessite($k['utilise'], $liste, 'utilise');
564
-			}
565
-		} else {
566
-			foreach ($msg[$p] as $c => $l) {
567
-				$msg[$p][$c] = plugin_controler_lib($l['nom'], $l['lien']);
568
-			}
569
-		}
570
-		$erreurs[$plug] = $msg[$p];
571
-	}
572
-
573
-	ecrire_meta('plugin_erreur_activation', serialize($erreurs));
540
+    static $erreurs = array();
541
+
542
+    if (!is_array($liste)) {
543
+        $liste = array();
544
+    }
545
+
546
+    // les plugins en erreur ne sont pas actifs ; ils ne doivent pas être dans la liste
547
+    $liste = array_diff_key($liste, $liste_non_classee);
548
+
549
+    foreach ($liste_non_classee as $p => $resume) {
550
+        $dir_type = $resume['dir_type'];
551
+        $plug = $resume['dir'];
552
+        $k = $infos[$dir_type][$plug];
553
+
554
+        $plug = constant($dir_type) . $plug;
555
+        if (!isset($msg[$p])) {
556
+            if (isset($resume['erreur']) and $resume['erreur']) {
557
+                $msg[$p] = array($resume['erreur']);
558
+            }
559
+            elseif (!plugin_version_compatible($k['compatibilite'], $GLOBALS['spip_version_branche'], 'spip')) {
560
+                $msg[$p] = array(plugin_message_incompatibilite($k['compatibilite'], $GLOBALS['spip_version_branche'], 'SPIP', 'necessite'));
561
+            }
562
+            elseif (!$msg[$p] = plugin_necessite($k['necessite'], $liste, 'necessite')) {
563
+                $msg[$p] = plugin_necessite($k['utilise'], $liste, 'utilise');
564
+            }
565
+        } else {
566
+            foreach ($msg[$p] as $c => $l) {
567
+                $msg[$p][$c] = plugin_controler_lib($l['nom'], $l['lien']);
568
+            }
569
+        }
570
+        $erreurs[$plug] = $msg[$p];
571
+    }
572
+
573
+    ecrire_meta('plugin_erreur_activation', serialize($erreurs));
574 574
 }
575 575
 
576 576
 /**
@@ -585,25 +585,25 @@  discard block
 block discarded – undo
585 585
  *     - Liste des erreurs ou code HTML des erreurs
586 586
 **/
587 587
 function plugin_donne_erreurs($raw = false, $raz = true) {
588
-	if (!isset($GLOBALS['meta']['plugin_erreur_activation'])) {
589
-		return $raw ? array() : '';
590
-	}
591
-	$list = @unserialize($GLOBALS['meta']['plugin_erreur_activation']);
592
-	// Compat ancienne version
593
-	if (!$list) {
594
-		$list = $raw ? array() : $GLOBALS['meta']['plugin_erreur_activation'];
595
-	} elseif (!$raw) {
596
-		foreach ($list as $plug => $msg) {
597
-			$list[$plug] = "<li>" . _T('plugin_impossible_activer', array('plugin' => $plug))
598
-				. "<ul><li>" . implode("</li><li>", $msg) . "</li></ul></li>";
599
-		}
600
-		$list = "<ul>" . join("\n", $list) . "</ul>";
601
-	}
602
-	if ($raz) {
603
-		effacer_meta('plugin_erreur_activation');
604
-	}
605
-
606
-	return $list;
588
+    if (!isset($GLOBALS['meta']['plugin_erreur_activation'])) {
589
+        return $raw ? array() : '';
590
+    }
591
+    $list = @unserialize($GLOBALS['meta']['plugin_erreur_activation']);
592
+    // Compat ancienne version
593
+    if (!$list) {
594
+        $list = $raw ? array() : $GLOBALS['meta']['plugin_erreur_activation'];
595
+    } elseif (!$raw) {
596
+        foreach ($list as $plug => $msg) {
597
+            $list[$plug] = "<li>" . _T('plugin_impossible_activer', array('plugin' => $plug))
598
+                . "<ul><li>" . implode("</li><li>", $msg) . "</li></ul></li>";
599
+        }
600
+        $list = "<ul>" . join("\n", $list) . "</ul>";
601
+    }
602
+    if ($raz) {
603
+        effacer_meta('plugin_erreur_activation');
604
+    }
605
+
606
+    return $list;
607 607
 }
608 608
 
609 609
 /**
@@ -623,21 +623,21 @@  discard block
 block discarded – undo
623 623
  *
624 624
  **/
625 625
 function plugin_necessite($n, $liste, $balise = 'necessite') {
626
-	$msg = array();
627
-	foreach ($n as $need) {
628
-		$id = strtoupper($need['nom']);
629
-		$r = plugin_controler_necessite(
630
-			$liste, 
631
-			$id, 
632
-			isset($need['compatibilite']) ? $need['compatibilite'] : '', 
633
-			$balise
634
-		);
635
-		if ($r) {
636
-			$msg[] = $r;
637
-		}
638
-	}
639
-
640
-	return $msg;
626
+    $msg = array();
627
+    foreach ($n as $need) {
628
+        $id = strtoupper($need['nom']);
629
+        $r = plugin_controler_necessite(
630
+            $liste, 
631
+            $id, 
632
+            isset($need['compatibilite']) ? $need['compatibilite'] : '', 
633
+            $balise
634
+        );
635
+        if ($r) {
636
+            $msg[] = $r;
637
+        }
638
+    }
639
+
640
+    return $msg;
641 641
 }
642 642
 
643 643
 /**
@@ -659,19 +659,19 @@  discard block
 block discarded – undo
659 659
  *    Message d'erreur lorsque la dépendance est absente.
660 660
  **/
661 661
 function plugin_controler_necessite($liste, $nom, $intervalle, $balise) {
662
-	if (isset($liste[$nom]) and plugin_version_compatible($intervalle, $liste[$nom]['version'])) {
663
-		return '';
664
-	}
665
-	// Si l'on a un <utilise="plugin non actif" />, ne pas renvoyer d'erreur
666
-	if ($balise === 'utilise' and !isset($liste[$nom])) {
667
-		return '';
668
-	}
669
-	return plugin_message_incompatibilite(
670
-		$intervalle, 
671
-		(isset($liste[$nom]) ? $liste[$nom]['version'] : ""), 
672
-		$nom, 
673
-		$balise
674
-	);
662
+    if (isset($liste[$nom]) and plugin_version_compatible($intervalle, $liste[$nom]['version'])) {
663
+        return '';
664
+    }
665
+    // Si l'on a un <utilise="plugin non actif" />, ne pas renvoyer d'erreur
666
+    if ($balise === 'utilise' and !isset($liste[$nom])) {
667
+        return '';
668
+    }
669
+    return plugin_message_incompatibilite(
670
+        $intervalle, 
671
+        (isset($liste[$nom]) ? $liste[$nom]['version'] : ""), 
672
+        $nom, 
673
+        $balise
674
+    );
675 675
 }
676 676
 
677 677
 /**
@@ -688,70 +688,70 @@  discard block
 block discarded – undo
688 688
  */
689 689
 function plugin_message_incompatibilite($intervalle, $version, $nom, $balise) {
690 690
 
691
-	// prendre en compte les erreurs de dépendances à PHP
692
-	// ou à une extension PHP avec des messages d'erreurs dédiés.
693
-	$type = 'plugin';
694
-	if ($nom === 'SPIP') {
695
-		$type = 'spip';
696
-	} elseif ($nom === 'PHP') {
697
-		$type = 'php';
698
-	} elseif (strncmp($nom, 'PHP:', 4) === 0) {
699
-		$type = 'extension_php';
700
-		list(,$nom) = explode(':', $nom, 2);
701
-	}
702
-
703
-	if (preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
704
-		$minimum = $regs[1];
705
-		$maximum = $regs[2];
706
-
707
-		$minimum_inclus = $intervalle[0] == "[";
708
-		$maximum_inclus = substr($intervalle, -1) == "]";
709
-
710
-		if (strlen($minimum)) {
711
-			if ($minimum_inclus and spip_version_compare($version, $minimum, '<')) {
712
-				return _T("plugin_${balise}_${type}", array(
713
-					'plugin' => $nom,
714
-					'version' => ' &ge; ' . $minimum
715
-				));
716
-			}
717
-			if (!$minimum_inclus and spip_version_compare($version, $minimum, '<=')) {
718
-				return _T("plugin_${balise}_${type}", array(
719
-					'plugin' => $nom,
720
-					'version' => ' &gt; ' . $minimum
721
-				));
722
-			}
723
-		}
724
-
725
-		if (strlen($maximum)) {
726
-			if ($maximum_inclus and spip_version_compare($version, $maximum, '>')) {
727
-				return _T("plugin_${balise}_${type}", array(
728
-					'plugin' => $nom,
729
-					'version' => ' &le; ' . $maximum
730
-				));
731
-			}
732
-			if (!$maximum_inclus and spip_version_compare($version, $maximum, '>=')) {
733
-				return _T("plugin_${balise}_plugin", array(
734
-					'plugin' => $nom,
735
-					'version' => ' &lt; ' . $maximum
736
-				));
737
-			}
738
-		}
739
-	}
740
-
741
-	// note : il ne peut pas y avoir d'erreur sur
742
-	// - un 'utilise' sans version.
743
-	// - un 'php' sans version.
744
-	return _T("plugin_necessite_${type}_sans_version", array('plugin' => $nom));
691
+    // prendre en compte les erreurs de dépendances à PHP
692
+    // ou à une extension PHP avec des messages d'erreurs dédiés.
693
+    $type = 'plugin';
694
+    if ($nom === 'SPIP') {
695
+        $type = 'spip';
696
+    } elseif ($nom === 'PHP') {
697
+        $type = 'php';
698
+    } elseif (strncmp($nom, 'PHP:', 4) === 0) {
699
+        $type = 'extension_php';
700
+        list(,$nom) = explode(':', $nom, 2);
701
+    }
702
+
703
+    if (preg_match(_EXTRAIRE_INTERVALLE, $intervalle, $regs)) {
704
+        $minimum = $regs[1];
705
+        $maximum = $regs[2];
706
+
707
+        $minimum_inclus = $intervalle[0] == "[";
708
+        $maximum_inclus = substr($intervalle, -1) == "]";
709
+
710
+        if (strlen($minimum)) {
711
+            if ($minimum_inclus and spip_version_compare($version, $minimum, '<')) {
712
+                return _T("plugin_${balise}_${type}", array(
713
+                    'plugin' => $nom,
714
+                    'version' => ' &ge; ' . $minimum
715
+                ));
716
+            }
717
+            if (!$minimum_inclus and spip_version_compare($version, $minimum, '<=')) {
718
+                return _T("plugin_${balise}_${type}", array(
719
+                    'plugin' => $nom,
720
+                    'version' => ' &gt; ' . $minimum
721
+                ));
722
+            }
723
+        }
724
+
725
+        if (strlen($maximum)) {
726
+            if ($maximum_inclus and spip_version_compare($version, $maximum, '>')) {
727
+                return _T("plugin_${balise}_${type}", array(
728
+                    'plugin' => $nom,
729
+                    'version' => ' &le; ' . $maximum
730
+                ));
731
+            }
732
+            if (!$maximum_inclus and spip_version_compare($version, $maximum, '>=')) {
733
+                return _T("plugin_${balise}_plugin", array(
734
+                    'plugin' => $nom,
735
+                    'version' => ' &lt; ' . $maximum
736
+                ));
737
+            }
738
+        }
739
+    }
740
+
741
+    // note : il ne peut pas y avoir d'erreur sur
742
+    // - un 'utilise' sans version.
743
+    // - un 'php' sans version.
744
+    return _T("plugin_necessite_${type}_sans_version", array('plugin' => $nom));
745 745
 }
746 746
 
747 747
 
748 748
 function plugin_controler_lib($lib, $url) {
749
-	/* Feature sortie du core, voir STP
749
+    /* Feature sortie du core, voir STP
750 750
 	 * if ($url) {
751 751
 		include_spip('inc/charger_plugin');
752 752
 		$url = '<br />'	. bouton_telechargement_plugin($url, 'lib');
753 753
 	}*/
754
-	return _T('plugin_necessite_lib', array('lib' => $lib)) . " <a href='$url'>$url</a>";
754
+    return _T('plugin_necessite_lib', array('lib' => $lib)) . " <a href='$url'>$url</a>";
755 755
 }
756 756
 
757 757
 
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
  *     true si il y a eu des modifications sur la liste des plugins actifs, false sinon
767 767
  **/
768 768
 function actualise_plugins_actifs($pipe_recherche = false) {
769
-	return ecrire_plugin_actifs('', $pipe_recherche, 'force');
769
+    return ecrire_plugin_actifs('', $pipe_recherche, 'force');
770 770
 }
771 771
 
772 772
 
@@ -793,113 +793,113 @@  discard block
 block discarded – undo
793 793
  **/
794 794
 function ecrire_plugin_actifs($plugin, $pipe_recherche = false, $operation = 'raz') {
795 795
 
796
-	// creer le repertoire cache/ si necessaire ! (installation notamment)
797
-	$cache = sous_repertoire(_DIR_CACHE, '', false, true);
798
-
799
-	// Si on n'a ni cache accessible, ni connexion SQL, on ne peut pas faire grand chose encore.
800
-	if (!$cache and !spip_connect()) {
801
-		return false;
802
-	}
803
-
804
-	if ($operation != 'raz') {
805
-		$plugin_valides = liste_chemin_plugin_actifs();
806
-		$plugin_valides = is_plugin_dir($plugin_valides);
807
-		if (defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
808
-			$plugin_valides_supp = liste_chemin_plugin_actifs(_DIR_PLUGINS_SUPPL);
809
-			$plugin_valides_supp = is_plugin_dir($plugin_valides_supp, _DIR_PLUGINS_SUPPL);
810
-			$plugin_valides = array_merge($plugin_valides, $plugin_valides_supp);
811
-		}
812
-		// si des plugins sont en attentes (coches mais impossible a activer)
813
-		// on les reinjecte ici
814
-		if (isset($GLOBALS['meta']['plugin_attente'])
815
-			and $a = unserialize($GLOBALS['meta']['plugin_attente'])
816
-		) {
817
-			$plugin_valides = $plugin_valides + liste_chemin_plugin($a);
818
-		}
819
-
820
-		if ($operation == 'ajoute') {
821
-			$plugin = array_merge($plugin_valides, $plugin);
822
-		} elseif ($operation == 'enleve') {
823
-			$plugin = array_diff($plugin_valides, $plugin);
824
-		} else {
825
-			$plugin = $plugin_valides;
826
-		}
827
-	}
828
-	$actifs_avant = isset($GLOBALS['meta']['plugin']) ? $GLOBALS['meta']['plugin'] : '';
829
-
830
-	// si une fonction de gestion de dependances existe, l'appeler ici
831
-	if ($ajouter_dependances = charger_fonction("ajouter_dependances", "plugins", true)) {
832
-		$plugin = $ajouter_dependances($plugin);
833
-	}
834
-
835
-	// recharger le xml des plugins a activer
836
-	// on force le reload ici, meme si le fichier xml n'a pas change
837
-	// pour ne pas rater l'ajout ou la suppression d'un fichier fonctions/options/administrations
838
-	// pourra etre evite quand on ne supportera plus les plugin.xml
839
-	// en deplacant la detection de ces fichiers dans la compilation ci dessous
840
-	list($infos, $liste, $invalides) = liste_plugin_valides($plugin, true);
841
-	// trouver l'ordre d'activation
842
-	list($plugin_valides, $ordre, $reste) = plugin_trier($infos, $liste);
843
-	if ($invalides or $reste) {
844
-		plugins_erreurs(array_merge($invalides, $reste), $liste, $infos);
845
-	}
846
-
847
-	// Ignorer les plugins necessitant une lib absente
848
-	// et preparer la meta d'entete Http
849
-	$err = $msg = $header = array();
850
-	foreach ($plugin_valides as $p => $resume) {
851
-		// Les headers ne doivent pas indiquer les versions des extensions PHP, ni la version PHP
852
-		if (0 !== strpos($p, 'PHP:') and $p !== 'PHP') {
853
-			$header[] = $p . ($resume['version'] ? "(" . $resume['version'] . ")" : "");
854
-		}
855
-		if ($resume['dir']) {
856
-			foreach ($infos[$resume['dir_type']][$resume['dir']]['lib'] as $l) {
857
-				if (!find_in_path($l['nom'], 'lib/')) {
858
-					$err[$p] = $resume;
859
-					$msg[$p][] = $l;
860
-					unset($plugin_valides[$p]);
861
-				}
862
-			}
863
-		}
864
-	}
865
-	if ($err) {
866
-		plugins_erreurs($err, '', $infos, $msg);
867
-	}
868
-
869
-	if (isset($GLOBALS['meta']['message_crash_plugins'])) {
870
-		effacer_meta('message_crash_plugins');
871
-	}
872
-	ecrire_meta('plugin', serialize($plugin_valides));
873
-	$liste = array_diff_key($liste, $plugin_valides);
874
-	ecrire_meta('plugin_attente', serialize($liste));
875
-	$header = strtolower(implode(",", $header));
876
-	if (!isset($GLOBALS['spip_header_silencieux']) or !$GLOBALS['spip_header_silencieux']) {
877
-		ecrire_fichier(_DIR_VAR . "config.txt",
878
-			(defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : "Composed-By: SPIP") . ' ' . $GLOBALS['spip_version_affichee'] . " @ www.spip.net + " . $header);
879
-	} else {
880
-		@unlink(_DIR_VAR . "config.txt");
881
-	}
882
-	// generer charger_plugins_chemin.php
883
-	plugins_precompile_chemin($plugin_valides, $ordre);
884
-	// generer les fichiers
885
-	// - charger_plugins_options.php
886
-	// - charger_plugins_fonctions.php
887
-	plugins_precompile_xxxtions($plugin_valides, $ordre);
888
-	// charger les chemins des plugins et les fichiers d'options 
889
-	// (qui peuvent déclarer / utiliser des pipelines, ajouter d'autres chemins)
890
-	plugins_amorcer_plugins_actifs();
891
-	// mise a jour de la matrice des pipelines
892
-	$prepend_code = pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche);
893
-	// generer le fichier _CACHE_PIPELINE
894
-	pipeline_precompile($prepend_code);
895
-
896
-	if (spip_connect()) {
897
-		// lancer et initialiser les nouveaux crons !
898
-		include_spip('inc/genie');
899
-		genie_queue_watch_dist();
900
-	}
901
-
902
-	return ($GLOBALS['meta']['plugin'] != $actifs_avant);
796
+    // creer le repertoire cache/ si necessaire ! (installation notamment)
797
+    $cache = sous_repertoire(_DIR_CACHE, '', false, true);
798
+
799
+    // Si on n'a ni cache accessible, ni connexion SQL, on ne peut pas faire grand chose encore.
800
+    if (!$cache and !spip_connect()) {
801
+        return false;
802
+    }
803
+
804
+    if ($operation != 'raz') {
805
+        $plugin_valides = liste_chemin_plugin_actifs();
806
+        $plugin_valides = is_plugin_dir($plugin_valides);
807
+        if (defined('_DIR_PLUGINS_SUPPL') && _DIR_PLUGINS_SUPPL) {
808
+            $plugin_valides_supp = liste_chemin_plugin_actifs(_DIR_PLUGINS_SUPPL);
809
+            $plugin_valides_supp = is_plugin_dir($plugin_valides_supp, _DIR_PLUGINS_SUPPL);
810
+            $plugin_valides = array_merge($plugin_valides, $plugin_valides_supp);
811
+        }
812
+        // si des plugins sont en attentes (coches mais impossible a activer)
813
+        // on les reinjecte ici
814
+        if (isset($GLOBALS['meta']['plugin_attente'])
815
+            and $a = unserialize($GLOBALS['meta']['plugin_attente'])
816
+        ) {
817
+            $plugin_valides = $plugin_valides + liste_chemin_plugin($a);
818
+        }
819
+
820
+        if ($operation == 'ajoute') {
821
+            $plugin = array_merge($plugin_valides, $plugin);
822
+        } elseif ($operation == 'enleve') {
823
+            $plugin = array_diff($plugin_valides, $plugin);
824
+        } else {
825
+            $plugin = $plugin_valides;
826
+        }
827
+    }
828
+    $actifs_avant = isset($GLOBALS['meta']['plugin']) ? $GLOBALS['meta']['plugin'] : '';
829
+
830
+    // si une fonction de gestion de dependances existe, l'appeler ici
831
+    if ($ajouter_dependances = charger_fonction("ajouter_dependances", "plugins", true)) {
832
+        $plugin = $ajouter_dependances($plugin);
833
+    }
834
+
835
+    // recharger le xml des plugins a activer
836
+    // on force le reload ici, meme si le fichier xml n'a pas change
837
+    // pour ne pas rater l'ajout ou la suppression d'un fichier fonctions/options/administrations
838
+    // pourra etre evite quand on ne supportera plus les plugin.xml
839
+    // en deplacant la detection de ces fichiers dans la compilation ci dessous
840
+    list($infos, $liste, $invalides) = liste_plugin_valides($plugin, true);
841
+    // trouver l'ordre d'activation
842
+    list($plugin_valides, $ordre, $reste) = plugin_trier($infos, $liste);
843
+    if ($invalides or $reste) {
844
+        plugins_erreurs(array_merge($invalides, $reste), $liste, $infos);
845
+    }
846
+
847
+    // Ignorer les plugins necessitant une lib absente
848
+    // et preparer la meta d'entete Http
849
+    $err = $msg = $header = array();
850
+    foreach ($plugin_valides as $p => $resume) {
851
+        // Les headers ne doivent pas indiquer les versions des extensions PHP, ni la version PHP
852
+        if (0 !== strpos($p, 'PHP:') and $p !== 'PHP') {
853
+            $header[] = $p . ($resume['version'] ? "(" . $resume['version'] . ")" : "");
854
+        }
855
+        if ($resume['dir']) {
856
+            foreach ($infos[$resume['dir_type']][$resume['dir']]['lib'] as $l) {
857
+                if (!find_in_path($l['nom'], 'lib/')) {
858
+                    $err[$p] = $resume;
859
+                    $msg[$p][] = $l;
860
+                    unset($plugin_valides[$p]);
861
+                }
862
+            }
863
+        }
864
+    }
865
+    if ($err) {
866
+        plugins_erreurs($err, '', $infos, $msg);
867
+    }
868
+
869
+    if (isset($GLOBALS['meta']['message_crash_plugins'])) {
870
+        effacer_meta('message_crash_plugins');
871
+    }
872
+    ecrire_meta('plugin', serialize($plugin_valides));
873
+    $liste = array_diff_key($liste, $plugin_valides);
874
+    ecrire_meta('plugin_attente', serialize($liste));
875
+    $header = strtolower(implode(",", $header));
876
+    if (!isset($GLOBALS['spip_header_silencieux']) or !$GLOBALS['spip_header_silencieux']) {
877
+        ecrire_fichier(_DIR_VAR . "config.txt",
878
+            (defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : "Composed-By: SPIP") . ' ' . $GLOBALS['spip_version_affichee'] . " @ www.spip.net + " . $header);
879
+    } else {
880
+        @unlink(_DIR_VAR . "config.txt");
881
+    }
882
+    // generer charger_plugins_chemin.php
883
+    plugins_precompile_chemin($plugin_valides, $ordre);
884
+    // generer les fichiers
885
+    // - charger_plugins_options.php
886
+    // - charger_plugins_fonctions.php
887
+    plugins_precompile_xxxtions($plugin_valides, $ordre);
888
+    // charger les chemins des plugins et les fichiers d'options 
889
+    // (qui peuvent déclarer / utiliser des pipelines, ajouter d'autres chemins)
890
+    plugins_amorcer_plugins_actifs();
891
+    // mise a jour de la matrice des pipelines
892
+    $prepend_code = pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche);
893
+    // generer le fichier _CACHE_PIPELINE
894
+    pipeline_precompile($prepend_code);
895
+
896
+    if (spip_connect()) {
897
+        // lancer et initialiser les nouveaux crons !
898
+        include_spip('inc/genie');
899
+        genie_queue_watch_dist();
900
+    }
901
+
902
+    return ($GLOBALS['meta']['plugin'] != $actifs_avant);
903 903
 }
904 904
 
905 905
 /**
@@ -918,68 +918,68 @@  discard block
 block discarded – undo
918 918
  *     Couples (prefixe => infos complètes) des plugins qui seront actifs, dans l'ordre de leurs dépendances
919 919
 **/
920 920
 function plugins_precompile_chemin($plugin_valides, $ordre) {
921
-	$chemins = [
922
-		'public' => [],
923
-		'prive' => []
924
-	];
925
-	$contenu = "";
926
-	foreach ($ordre as $p => $info) {
927
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
928
-		if (isset($plugin_valides[$p])) {
929
-			$dir_type = $plugin_valides[$p]['dir_type'];
930
-			$plug = $plugin_valides[$p]['dir'];
931
-			// definir le plugin, donc le path avant l'include du fichier options
932
-			// permet de faire des include_spip pour attraper un inc_ du plugin
933
-
934
-			$dir = $dir_type . ".'" . $plug . "/'";
935
-
936
-			$prefix = strtoupper(preg_replace(',\W,', '_', $info['prefix']));
937
-			if (
938
-				$prefix !== "SPIP"
939
-				and strpos($dir, ":") === false // exclure le cas des procure:
940
-			) {
941
-				$contenu .= "define('_DIR_PLUGIN_$prefix',$dir);\n";
942
-				if (!$info['chemin']) {
943
-					$chemins['public'][] = "_DIR_PLUGIN_$prefix";
944
-					$chemins['prive'][] = "_DIR_PLUGIN_$prefix";
945
-					if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
946
-						$chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
947
-					}
948
-				}
949
-				else{
950
-					foreach ($info['chemin'] as $chemin) {
951
-						if (!isset($chemin['version']) or plugin_version_compatible($chemin['version'],
952
-								$GLOBALS['spip_version_branche'], 'spip')
953
-						) {
954
-							$dir = $chemin['path'];
955
-							if (strlen($dir) and $dir[0] == "/") {
956
-								$dir = substr($dir, 1);
957
-							}
958
-							if (strlen($dir) and $dir == "./") {
959
-								$dir = '';
960
-							}
961
-							if (strlen($dir)) {
962
-								$dir = rtrim($dir, '/') . '/';
963
-							}
964
-							if (!isset($chemin['type']) or $chemin['type'] == 'public') {
965
-								$chemins['public'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
966
-							}
967
-							if (!isset($chemin['type']) or $chemin['type'] == 'prive') {
968
-								$chemins['prive'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
969
-							}
970
-						}
971
-					}
972
-				}
973
-			}
974
-		}
975
-	}
976
-	if (count($chemins['public']) or count($chemins['prive'])) {
977
-		$contenu .= "if (_DIR_RESTREINT) _chemin([" . implode(',',
978
-				array_reverse($chemins['public'])) . "]);\n"
979
-			. "else _chemin([" . implode(',', array_reverse($chemins['prive'])) . "]);\n";
980
-	}
981
-
982
-	ecrire_fichier_php(_CACHE_PLUGINS_PATH, $contenu);
921
+    $chemins = [
922
+        'public' => [],
923
+        'prive' => []
924
+    ];
925
+    $contenu = "";
926
+    foreach ($ordre as $p => $info) {
927
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
928
+        if (isset($plugin_valides[$p])) {
929
+            $dir_type = $plugin_valides[$p]['dir_type'];
930
+            $plug = $plugin_valides[$p]['dir'];
931
+            // definir le plugin, donc le path avant l'include du fichier options
932
+            // permet de faire des include_spip pour attraper un inc_ du plugin
933
+
934
+            $dir = $dir_type . ".'" . $plug . "/'";
935
+
936
+            $prefix = strtoupper(preg_replace(',\W,', '_', $info['prefix']));
937
+            if (
938
+                $prefix !== "SPIP"
939
+                and strpos($dir, ":") === false // exclure le cas des procure:
940
+            ) {
941
+                $contenu .= "define('_DIR_PLUGIN_$prefix',$dir);\n";
942
+                if (!$info['chemin']) {
943
+                    $chemins['public'][] = "_DIR_PLUGIN_$prefix";
944
+                    $chemins['prive'][] = "_DIR_PLUGIN_$prefix";
945
+                    if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
946
+                        $chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
947
+                    }
948
+                }
949
+                else{
950
+                    foreach ($info['chemin'] as $chemin) {
951
+                        if (!isset($chemin['version']) or plugin_version_compatible($chemin['version'],
952
+                                $GLOBALS['spip_version_branche'], 'spip')
953
+                        ) {
954
+                            $dir = $chemin['path'];
955
+                            if (strlen($dir) and $dir[0] == "/") {
956
+                                $dir = substr($dir, 1);
957
+                            }
958
+                            if (strlen($dir) and $dir == "./") {
959
+                                $dir = '';
960
+                            }
961
+                            if (strlen($dir)) {
962
+                                $dir = rtrim($dir, '/') . '/';
963
+                            }
964
+                            if (!isset($chemin['type']) or $chemin['type'] == 'public') {
965
+                                $chemins['public'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
966
+                            }
967
+                            if (!isset($chemin['type']) or $chemin['type'] == 'prive') {
968
+                                $chemins['prive'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
969
+                            }
970
+                        }
971
+                    }
972
+                }
973
+            }
974
+        }
975
+    }
976
+    if (count($chemins['public']) or count($chemins['prive'])) {
977
+        $contenu .= "if (_DIR_RESTREINT) _chemin([" . implode(',',
978
+                array_reverse($chemins['public'])) . "]);\n"
979
+            . "else _chemin([" . implode(',', array_reverse($chemins['prive'])) . "]);\n";
980
+    }
981
+
982
+    ecrire_fichier_php(_CACHE_PLUGINS_PATH, $contenu);
983 983
 }
984 984
 
985 985
 /**
@@ -997,65 +997,65 @@  discard block
 block discarded – undo
997 997
  *     Couples (prefixe => infos complètes) des plugins qui seront actifs, dans l'ordre de leurs dépendances
998 998
 **/
999 999
 function plugins_precompile_xxxtions($plugin_valides, $ordre) {
1000
-	$contenu = array('options' => '', 'fonctions' => '');
1001
-	$boutons = array();
1002
-	$onglets = array();
1003
-	$sign = "";
1004
-
1005
-	foreach ($ordre as $p => $info) {
1006
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
1007
-		if (isset($plugin_valides[$p])) {
1008
-			$dir_type = $plugin_valides[$p]['dir_type'];
1009
-			$plug = $plugin_valides[$p]['dir'];
1010
-			$dir = constant($dir_type);
1011
-			$root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1012
-			if ($info['menu']) {
1013
-				$boutons = array_merge($boutons, $info['menu']);
1014
-			}
1015
-			if ($info['onglet']) {
1016
-				$onglets = array_merge($onglets, $info['onglet']);
1017
-			}
1018
-			foreach ($contenu as $charge => $v) {
1019
-				// si pas declare/detecte a la lecture du paquet.xml,
1020
-				// detecer a nouveau ici puisque son ajout ne provoque pas une modif du paquet.xml
1021
-				// donc ni sa relecture, ni sa detection
1022
-				if (!isset($info[$charge])
1023
-					and $dir // exclure le cas du plugin "SPIP"
1024
-					and strpos($dir, ":") === false // exclure le cas des procure:
1025
-					and file_exists("$dir$plug/paquet.xml") // uniquement pour les paquet.xml
1026
-				) {
1027
-					if (is_readable("$dir$plug/" . ($file = $info['prefix'] . "_" . $charge . ".php"))) {
1028
-						$info[$charge] = array($file);
1029
-					}
1030
-				}
1031
-				if (isset($info[$charge])) {
1032
-					$files = $info[$charge];
1033
-					foreach ($files as $k => $file) {
1034
-						// on genere un if file_exists devant chaque include
1035
-						// pour pouvoir garder le meme niveau d'erreur general
1036
-						$file = trim($file);
1037
-						if (!is_readable("$dir$plug/$file")
1038
-							// uniquement pour les paquet.xml
1039
-							and file_exists("$dir$plug/paquet.xml")
1040
-						) {
1041
-							unset($info[$charge][$k]);
1042
-						} else {
1043
-							$_file = $root_dir_type . ".'$plug/$file'";
1044
-							$contenu[$charge] .= "include_once_check($_file);\n";
1045
-						}
1046
-					}
1047
-				}
1048
-			}
1049
-			$sign .= md5(serialize($info));
1050
-		}
1051
-	}
1052
-
1053
-	$contenu['options'] = "define('_PLUGINS_HASH','" . md5($sign) . "');\n" . $contenu['options'];
1054
-	$contenu['fonctions'] .= plugin_ongletbouton("boutons_plugins", $boutons)
1055
-		. plugin_ongletbouton("onglets_plugins", $onglets);
1056
-
1057
-	ecrire_fichier_php(_CACHE_PLUGINS_OPT, $contenu['options']);
1058
-	ecrire_fichier_php(_CACHE_PLUGINS_FCT, $contenu['fonctions']);
1000
+    $contenu = array('options' => '', 'fonctions' => '');
1001
+    $boutons = array();
1002
+    $onglets = array();
1003
+    $sign = "";
1004
+
1005
+    foreach ($ordre as $p => $info) {
1006
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
1007
+        if (isset($plugin_valides[$p])) {
1008
+            $dir_type = $plugin_valides[$p]['dir_type'];
1009
+            $plug = $plugin_valides[$p]['dir'];
1010
+            $dir = constant($dir_type);
1011
+            $root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1012
+            if ($info['menu']) {
1013
+                $boutons = array_merge($boutons, $info['menu']);
1014
+            }
1015
+            if ($info['onglet']) {
1016
+                $onglets = array_merge($onglets, $info['onglet']);
1017
+            }
1018
+            foreach ($contenu as $charge => $v) {
1019
+                // si pas declare/detecte a la lecture du paquet.xml,
1020
+                // detecer a nouveau ici puisque son ajout ne provoque pas une modif du paquet.xml
1021
+                // donc ni sa relecture, ni sa detection
1022
+                if (!isset($info[$charge])
1023
+                    and $dir // exclure le cas du plugin "SPIP"
1024
+                    and strpos($dir, ":") === false // exclure le cas des procure:
1025
+                    and file_exists("$dir$plug/paquet.xml") // uniquement pour les paquet.xml
1026
+                ) {
1027
+                    if (is_readable("$dir$plug/" . ($file = $info['prefix'] . "_" . $charge . ".php"))) {
1028
+                        $info[$charge] = array($file);
1029
+                    }
1030
+                }
1031
+                if (isset($info[$charge])) {
1032
+                    $files = $info[$charge];
1033
+                    foreach ($files as $k => $file) {
1034
+                        // on genere un if file_exists devant chaque include
1035
+                        // pour pouvoir garder le meme niveau d'erreur general
1036
+                        $file = trim($file);
1037
+                        if (!is_readable("$dir$plug/$file")
1038
+                            // uniquement pour les paquet.xml
1039
+                            and file_exists("$dir$plug/paquet.xml")
1040
+                        ) {
1041
+                            unset($info[$charge][$k]);
1042
+                        } else {
1043
+                            $_file = $root_dir_type . ".'$plug/$file'";
1044
+                            $contenu[$charge] .= "include_once_check($_file);\n";
1045
+                        }
1046
+                    }
1047
+                }
1048
+            }
1049
+            $sign .= md5(serialize($info));
1050
+        }
1051
+    }
1052
+
1053
+    $contenu['options'] = "define('_PLUGINS_HASH','" . md5($sign) . "');\n" . $contenu['options'];
1054
+    $contenu['fonctions'] .= plugin_ongletbouton("boutons_plugins", $boutons)
1055
+        . plugin_ongletbouton("onglets_plugins", $onglets);
1056
+
1057
+    ecrire_fichier_php(_CACHE_PLUGINS_OPT, $contenu['options']);
1058
+    ecrire_fichier_php(_CACHE_PLUGINS_FCT, $contenu['fonctions']);
1059 1059
 }
1060 1060
 
1061 1061
 /**
@@ -1074,24 +1074,24 @@  discard block
 block discarded – undo
1074 1074
  * @return string Code php
1075 1075
  */
1076 1076
 function plugin_ongletbouton($nom, $val) {
1077
-	if (!$val) {
1078
-		$val = array();
1079
-	}
1080
-
1081
-	$val = serialize($val);
1082
-	$md5 = md5($val);
1083
-
1084
-	if (!defined("_UPDATED_$nom")) {
1085
-		define("_UPDATED_$nom", $val);
1086
-		define("_UPDATED_md5_$nom", $md5);
1087
-	}
1088
-	$val = "unserialize('" . str_replace("'", "\'", $val) . "')";
1089
-
1090
-	return
1091
-		"if (!function_exists('$nom')) {\n"
1092
-		. "function $nom(){return defined('_UPDATED_$nom')?unserialize(_UPDATED_$nom):$val;}\n"
1093
-		. "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'" . $md5 . "';}\n"
1094
-		. "}\n";
1077
+    if (!$val) {
1078
+        $val = array();
1079
+    }
1080
+
1081
+    $val = serialize($val);
1082
+    $md5 = md5($val);
1083
+
1084
+    if (!defined("_UPDATED_$nom")) {
1085
+        define("_UPDATED_$nom", $val);
1086
+        define("_UPDATED_md5_$nom", $md5);
1087
+    }
1088
+    $val = "unserialize('" . str_replace("'", "\'", $val) . "')";
1089
+
1090
+    return
1091
+        "if (!function_exists('$nom')) {\n"
1092
+        . "function $nom(){return defined('_UPDATED_$nom')?unserialize(_UPDATED_$nom):$val;}\n"
1093
+        . "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'" . $md5 . "';}\n"
1094
+        . "}\n";
1095 1095
 }
1096 1096
 
1097 1097
 /**
@@ -1106,15 +1106,15 @@  discard block
 block discarded – undo
1106 1106
 **/
1107 1107
 function plugins_amorcer_plugins_actifs() {
1108 1108
 
1109
-	if (@is_readable(_CACHE_PLUGINS_PATH)) {
1110
-		include_once(_CACHE_PLUGINS_PATH);
1111
-	} 
1109
+    if (@is_readable(_CACHE_PLUGINS_PATH)) {
1110
+        include_once(_CACHE_PLUGINS_PATH);
1111
+    } 
1112 1112
 
1113
-	if (@is_readable(_CACHE_PLUGINS_OPT)) {
1114
-		include_once(_CACHE_PLUGINS_OPT);
1115
-	} else {
1116
-		spip_log("pipelines desactives: impossible de produire " . _CACHE_PLUGINS_OPT);
1117
-	}
1113
+    if (@is_readable(_CACHE_PLUGINS_OPT)) {
1114
+        include_once(_CACHE_PLUGINS_OPT);
1115
+    } else {
1116
+        spip_log("pipelines desactives: impossible de produire " . _CACHE_PLUGINS_OPT);
1117
+    }
1118 1118
 }
1119 1119
 
1120 1120
 /**
@@ -1137,136 +1137,136 @@  discard block
 block discarded – undo
1137 1137
  *     Couples (nom du pipeline => Code PHP à insérer au début du pipeline)
1138 1138
 **/
1139 1139
 function pipeline_matrice_precompile($plugin_valides, $ordre, $pipe_recherche) {
1140
-	static $liste_pipe_manquants = array();
1141
-	if (($pipe_recherche) && (!in_array($pipe_recherche, $liste_pipe_manquants))) {
1142
-		$liste_pipe_manquants[] = $pipe_recherche;
1143
-	}
1144
-
1145
-	$prepend_code = array();
1146
-
1147
-	foreach ($ordre as $p => $info) {
1148
-		// $ordre peur contenir des plugins en attente et non valides pour ce hit
1149
-		if (isset($plugin_valides[$p])) {
1150
-			$dir_type = $plugin_valides[$p]['dir_type'];
1151
-			$root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1152
-			$plug = $plugin_valides[$p]['dir'];
1153
-			$prefix = (($info['prefix'] == "spip") ? "" : $info['prefix'] . "_");
1154
-			if (isset($info['pipeline']) and is_array($info['pipeline'])) {
1155
-				foreach ($info['pipeline'] as $pipe) {
1156
-					$nom = $pipe['nom'];
1157
-					if (isset($pipe['action'])) {
1158
-						$action = $pipe['action'];
1159
-					} else {
1160
-						$action = $nom;
1161
-					}
1162
-					$nomlower = strtolower($nom);
1163
-					if ($nomlower != $nom
1164
-						and isset($GLOBALS['spip_pipeline'][$nom])
1165
-						and !isset($GLOBALS['spip_pipeline'][$nomlower])
1166
-					) {
1167
-						$GLOBALS['spip_pipeline'][$nomlower] = $GLOBALS['spip_pipeline'][$nom];
1168
-						unset($GLOBALS['spip_pipeline'][$nom]);
1169
-					}
1170
-					$nom = $nomlower;
1171
-					// une action vide est une declaration qui ne doit pas etre compilee !
1172
-					if (!isset($GLOBALS['spip_pipeline'][$nom])) // creer le pipeline eventuel
1173
-					{
1174
-						$GLOBALS['spip_pipeline'][$nom] = "";
1175
-					}
1176
-					if ($action) {
1177
-						if (strpos($GLOBALS['spip_pipeline'][$nom], "|$prefix$action") === false) {
1178
-							$GLOBALS['spip_pipeline'][$nom] = preg_replace(",(\|\||$),", "|$prefix$action\\1",
1179
-								$GLOBALS['spip_pipeline'][$nom], 1);
1180
-						}
1181
-						if (isset($pipe['inclure'])) {
1182
-							$GLOBALS['spip_matrice']["$prefix$action"] =
1183
-								"$root_dir_type:$plug/" . $pipe['inclure'];
1184
-						}
1185
-					}
1186
-				}
1187
-			}
1188
-			if (isset($info['genie']) and count($info['genie'])) {
1189
-				if (!isset($prepend_code['taches_generales_cron'])) {
1190
-					$prepend_code['taches_generales_cron'] = "";
1191
-				}
1192
-				foreach ($info['genie'] as $genie) {
1193
-					$nom = $prefix . $genie['nom'];
1194
-					$periode = max(60, intval($genie['periode']));
1195
-					if (charger_fonction($nom, "genie", true)) {
1196
-						$prepend_code['taches_generales_cron'] .= "\$val['$nom'] = $periode;\n";
1197
-					} else {
1198
-						spip_log("Fonction genie_$nom introuvable", _LOG_ERREUR);
1199
-					}
1200
-				}
1201
-			}
1202
-			if (isset($info['style']) and count($info['style'])) {
1203
-				if (!isset($prepend_code['insert_head_css'])) {
1204
-					$prepend_code['insert_head_css'] = "";
1205
-				}
1206
-				if (!isset($prepend_code['header_prive_css'])) {
1207
-					$prepend_code['header_prive_css'] = "";
1208
-				}
1209
-				foreach ($info['style'] as $style) {
1210
-					if (isset($style['path']) and $style['path']) {
1211
-						$code = "if (\$f=timestamp(direction_css(find_in_path('" . addslashes($style['path']) . "')))) ";
1212
-					} else {
1213
-						$code = "if (\$f='" . addslashes($style['url']) . "') ";
1214
-					}
1215
-					$code .= "\$val .= '<link rel=\"stylesheet\" href=\"'.\$f.'\" type=\"text/css\"";
1216
-					if (isset($style['media']) and strlen($style['media'])) {
1217
-						$code .= " media=\"" . addslashes($style['media']) . "\"";
1218
-					}
1219
-					$code .= "/>';\n";
1220
-					if ($style['type'] != 'prive') {
1221
-						$prepend_code['insert_head_css'] .= $code;
1222
-					}
1223
-					if ($style['type'] != 'public') {
1224
-						$prepend_code['header_prive_css'] .= $code;
1225
-					}
1226
-				}
1227
-			}
1228
-			if (!isset($prepend_code['insert_head'])) {
1229
-				$prepend_code['insert_head'] = "";
1230
-			}
1231
-			if (!isset($prepend_code['header_prive'])) {
1232
-				$prepend_code['header_prive'] = "";
1233
-			}
1234
-			if (isset($info['script']) and count($info['script'])) {
1235
-				foreach ($info['script'] as $script) {
1236
-					if (isset($script['path']) and $script['path']) {
1237
-						$code = "if (\$f=timestamp(find_in_path('" . addslashes($script['path']) . "'))) ";
1238
-					} else {
1239
-						$code = "if (\$f='" . addslashes($script['url']) . "') ";
1240
-					}
1241
-					$code .= "\$val .= '<script src=\"'.\$f.'\" type=\"text/javascript\"></script>';\n";
1242
-					if ($script['type'] != 'prive') {
1243
-						$prepend_code['insert_head'] .= $code;
1244
-					}
1245
-					if ($script['type'] != 'public') {
1246
-						$prepend_code['header_prive'] .= $code;
1247
-					}
1248
-				}
1249
-			}
1250
-		}
1251
-	}
1252
-
1253
-	$prepend_code['insert_head'] =
1254
-		"include_once_check(_DIR_RESTREINT . 'inc/pipelines.php');\n"
1255
-		. "\$val = minipipe('f_jQuery', \$val);\n"
1256
-		. $prepend_code['insert_head'];
1257
-	$prepend_code['header_prive'] =
1258
-		"include_once_check(_DIR_RESTREINT . 'inc/pipelines_ecrire.php');\n"
1259
-		. "\$val = minipipe('f_jQuery_prive', \$val);\n"
1260
-		. $prepend_code['header_prive'];
1261
-
1262
-	// on ajoute les pipe qui ont ete recenses manquants
1263
-	foreach ($liste_pipe_manquants as $add_pipe) {
1264
-		if (!isset($GLOBALS['spip_pipeline'][$add_pipe])) {
1265
-			$GLOBALS['spip_pipeline'][$add_pipe] = '';
1266
-		}
1267
-	}
1268
-
1269
-	return $prepend_code;
1140
+    static $liste_pipe_manquants = array();
1141
+    if (($pipe_recherche) && (!in_array($pipe_recherche, $liste_pipe_manquants))) {
1142
+        $liste_pipe_manquants[] = $pipe_recherche;
1143
+    }
1144
+
1145
+    $prepend_code = array();
1146
+
1147
+    foreach ($ordre as $p => $info) {
1148
+        // $ordre peur contenir des plugins en attente et non valides pour ce hit
1149
+        if (isset($plugin_valides[$p])) {
1150
+            $dir_type = $plugin_valides[$p]['dir_type'];
1151
+            $root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1152
+            $plug = $plugin_valides[$p]['dir'];
1153
+            $prefix = (($info['prefix'] == "spip") ? "" : $info['prefix'] . "_");
1154
+            if (isset($info['pipeline']) and is_array($info['pipeline'])) {
1155
+                foreach ($info['pipeline'] as $pipe) {
1156
+                    $nom = $pipe['nom'];
1157
+                    if (isset($pipe['action'])) {
1158
+                        $action = $pipe['action'];
1159
+                    } else {
1160
+                        $action = $nom;
1161
+                    }
1162
+                    $nomlower = strtolower($nom);
1163
+                    if ($nomlower != $nom
1164
+                        and isset($GLOBALS['spip_pipeline'][$nom])
1165
+                        and !isset($GLOBALS['spip_pipeline'][$nomlower])
1166
+                    ) {
1167
+                        $GLOBALS['spip_pipeline'][$nomlower] = $GLOBALS['spip_pipeline'][$nom];
1168
+                        unset($GLOBALS['spip_pipeline'][$nom]);
1169
+                    }
1170
+                    $nom = $nomlower;
1171
+                    // une action vide est une declaration qui ne doit pas etre compilee !
1172
+                    if (!isset($GLOBALS['spip_pipeline'][$nom])) // creer le pipeline eventuel
1173
+                    {
1174
+                        $GLOBALS['spip_pipeline'][$nom] = "";
1175
+                    }
1176
+                    if ($action) {
1177
+                        if (strpos($GLOBALS['spip_pipeline'][$nom], "|$prefix$action") === false) {
1178
+                            $GLOBALS['spip_pipeline'][$nom] = preg_replace(",(\|\||$),", "|$prefix$action\\1",
1179
+                                $GLOBALS['spip_pipeline'][$nom], 1);
1180
+                        }
1181
+                        if (isset($pipe['inclure'])) {
1182
+                            $GLOBALS['spip_matrice']["$prefix$action"] =
1183
+                                "$root_dir_type:$plug/" . $pipe['inclure'];
1184
+                        }
1185
+                    }
1186
+                }
1187
+            }
1188
+            if (isset($info['genie']) and count($info['genie'])) {
1189
+                if (!isset($prepend_code['taches_generales_cron'])) {
1190
+                    $prepend_code['taches_generales_cron'] = "";
1191
+                }
1192
+                foreach ($info['genie'] as $genie) {
1193
+                    $nom = $prefix . $genie['nom'];
1194
+                    $periode = max(60, intval($genie['periode']));
1195
+                    if (charger_fonction($nom, "genie", true)) {
1196
+                        $prepend_code['taches_generales_cron'] .= "\$val['$nom'] = $periode;\n";
1197
+                    } else {
1198
+                        spip_log("Fonction genie_$nom introuvable", _LOG_ERREUR);
1199
+                    }
1200
+                }
1201
+            }
1202
+            if (isset($info['style']) and count($info['style'])) {
1203
+                if (!isset($prepend_code['insert_head_css'])) {
1204
+                    $prepend_code['insert_head_css'] = "";
1205
+                }
1206
+                if (!isset($prepend_code['header_prive_css'])) {
1207
+                    $prepend_code['header_prive_css'] = "";
1208
+                }
1209
+                foreach ($info['style'] as $style) {
1210
+                    if (isset($style['path']) and $style['path']) {
1211
+                        $code = "if (\$f=timestamp(direction_css(find_in_path('" . addslashes($style['path']) . "')))) ";
1212
+                    } else {
1213
+                        $code = "if (\$f='" . addslashes($style['url']) . "') ";
1214
+                    }
1215
+                    $code .= "\$val .= '<link rel=\"stylesheet\" href=\"'.\$f.'\" type=\"text/css\"";
1216
+                    if (isset($style['media']) and strlen($style['media'])) {
1217
+                        $code .= " media=\"" . addslashes($style['media']) . "\"";
1218
+                    }
1219
+                    $code .= "/>';\n";
1220
+                    if ($style['type'] != 'prive') {
1221
+                        $prepend_code['insert_head_css'] .= $code;
1222
+                    }
1223
+                    if ($style['type'] != 'public') {
1224
+                        $prepend_code['header_prive_css'] .= $code;
1225
+                    }
1226
+                }
1227
+            }
1228
+            if (!isset($prepend_code['insert_head'])) {
1229
+                $prepend_code['insert_head'] = "";
1230
+            }
1231
+            if (!isset($prepend_code['header_prive'])) {
1232
+                $prepend_code['header_prive'] = "";
1233
+            }
1234
+            if (isset($info['script']) and count($info['script'])) {
1235
+                foreach ($info['script'] as $script) {
1236
+                    if (isset($script['path']) and $script['path']) {
1237
+                        $code = "if (\$f=timestamp(find_in_path('" . addslashes($script['path']) . "'))) ";
1238
+                    } else {
1239
+                        $code = "if (\$f='" . addslashes($script['url']) . "') ";
1240
+                    }
1241
+                    $code .= "\$val .= '<script src=\"'.\$f.'\" type=\"text/javascript\"></script>';\n";
1242
+                    if ($script['type'] != 'prive') {
1243
+                        $prepend_code['insert_head'] .= $code;
1244
+                    }
1245
+                    if ($script['type'] != 'public') {
1246
+                        $prepend_code['header_prive'] .= $code;
1247
+                    }
1248
+                }
1249
+            }
1250
+        }
1251
+    }
1252
+
1253
+    $prepend_code['insert_head'] =
1254
+        "include_once_check(_DIR_RESTREINT . 'inc/pipelines.php');\n"
1255
+        . "\$val = minipipe('f_jQuery', \$val);\n"
1256
+        . $prepend_code['insert_head'];
1257
+    $prepend_code['header_prive'] =
1258
+        "include_once_check(_DIR_RESTREINT . 'inc/pipelines_ecrire.php');\n"
1259
+        . "\$val = minipipe('f_jQuery_prive', \$val);\n"
1260
+        . $prepend_code['header_prive'];
1261
+
1262
+    // on ajoute les pipe qui ont ete recenses manquants
1263
+    foreach ($liste_pipe_manquants as $add_pipe) {
1264
+        if (!isset($GLOBALS['spip_pipeline'][$add_pipe])) {
1265
+            $GLOBALS['spip_pipeline'][$add_pipe] = '';
1266
+        }
1267
+    }
1268
+
1269
+    return $prepend_code;
1270 1270
 }
1271 1271
 
1272 1272
 /**
@@ -1293,62 +1293,62 @@  discard block
 block discarded – undo
1293 1293
 **/
1294 1294
 function pipeline_precompile($prepend_code = array()) {
1295 1295
 
1296
-	$all_pipes = $all_pipes_end = '';
1297
-	if (!empty($GLOBALS['spip_pipeline']['all'])) {
1298
-		$a = explode('||', $GLOBALS['spip_pipeline']['all'], 2);
1299
-		unset($GLOBALS['spip_pipeline']['all']);
1300
-		$all_pipes = trim(array_shift($a));
1301
-		if ($all_pipes) {
1302
-			$all_pipes = '|' . ltrim($all_pipes, '|');
1303
-		}
1304
-		if (count($a)) {
1305
-			$all_pipes_end = '||' . array_shift($a);
1306
-		}
1307
-	}
1308
-	$content = "";
1309
-	foreach ($GLOBALS['spip_pipeline'] as $action => $pipeline) {
1310
-		$s_inc = "";
1311
-		$s_call = "";
1312
-		if ($all_pipes) {
1313
-			$pipeline = preg_replace(",(\|\||$),", "$all_pipes\\1", $pipeline, 1);
1314
-		}
1315
-		if ($all_pipes_end) {
1316
-			$pipeline .= $all_pipes_end;
1317
-		}
1318
-		$pipe = array_filter(explode('|', $pipeline));
1319
-		// Eclater le pipeline en filtres et appliquer chaque filtre
1320
-		foreach ($pipe as $fonc) {
1321
-			$fonc = trim($fonc);
1322
-			$s_call .= '$val = minipipe(\'' . $fonc . '\', $val);' . "\n";
1323
-			if (isset($GLOBALS['spip_matrice'][$fonc])) {
1324
-				$file = $GLOBALS['spip_matrice'][$fonc];
1325
-				$file = "'$file'";
1326
-				// si un _DIR_XXX: est dans la chaine, on extrait la constante
1327
-				if (preg_match(",(_(DIR|ROOT)_[A-Z_]+):,Ums", $file, $regs)) {
1328
-					$dir = $regs[1];
1329
-					$root_dir = str_replace('_DIR_', '_ROOT_', $dir);
1330
-					if (defined($root_dir)) {
1331
-						$dir = $root_dir;
1332
-					}
1333
-					$file = str_replace($regs[0], "'." . $dir . ".'", $file);
1334
-					$file = str_replace("''.", "", $file);
1335
-					$file = str_replace(constant($dir), '', $file);
1336
-				}
1337
-				$s_inc .= "include_once_check($file);\n";
1338
-			}
1339
-		}
1340
-		if (strlen($s_inc)) {
1341
-			$s_inc = "static \$inc=null;\nif (!\$inc){\n$s_inc\$inc=true;\n}\n";
1342
-		}
1343
-		$content .= "// Pipeline $action \n"
1344
-			. "function execute_pipeline_$action(&\$val){\n"
1345
-			. $s_inc
1346
-			. ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action]) . "\n" : '')
1347
-			. $s_call
1348
-			. "return \$val;\n}\n";
1349
-	}
1350
-	ecrire_fichier_php(_CACHE_PIPELINES, $content);
1351
-	clear_path_cache();
1296
+    $all_pipes = $all_pipes_end = '';
1297
+    if (!empty($GLOBALS['spip_pipeline']['all'])) {
1298
+        $a = explode('||', $GLOBALS['spip_pipeline']['all'], 2);
1299
+        unset($GLOBALS['spip_pipeline']['all']);
1300
+        $all_pipes = trim(array_shift($a));
1301
+        if ($all_pipes) {
1302
+            $all_pipes = '|' . ltrim($all_pipes, '|');
1303
+        }
1304
+        if (count($a)) {
1305
+            $all_pipes_end = '||' . array_shift($a);
1306
+        }
1307
+    }
1308
+    $content = "";
1309
+    foreach ($GLOBALS['spip_pipeline'] as $action => $pipeline) {
1310
+        $s_inc = "";
1311
+        $s_call = "";
1312
+        if ($all_pipes) {
1313
+            $pipeline = preg_replace(",(\|\||$),", "$all_pipes\\1", $pipeline, 1);
1314
+        }
1315
+        if ($all_pipes_end) {
1316
+            $pipeline .= $all_pipes_end;
1317
+        }
1318
+        $pipe = array_filter(explode('|', $pipeline));
1319
+        // Eclater le pipeline en filtres et appliquer chaque filtre
1320
+        foreach ($pipe as $fonc) {
1321
+            $fonc = trim($fonc);
1322
+            $s_call .= '$val = minipipe(\'' . $fonc . '\', $val);' . "\n";
1323
+            if (isset($GLOBALS['spip_matrice'][$fonc])) {
1324
+                $file = $GLOBALS['spip_matrice'][$fonc];
1325
+                $file = "'$file'";
1326
+                // si un _DIR_XXX: est dans la chaine, on extrait la constante
1327
+                if (preg_match(",(_(DIR|ROOT)_[A-Z_]+):,Ums", $file, $regs)) {
1328
+                    $dir = $regs[1];
1329
+                    $root_dir = str_replace('_DIR_', '_ROOT_', $dir);
1330
+                    if (defined($root_dir)) {
1331
+                        $dir = $root_dir;
1332
+                    }
1333
+                    $file = str_replace($regs[0], "'." . $dir . ".'", $file);
1334
+                    $file = str_replace("''.", "", $file);
1335
+                    $file = str_replace(constant($dir), '', $file);
1336
+                }
1337
+                $s_inc .= "include_once_check($file);\n";
1338
+            }
1339
+        }
1340
+        if (strlen($s_inc)) {
1341
+            $s_inc = "static \$inc=null;\nif (!\$inc){\n$s_inc\$inc=true;\n}\n";
1342
+        }
1343
+        $content .= "// Pipeline $action \n"
1344
+            . "function execute_pipeline_$action(&\$val){\n"
1345
+            . $s_inc
1346
+            . ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action]) . "\n" : '')
1347
+            . $s_call
1348
+            . "return \$val;\n}\n";
1349
+    }
1350
+    ecrire_fichier_php(_CACHE_PIPELINES, $content);
1351
+    clear_path_cache();
1352 1352
 }
1353 1353
 
1354 1354
 
@@ -1361,12 +1361,12 @@  discard block
 block discarded – undo
1361 1361
  *     true si le plugin est actif, false sinon
1362 1362
 **/
1363 1363
 function plugin_est_installe($plug_path) {
1364
-	$plugin_installes = isset($GLOBALS['meta']['plugin_installes']) ? unserialize($GLOBALS['meta']['plugin_installes']) : array();
1365
-	if (!$plugin_installes) {
1366
-		return false;
1367
-	}
1364
+    $plugin_installes = isset($GLOBALS['meta']['plugin_installes']) ? unserialize($GLOBALS['meta']['plugin_installes']) : array();
1365
+    if (!$plugin_installes) {
1366
+        return false;
1367
+    }
1368 1368
 
1369
-	return in_array($plug_path, $plugin_installes);
1369
+    return in_array($plug_path, $plugin_installes);
1370 1370
 }
1371 1371
 
1372 1372
 
@@ -1379,37 +1379,37 @@  discard block
 block discarded – undo
1379 1379
  * @uses plugins_installer_dist()
1380 1380
  **/
1381 1381
 function plugin_installes_meta() {
1382
-	if (isset($GLOBALS['fichier_php_compile_recent'])) {
1383
-		// attendre eventuellement l'invalidation du cache opcode
1384
-		spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
1385
-	}
1386
-
1387
-	$installer_plugins = charger_fonction('installer', 'plugins');
1388
-	$meta_plug_installes = array();
1389
-	foreach (unserialize($GLOBALS['meta']['plugin']) as $prefix => $resume) {
1390
-		if ($plug = $resume['dir']) {
1391
-			$infos = $installer_plugins($plug, 'install', $resume['dir_type']);
1392
-			if ($infos) {
1393
-				if (!is_array($infos) or $infos['install_test'][0]) {
1394
-					$meta_plug_installes[] = $plug;
1395
-				}
1396
-				if (is_array($infos)) {
1397
-					list($ok, $trace) = $infos['install_test'];
1398
-					include_spip('inc/filtres_boites');
1399
-					echo "<div class='install-plugins svp_retour'>"
1400
-						. boite_ouvrir(_T('plugin_titre_installation', array('plugin' => typo($infos['nom']))),
1401
-							($ok ? 'success' : 'error'))
1402
-						. $trace
1403
-						. "<div class='result'>"
1404
-						. ($ok ? ((isset($infos['upgrade']) && $infos['upgrade']) ? _T("plugin_info_upgrade_ok") : _T("plugin_info_install_ok")) : _T("avis_operation_echec"))
1405
-						. "</div>"
1406
-						. boite_fermer()
1407
-						. "</div>";
1408
-				}
1409
-			}
1410
-		}
1411
-	}
1412
-	ecrire_meta('plugin_installes', serialize($meta_plug_installes), 'non');
1382
+    if (isset($GLOBALS['fichier_php_compile_recent'])) {
1383
+        // attendre eventuellement l'invalidation du cache opcode
1384
+        spip_attend_invalidation_opcode_cache($GLOBALS['fichier_php_compile_recent']);
1385
+    }
1386
+
1387
+    $installer_plugins = charger_fonction('installer', 'plugins');
1388
+    $meta_plug_installes = array();
1389
+    foreach (unserialize($GLOBALS['meta']['plugin']) as $prefix => $resume) {
1390
+        if ($plug = $resume['dir']) {
1391
+            $infos = $installer_plugins($plug, 'install', $resume['dir_type']);
1392
+            if ($infos) {
1393
+                if (!is_array($infos) or $infos['install_test'][0]) {
1394
+                    $meta_plug_installes[] = $plug;
1395
+                }
1396
+                if (is_array($infos)) {
1397
+                    list($ok, $trace) = $infos['install_test'];
1398
+                    include_spip('inc/filtres_boites');
1399
+                    echo "<div class='install-plugins svp_retour'>"
1400
+                        . boite_ouvrir(_T('plugin_titre_installation', array('plugin' => typo($infos['nom']))),
1401
+                            ($ok ? 'success' : 'error'))
1402
+                        . $trace
1403
+                        . "<div class='result'>"
1404
+                        . ($ok ? ((isset($infos['upgrade']) && $infos['upgrade']) ? _T("plugin_info_upgrade_ok") : _T("plugin_info_install_ok")) : _T("avis_operation_echec"))
1405
+                        . "</div>"
1406
+                        . boite_fermer()
1407
+                        . "</div>";
1408
+                }
1409
+            }
1410
+        }
1411
+    }
1412
+    ecrire_meta('plugin_installes', serialize($meta_plug_installes), 'non');
1413 1413
 }
1414 1414
 
1415 1415
 /**
@@ -1423,29 +1423,29 @@  discard block
 block discarded – undo
1423 1423
  *     Commentaire : code écrit en tout début de fichier, après la balise PHP ouvrante
1424 1424
 **/
1425 1425
 function ecrire_fichier_php($nom, $contenu, $comment = '') {
1426
-	if (!isset($GLOBALS['fichier_php_compile_recent'])) {
1427
-		$GLOBALS['fichier_php_compile_recent'] = 0;
1428
-	}
1429
-
1430
-	$contenu = '<' . '?php' . "\n" . $comment . "\nif (defined('_ECRIRE_INC_VERSION')) {\n" . $contenu . "}\n?" . '>';
1431
-	// si un fichier existe deja on verifie que son contenu change avant de l'ecraser
1432
-	// si pas de modif on ne touche pas au fichier initial
1433
-	if (file_exists($nom)) {
1434
-		if (substr($nom, -4) == '.php') {
1435
-			$fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1436
-		}
1437
-		else {
1438
-			$fichier_tmp = $nom . '.tmp';
1439
-		}
1440
-		file_put_contents($fichier_tmp, $contenu);
1441
-		if(md5_file($nom) == md5_file($fichier_tmp)) {
1442
-			$GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1443
-			@unlink($fichier_tmp);
1444
-			return;
1445
-		}
1446
-		@unlink($fichier_tmp);
1447
-	}
1448
-	ecrire_fichier($nom, $contenu);
1449
-	$GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1450
-	spip_clear_opcode_cache(realpath($nom));
1426
+    if (!isset($GLOBALS['fichier_php_compile_recent'])) {
1427
+        $GLOBALS['fichier_php_compile_recent'] = 0;
1428
+    }
1429
+
1430
+    $contenu = '<' . '?php' . "\n" . $comment . "\nif (defined('_ECRIRE_INC_VERSION')) {\n" . $contenu . "}\n?" . '>';
1431
+    // si un fichier existe deja on verifie que son contenu change avant de l'ecraser
1432
+    // si pas de modif on ne touche pas au fichier initial
1433
+    if (file_exists($nom)) {
1434
+        if (substr($nom, -4) == '.php') {
1435
+            $fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1436
+        }
1437
+        else {
1438
+            $fichier_tmp = $nom . '.tmp';
1439
+        }
1440
+        file_put_contents($fichier_tmp, $contenu);
1441
+        if(md5_file($nom) == md5_file($fichier_tmp)) {
1442
+            $GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1443
+            @unlink($fichier_tmp);
1444
+            return;
1445
+        }
1446
+        @unlink($fichier_tmp);
1447
+    }
1448
+    ecrire_fichier($nom, $contenu);
1449
+    $GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1450
+    spip_clear_opcode_cache(realpath($nom));
1451 1451
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 
23 23
 /** l'adresse du repertoire de telechargement et de decompactage des plugins */
24 24
 if (!defined('_DIR_PLUGINS_AUTO')) {
25
-	define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS . 'auto/');
25
+	define('_DIR_PLUGINS_AUTO', _DIR_PLUGINS.'auto/');
26 26
 }
27 27
 
28 28
 #include_spip('inc/texte'); // ????? Appelle public/parametrer trop tot avant la reconstruction du chemin des plugins.
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 				if ($dir) {
371 371
 					$dir .= "/";
372 372
 				}
373
-				$dir .= "procure:" . $procure['nom'];
373
+				$dir .= "procure:".$procure['nom'];
374 374
 
375 375
 				$procure['etat'] = '?';
376 376
 				$procure['dir_type'] = $resume['dir_type'];
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 		$plug = $resume['dir'];
552 552
 		$k = $infos[$dir_type][$plug];
553 553
 
554
-		$plug = constant($dir_type) . $plug;
554
+		$plug = constant($dir_type).$plug;
555 555
 		if (!isset($msg[$p])) {
556 556
 			if (isset($resume['erreur']) and $resume['erreur']) {
557 557
 				$msg[$p] = array($resume['erreur']);
@@ -594,10 +594,10 @@  discard block
 block discarded – undo
594 594
 		$list = $raw ? array() : $GLOBALS['meta']['plugin_erreur_activation'];
595 595
 	} elseif (!$raw) {
596 596
 		foreach ($list as $plug => $msg) {
597
-			$list[$plug] = "<li>" . _T('plugin_impossible_activer', array('plugin' => $plug))
598
-				. "<ul><li>" . implode("</li><li>", $msg) . "</li></ul></li>";
597
+			$list[$plug] = "<li>"._T('plugin_impossible_activer', array('plugin' => $plug))
598
+				. "<ul><li>".implode("</li><li>", $msg)."</li></ul></li>";
599 599
 		}
600
-		$list = "<ul>" . join("\n", $list) . "</ul>";
600
+		$list = "<ul>".join("\n", $list)."</ul>";
601 601
 	}
602 602
 	if ($raz) {
603 603
 		effacer_meta('plugin_erreur_activation');
@@ -711,13 +711,13 @@  discard block
 block discarded – undo
711 711
 			if ($minimum_inclus and spip_version_compare($version, $minimum, '<')) {
712 712
 				return _T("plugin_${balise}_${type}", array(
713 713
 					'plugin' => $nom,
714
-					'version' => ' &ge; ' . $minimum
714
+					'version' => ' &ge; '.$minimum
715 715
 				));
716 716
 			}
717 717
 			if (!$minimum_inclus and spip_version_compare($version, $minimum, '<=')) {
718 718
 				return _T("plugin_${balise}_${type}", array(
719 719
 					'plugin' => $nom,
720
-					'version' => ' &gt; ' . $minimum
720
+					'version' => ' &gt; '.$minimum
721 721
 				));
722 722
 			}
723 723
 		}
@@ -726,13 +726,13 @@  discard block
 block discarded – undo
726 726
 			if ($maximum_inclus and spip_version_compare($version, $maximum, '>')) {
727 727
 				return _T("plugin_${balise}_${type}", array(
728 728
 					'plugin' => $nom,
729
-					'version' => ' &le; ' . $maximum
729
+					'version' => ' &le; '.$maximum
730 730
 				));
731 731
 			}
732 732
 			if (!$maximum_inclus and spip_version_compare($version, $maximum, '>=')) {
733 733
 				return _T("plugin_${balise}_plugin", array(
734 734
 					'plugin' => $nom,
735
-					'version' => ' &lt; ' . $maximum
735
+					'version' => ' &lt; '.$maximum
736 736
 				));
737 737
 			}
738 738
 		}
@@ -751,7 +751,7 @@  discard block
 block discarded – undo
751 751
 		include_spip('inc/charger_plugin');
752 752
 		$url = '<br />'	. bouton_telechargement_plugin($url, 'lib');
753 753
 	}*/
754
-	return _T('plugin_necessite_lib', array('lib' => $lib)) . " <a href='$url'>$url</a>";
754
+	return _T('plugin_necessite_lib', array('lib' => $lib))." <a href='$url'>$url</a>";
755 755
 }
756 756
 
757 757
 
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
 	foreach ($plugin_valides as $p => $resume) {
851 851
 		// Les headers ne doivent pas indiquer les versions des extensions PHP, ni la version PHP
852 852
 		if (0 !== strpos($p, 'PHP:') and $p !== 'PHP') {
853
-			$header[] = $p . ($resume['version'] ? "(" . $resume['version'] . ")" : "");
853
+			$header[] = $p.($resume['version'] ? "(".$resume['version'].")" : "");
854 854
 		}
855 855
 		if ($resume['dir']) {
856 856
 			foreach ($infos[$resume['dir_type']][$resume['dir']]['lib'] as $l) {
@@ -874,10 +874,10 @@  discard block
 block discarded – undo
874 874
 	ecrire_meta('plugin_attente', serialize($liste));
875 875
 	$header = strtolower(implode(",", $header));
876 876
 	if (!isset($GLOBALS['spip_header_silencieux']) or !$GLOBALS['spip_header_silencieux']) {
877
-		ecrire_fichier(_DIR_VAR . "config.txt",
878
-			(defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : "Composed-By: SPIP") . ' ' . $GLOBALS['spip_version_affichee'] . " @ www.spip.net + " . $header);
877
+		ecrire_fichier(_DIR_VAR."config.txt",
878
+			(defined('_HEADER_COMPOSED_BY') ? _HEADER_COMPOSED_BY : "Composed-By: SPIP").' '.$GLOBALS['spip_version_affichee']." @ www.spip.net + ".$header);
879 879
 	} else {
880
-		@unlink(_DIR_VAR . "config.txt");
880
+		@unlink(_DIR_VAR."config.txt");
881 881
 	}
882 882
 	// generer charger_plugins_chemin.php
883 883
 	plugins_precompile_chemin($plugin_valides, $ordre);
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
 			// definir le plugin, donc le path avant l'include du fichier options
932 932
 			// permet de faire des include_spip pour attraper un inc_ du plugin
933 933
 
934
-			$dir = $dir_type . ".'" . $plug . "/'";
934
+			$dir = $dir_type.".'".$plug."/'";
935 935
 
936 936
 			$prefix = strtoupper(preg_replace(',\W,', '_', $info['prefix']));
937 937
 			if (
@@ -942,11 +942,11 @@  discard block
 block discarded – undo
942 942
 				if (!$info['chemin']) {
943 943
 					$chemins['public'][] = "_DIR_PLUGIN_$prefix";
944 944
 					$chemins['prive'][] = "_DIR_PLUGIN_$prefix";
945
-					if (is_dir(constant($dir_type) . $plug . '/squelettes/')) {
945
+					if (is_dir(constant($dir_type).$plug.'/squelettes/')) {
946 946
 						$chemins['public'][] = "_DIR_PLUGIN_{$prefix}.'squelettes/'";
947 947
 					}
948 948
 				}
949
-				else{
949
+				else {
950 950
 					foreach ($info['chemin'] as $chemin) {
951 951
 						if (!isset($chemin['version']) or plugin_version_compatible($chemin['version'],
952 952
 								$GLOBALS['spip_version_branche'], 'spip')
@@ -959,13 +959,13 @@  discard block
 block discarded – undo
959 959
 								$dir = '';
960 960
 							}
961 961
 							if (strlen($dir)) {
962
-								$dir = rtrim($dir, '/') . '/';
962
+								$dir = rtrim($dir, '/').'/';
963 963
 							}
964 964
 							if (!isset($chemin['type']) or $chemin['type'] == 'public') {
965
-								$chemins['public'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
965
+								$chemins['public'][] = "_DIR_PLUGIN_$prefix".(strlen($dir) ? ".'$dir'" : "");
966 966
 							}
967 967
 							if (!isset($chemin['type']) or $chemin['type'] == 'prive') {
968
-								$chemins['prive'][] = "_DIR_PLUGIN_$prefix" . (strlen($dir) ? ".'$dir'" : "");
968
+								$chemins['prive'][] = "_DIR_PLUGIN_$prefix".(strlen($dir) ? ".'$dir'" : "");
969 969
 							}
970 970
 						}
971 971
 					}
@@ -974,9 +974,9 @@  discard block
 block discarded – undo
974 974
 		}
975 975
 	}
976 976
 	if (count($chemins['public']) or count($chemins['prive'])) {
977
-		$contenu .= "if (_DIR_RESTREINT) _chemin([" . implode(',',
978
-				array_reverse($chemins['public'])) . "]);\n"
979
-			. "else _chemin([" . implode(',', array_reverse($chemins['prive'])) . "]);\n";
977
+		$contenu .= "if (_DIR_RESTREINT) _chemin([".implode(',',
978
+				array_reverse($chemins['public']))."]);\n"
979
+			. "else _chemin([".implode(',', array_reverse($chemins['prive']))."]);\n";
980 980
 	}
981 981
 
982 982
 	ecrire_fichier_php(_CACHE_PLUGINS_PATH, $contenu);
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
 					and strpos($dir, ":") === false // exclure le cas des procure:
1025 1025
 					and file_exists("$dir$plug/paquet.xml") // uniquement pour les paquet.xml
1026 1026
 				) {
1027
-					if (is_readable("$dir$plug/" . ($file = $info['prefix'] . "_" . $charge . ".php"))) {
1027
+					if (is_readable("$dir$plug/".($file = $info['prefix']."_".$charge.".php"))) {
1028 1028
 						$info[$charge] = array($file);
1029 1029
 					}
1030 1030
 				}
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 						) {
1041 1041
 							unset($info[$charge][$k]);
1042 1042
 						} else {
1043
-							$_file = $root_dir_type . ".'$plug/$file'";
1043
+							$_file = $root_dir_type.".'$plug/$file'";
1044 1044
 							$contenu[$charge] .= "include_once_check($_file);\n";
1045 1045
 						}
1046 1046
 					}
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
 		}
1051 1051
 	}
1052 1052
 
1053
-	$contenu['options'] = "define('_PLUGINS_HASH','" . md5($sign) . "');\n" . $contenu['options'];
1053
+	$contenu['options'] = "define('_PLUGINS_HASH','".md5($sign)."');\n".$contenu['options'];
1054 1054
 	$contenu['fonctions'] .= plugin_ongletbouton("boutons_plugins", $boutons)
1055 1055
 		. plugin_ongletbouton("onglets_plugins", $onglets);
1056 1056
 
@@ -1085,12 +1085,12 @@  discard block
 block discarded – undo
1085 1085
 		define("_UPDATED_$nom", $val);
1086 1086
 		define("_UPDATED_md5_$nom", $md5);
1087 1087
 	}
1088
-	$val = "unserialize('" . str_replace("'", "\'", $val) . "')";
1088
+	$val = "unserialize('".str_replace("'", "\'", $val)."')";
1089 1089
 
1090 1090
 	return
1091 1091
 		"if (!function_exists('$nom')) {\n"
1092 1092
 		. "function $nom(){return defined('_UPDATED_$nom')?unserialize(_UPDATED_$nom):$val;}\n"
1093
-		. "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'" . $md5 . "';}\n"
1093
+		. "function md5_$nom(){return defined('_UPDATED_md5_$nom')?_UPDATED_md5_$nom:'".$md5."';}\n"
1094 1094
 		. "}\n";
1095 1095
 }
1096 1096
 
@@ -1113,7 +1113,7 @@  discard block
 block discarded – undo
1113 1113
 	if (@is_readable(_CACHE_PLUGINS_OPT)) {
1114 1114
 		include_once(_CACHE_PLUGINS_OPT);
1115 1115
 	} else {
1116
-		spip_log("pipelines desactives: impossible de produire " . _CACHE_PLUGINS_OPT);
1116
+		spip_log("pipelines desactives: impossible de produire "._CACHE_PLUGINS_OPT);
1117 1117
 	}
1118 1118
 }
1119 1119
 
@@ -1150,7 +1150,7 @@  discard block
 block discarded – undo
1150 1150
 			$dir_type = $plugin_valides[$p]['dir_type'];
1151 1151
 			$root_dir_type = str_replace('_DIR_', '_ROOT_', $dir_type);
1152 1152
 			$plug = $plugin_valides[$p]['dir'];
1153
-			$prefix = (($info['prefix'] == "spip") ? "" : $info['prefix'] . "_");
1153
+			$prefix = (($info['prefix'] == "spip") ? "" : $info['prefix']."_");
1154 1154
 			if (isset($info['pipeline']) and is_array($info['pipeline'])) {
1155 1155
 				foreach ($info['pipeline'] as $pipe) {
1156 1156
 					$nom = $pipe['nom'];
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
 						}
1181 1181
 						if (isset($pipe['inclure'])) {
1182 1182
 							$GLOBALS['spip_matrice']["$prefix$action"] =
1183
-								"$root_dir_type:$plug/" . $pipe['inclure'];
1183
+								"$root_dir_type:$plug/".$pipe['inclure'];
1184 1184
 						}
1185 1185
 					}
1186 1186
 				}
@@ -1190,7 +1190,7 @@  discard block
 block discarded – undo
1190 1190
 					$prepend_code['taches_generales_cron'] = "";
1191 1191
 				}
1192 1192
 				foreach ($info['genie'] as $genie) {
1193
-					$nom = $prefix . $genie['nom'];
1193
+					$nom = $prefix.$genie['nom'];
1194 1194
 					$periode = max(60, intval($genie['periode']));
1195 1195
 					if (charger_fonction($nom, "genie", true)) {
1196 1196
 						$prepend_code['taches_generales_cron'] .= "\$val['$nom'] = $periode;\n";
@@ -1208,13 +1208,13 @@  discard block
 block discarded – undo
1208 1208
 				}
1209 1209
 				foreach ($info['style'] as $style) {
1210 1210
 					if (isset($style['path']) and $style['path']) {
1211
-						$code = "if (\$f=timestamp(direction_css(find_in_path('" . addslashes($style['path']) . "')))) ";
1211
+						$code = "if (\$f=timestamp(direction_css(find_in_path('".addslashes($style['path'])."')))) ";
1212 1212
 					} else {
1213
-						$code = "if (\$f='" . addslashes($style['url']) . "') ";
1213
+						$code = "if (\$f='".addslashes($style['url'])."') ";
1214 1214
 					}
1215 1215
 					$code .= "\$val .= '<link rel=\"stylesheet\" href=\"'.\$f.'\" type=\"text/css\"";
1216 1216
 					if (isset($style['media']) and strlen($style['media'])) {
1217
-						$code .= " media=\"" . addslashes($style['media']) . "\"";
1217
+						$code .= " media=\"".addslashes($style['media'])."\"";
1218 1218
 					}
1219 1219
 					$code .= "/>';\n";
1220 1220
 					if ($style['type'] != 'prive') {
@@ -1234,9 +1234,9 @@  discard block
 block discarded – undo
1234 1234
 			if (isset($info['script']) and count($info['script'])) {
1235 1235
 				foreach ($info['script'] as $script) {
1236 1236
 					if (isset($script['path']) and $script['path']) {
1237
-						$code = "if (\$f=timestamp(find_in_path('" . addslashes($script['path']) . "'))) ";
1237
+						$code = "if (\$f=timestamp(find_in_path('".addslashes($script['path'])."'))) ";
1238 1238
 					} else {
1239
-						$code = "if (\$f='" . addslashes($script['url']) . "') ";
1239
+						$code = "if (\$f='".addslashes($script['url'])."') ";
1240 1240
 					}
1241 1241
 					$code .= "\$val .= '<script src=\"'.\$f.'\" type=\"text/javascript\"></script>';\n";
1242 1242
 					if ($script['type'] != 'prive') {
@@ -1299,10 +1299,10 @@  discard block
 block discarded – undo
1299 1299
 		unset($GLOBALS['spip_pipeline']['all']);
1300 1300
 		$all_pipes = trim(array_shift($a));
1301 1301
 		if ($all_pipes) {
1302
-			$all_pipes = '|' . ltrim($all_pipes, '|');
1302
+			$all_pipes = '|'.ltrim($all_pipes, '|');
1303 1303
 		}
1304 1304
 		if (count($a)) {
1305
-			$all_pipes_end = '||' . array_shift($a);
1305
+			$all_pipes_end = '||'.array_shift($a);
1306 1306
 		}
1307 1307
 	}
1308 1308
 	$content = "";
@@ -1319,7 +1319,7 @@  discard block
 block discarded – undo
1319 1319
 		// Eclater le pipeline en filtres et appliquer chaque filtre
1320 1320
 		foreach ($pipe as $fonc) {
1321 1321
 			$fonc = trim($fonc);
1322
-			$s_call .= '$val = minipipe(\'' . $fonc . '\', $val);' . "\n";
1322
+			$s_call .= '$val = minipipe(\''.$fonc.'\', $val);'."\n";
1323 1323
 			if (isset($GLOBALS['spip_matrice'][$fonc])) {
1324 1324
 				$file = $GLOBALS['spip_matrice'][$fonc];
1325 1325
 				$file = "'$file'";
@@ -1330,7 +1330,7 @@  discard block
 block discarded – undo
1330 1330
 					if (defined($root_dir)) {
1331 1331
 						$dir = $root_dir;
1332 1332
 					}
1333
-					$file = str_replace($regs[0], "'." . $dir . ".'", $file);
1333
+					$file = str_replace($regs[0], "'.".$dir.".'", $file);
1334 1334
 					$file = str_replace("''.", "", $file);
1335 1335
 					$file = str_replace(constant($dir), '', $file);
1336 1336
 				}
@@ -1343,7 +1343,7 @@  discard block
 block discarded – undo
1343 1343
 		$content .= "// Pipeline $action \n"
1344 1344
 			. "function execute_pipeline_$action(&\$val){\n"
1345 1345
 			. $s_inc
1346
-			. ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action]) . "\n" : '')
1346
+			. ((isset($prepend_code[$action]) and strlen($prepend_code[$action])) ? trim($prepend_code[$action])."\n" : '')
1347 1347
 			. $s_call
1348 1348
 			. "return \$val;\n}\n";
1349 1349
 	}
@@ -1427,18 +1427,18 @@  discard block
 block discarded – undo
1427 1427
 		$GLOBALS['fichier_php_compile_recent'] = 0;
1428 1428
 	}
1429 1429
 
1430
-	$contenu = '<' . '?php' . "\n" . $comment . "\nif (defined('_ECRIRE_INC_VERSION')) {\n" . $contenu . "}\n?" . '>';
1430
+	$contenu = '<'.'?php'."\n".$comment."\nif (defined('_ECRIRE_INC_VERSION')) {\n".$contenu."}\n?".'>';
1431 1431
 	// si un fichier existe deja on verifie que son contenu change avant de l'ecraser
1432 1432
 	// si pas de modif on ne touche pas au fichier initial
1433 1433
 	if (file_exists($nom)) {
1434 1434
 		if (substr($nom, -4) == '.php') {
1435
-			$fichier_tmp = substr($nom, 0, -4) . '.tmp.php';
1435
+			$fichier_tmp = substr($nom, 0, -4).'.tmp.php';
1436 1436
 		}
1437 1437
 		else {
1438
-			$fichier_tmp = $nom . '.tmp';
1438
+			$fichier_tmp = $nom.'.tmp';
1439 1439
 		}
1440 1440
 		file_put_contents($fichier_tmp, $contenu);
1441
-		if(md5_file($nom) == md5_file($fichier_tmp)) {
1441
+		if (md5_file($nom) == md5_file($fichier_tmp)) {
1442 1442
 			$GLOBALS['fichier_php_compile_recent'] = max($GLOBALS['fichier_php_compile_recent'], filemtime($nom));
1443 1443
 			@unlink($fichier_tmp);
1444 1444
 			return;
Please login to merge, or discard this patch.
ecrire/inc/prepare_recherche.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -165,7 +165,7 @@
 block discarded – undo
165 165
  * @param string $primary
166 166
  * @param array $rows
167 167
  * @param string $serveur
168
- * @return array
168
+ * @return string[]
169 169
  */
170 170
 function generer_select_where_explicites($table, $primary, $rows, $serveur) {
171 171
 	# calculer le {id_article IN()} et le {... as points}
Please login to merge, or discard this patch.
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  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
 include_spip('inc/rechercher');
24 24
 if (!defined('_DELAI_CACHE_resultats')) {
25
-	define('_DELAI_CACHE_resultats', 600);
25
+    define('_DELAI_CACHE_resultats', 600);
26 26
 }
27 27
 
28 28
 /**
@@ -49,111 +49,111 @@  discard block
 block discarded – undo
49 49
  * @return array
50 50
  */
51 51
 function inc_prepare_recherche_dist(
52
-	$recherche,
53
-	$table = 'articles',
54
-	$cond = false,
55
-	$serveur = '',
56
-	$modificateurs = array(),
57
-	$primary = ''
52
+    $recherche,
53
+    $table = 'articles',
54
+    $cond = false,
55
+    $serveur = '',
56
+    $modificateurs = array(),
57
+    $primary = ''
58 58
 ) {
59
-	static $cache = array();
60
-	$delai_fraicheur = min(_DELAI_CACHE_resultats,
61
-		time() - (isset($GLOBALS['meta']['derniere_modif']) ? $GLOBALS['meta']['derniere_modif'] : 0));
62
-
63
-	// si recherche n'est pas dans le contexte, on va prendre en globals
64
-	// ca permet de faire des inclure simple.
65
-	if (!isset($recherche) and isset($GLOBALS['recherche'])) {
66
-		$recherche = $GLOBALS['recherche'];
67
-	}
68
-
69
-	// traiter le cas {recherche?}
70
-	if ($cond and !strlen($recherche)) {
71
-		return array(
72
-			"0 as points" /* as points */, /* where */
73
-			''
74
-		);
75
-	}
76
-
77
-
78
-	$rechercher = false;
79
-
80
-	$where_resultat_recent = sql_date_proche('maj', (0 - ($delai_fraicheur + 100)), " SECOND");
81
-	if (!isset($cache[$serveur][$table][$recherche])) {
82
-		$hash_serv = ($serveur ? substr(md5($serveur), 0, 16) : '');
83
-		$hash = substr(md5($recherche . $table), 0, 16);
84
-		$where = "(resultats.recherche='$hash' AND resultats.table_objet=" . sql_quote($table) . " AND resultats.serveur='$hash_serv')";
85
-		$row = sql_fetsel('recherche', 'spip_resultats AS resultats',
86
-			$where . " AND $where_resultat_recent", '', '', '0,1');
87
-		if (!$row
88
-			or (defined('_VAR_MODE') and _VAR_MODE == 'recalcul')
89
-		) {
90
-			$rechercher = true;
91
-		}
92
-	}
93
-
94
-	// si on n'a pas encore traite les donnees dans une boucle precedente
95
-	if ($rechercher) {
96
-		//$tables = liste_des_champs();
97
-		$x = objet_type($table);
98
-		$points = recherche_en_base($recherche,
99
-			$x,
100
-			array(
101
-				'score' => true,
102
-				'toutvoir' => true,
103
-				'jointures' => true
104
-			),
105
-			$serveur);
106
-		// pas de résultat, pas de point
107
-		$points = isset($points[$x]) ? $points[$x] : array();
108
-
109
-		// permettre aux plugins de modifier le resultat
110
-		$points = pipeline('prepare_recherche', array(
111
-			'args' => array(
112
-				'type' => $x,
113
-				'recherche' => $recherche,
114
-				'serveur' => $serveur,
115
-				'modificateurs' => $modificateurs
116
-			),
117
-			'data' => $points
118
-		));
119
-
120
-		// supprimer les anciens resultats de cette recherche
121
-		// et les resultats trop vieux avec une marge
122
-		// pas de AS resultats dans un delete (mysql)
123
-		$whered = str_replace(array("resultats.recherche", "resultats.table_objet", "resultats.serveur"),
124
-			array("recherche", "table_objet", "serveur"), $where);
125
-
126
-		sql_delete('spip_resultats',
127
-			"NOT($where_resultat_recent) OR ($whered)");
128
-
129
-		// inserer les resultats dans la table de cache des resultats
130
-		if (count($points)) {
131
-			$tab_couples = array();
132
-			foreach ($points as $id => $p) {
133
-				$tab_couples[] = array(
134
-					'recherche' => $hash,
135
-					'id' => $id,
136
-					'points' => $p['score'],
137
-					'table_objet' => $table,
138
-					'serveur' => $hash_serv,
139
-				);
140
-			}
141
-			sql_insertq_multi('spip_resultats', $tab_couples, array());
142
-		}
143
-	}
144
-
145
-	if (!isset($cache[$serveur][$table][$recherche])) {
146
-		if (!$serveur) {
147
-			$cache[$serveur][$table][$recherche] = array("resultats.points AS points", $where);
148
-		} else {
149
-			if (sql_countsel('spip_resultats as resultats', $where)) {
150
-				$rows = sql_allfetsel('resultats.id,resultats.points', 'spip_resultats as resultats', $where);
151
-			}
152
-			$cache[$serveur][$table][$recherche] = generer_select_where_explicites($table, $primary, $rows, $serveur);
153
-		}
154
-	}
155
-
156
-	return $cache[$serveur][$table][$recherche];
59
+    static $cache = array();
60
+    $delai_fraicheur = min(_DELAI_CACHE_resultats,
61
+        time() - (isset($GLOBALS['meta']['derniere_modif']) ? $GLOBALS['meta']['derniere_modif'] : 0));
62
+
63
+    // si recherche n'est pas dans le contexte, on va prendre en globals
64
+    // ca permet de faire des inclure simple.
65
+    if (!isset($recherche) and isset($GLOBALS['recherche'])) {
66
+        $recherche = $GLOBALS['recherche'];
67
+    }
68
+
69
+    // traiter le cas {recherche?}
70
+    if ($cond and !strlen($recherche)) {
71
+        return array(
72
+            "0 as points" /* as points */, /* where */
73
+            ''
74
+        );
75
+    }
76
+
77
+
78
+    $rechercher = false;
79
+
80
+    $where_resultat_recent = sql_date_proche('maj', (0 - ($delai_fraicheur + 100)), " SECOND");
81
+    if (!isset($cache[$serveur][$table][$recherche])) {
82
+        $hash_serv = ($serveur ? substr(md5($serveur), 0, 16) : '');
83
+        $hash = substr(md5($recherche . $table), 0, 16);
84
+        $where = "(resultats.recherche='$hash' AND resultats.table_objet=" . sql_quote($table) . " AND resultats.serveur='$hash_serv')";
85
+        $row = sql_fetsel('recherche', 'spip_resultats AS resultats',
86
+            $where . " AND $where_resultat_recent", '', '', '0,1');
87
+        if (!$row
88
+            or (defined('_VAR_MODE') and _VAR_MODE == 'recalcul')
89
+        ) {
90
+            $rechercher = true;
91
+        }
92
+    }
93
+
94
+    // si on n'a pas encore traite les donnees dans une boucle precedente
95
+    if ($rechercher) {
96
+        //$tables = liste_des_champs();
97
+        $x = objet_type($table);
98
+        $points = recherche_en_base($recherche,
99
+            $x,
100
+            array(
101
+                'score' => true,
102
+                'toutvoir' => true,
103
+                'jointures' => true
104
+            ),
105
+            $serveur);
106
+        // pas de résultat, pas de point
107
+        $points = isset($points[$x]) ? $points[$x] : array();
108
+
109
+        // permettre aux plugins de modifier le resultat
110
+        $points = pipeline('prepare_recherche', array(
111
+            'args' => array(
112
+                'type' => $x,
113
+                'recherche' => $recherche,
114
+                'serveur' => $serveur,
115
+                'modificateurs' => $modificateurs
116
+            ),
117
+            'data' => $points
118
+        ));
119
+
120
+        // supprimer les anciens resultats de cette recherche
121
+        // et les resultats trop vieux avec une marge
122
+        // pas de AS resultats dans un delete (mysql)
123
+        $whered = str_replace(array("resultats.recherche", "resultats.table_objet", "resultats.serveur"),
124
+            array("recherche", "table_objet", "serveur"), $where);
125
+
126
+        sql_delete('spip_resultats',
127
+            "NOT($where_resultat_recent) OR ($whered)");
128
+
129
+        // inserer les resultats dans la table de cache des resultats
130
+        if (count($points)) {
131
+            $tab_couples = array();
132
+            foreach ($points as $id => $p) {
133
+                $tab_couples[] = array(
134
+                    'recherche' => $hash,
135
+                    'id' => $id,
136
+                    'points' => $p['score'],
137
+                    'table_objet' => $table,
138
+                    'serveur' => $hash_serv,
139
+                );
140
+            }
141
+            sql_insertq_multi('spip_resultats', $tab_couples, array());
142
+        }
143
+    }
144
+
145
+    if (!isset($cache[$serveur][$table][$recherche])) {
146
+        if (!$serveur) {
147
+            $cache[$serveur][$table][$recherche] = array("resultats.points AS points", $where);
148
+        } else {
149
+            if (sql_countsel('spip_resultats as resultats', $where)) {
150
+                $rows = sql_allfetsel('resultats.id,resultats.points', 'spip_resultats as resultats', $where);
151
+            }
152
+            $cache[$serveur][$table][$recherche] = generer_select_where_explicites($table, $primary, $rows, $serveur);
153
+        }
154
+    }
155
+
156
+    return $cache[$serveur][$table][$recherche];
157 157
 }
158 158
 
159 159
 
@@ -169,22 +169,22 @@  discard block
 block discarded – undo
169 169
  * @return array
170 170
  */
171 171
 function generer_select_where_explicites($table, $primary, $rows, $serveur) {
172
-	# calculer le {id_article IN()} et le {... as points}
173
-	if (!count($rows)) {
174
-		return array("''", "0=1");
175
-	} else {
176
-		$listes_ids = array();
177
-		$select = '0';
178
-		foreach ($rows as $r) {
179
-			$listes_ids[$r['points']][] = $r['id'];
180
-		}
181
-
182
-		foreach ($listes_ids as $p => $ids) {
183
-			$select .= "+$p*(" .
184
-				sql_in("$table.$primary", $ids, '', $serveur)
185
-				. ") ";
186
-		}
187
-
188
-		return array("$select AS points ", sql_in("$table.$primary", array_map('reset', $rows), '', $serveur));
189
-	}
172
+    # calculer le {id_article IN()} et le {... as points}
173
+    if (!count($rows)) {
174
+        return array("''", "0=1");
175
+    } else {
176
+        $listes_ids = array();
177
+        $select = '0';
178
+        foreach ($rows as $r) {
179
+            $listes_ids[$r['points']][] = $r['id'];
180
+        }
181
+
182
+        foreach ($listes_ids as $p => $ids) {
183
+            $select .= "+$p*(" .
184
+                sql_in("$table.$primary", $ids, '', $serveur)
185
+                . ") ";
186
+        }
187
+
188
+        return array("$select AS points ", sql_in("$table.$primary", array_map('reset', $rows), '', $serveur));
189
+    }
190 190
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -80,10 +80,10 @@  discard block
 block discarded – undo
80 80
 	$where_resultat_recent = sql_date_proche('maj', (0 - ($delai_fraicheur + 100)), " SECOND");
81 81
 	if (!isset($cache[$serveur][$table][$recherche])) {
82 82
 		$hash_serv = ($serveur ? substr(md5($serveur), 0, 16) : '');
83
-		$hash = substr(md5($recherche . $table), 0, 16);
84
-		$where = "(resultats.recherche='$hash' AND resultats.table_objet=" . sql_quote($table) . " AND resultats.serveur='$hash_serv')";
83
+		$hash = substr(md5($recherche.$table), 0, 16);
84
+		$where = "(resultats.recherche='$hash' AND resultats.table_objet=".sql_quote($table)." AND resultats.serveur='$hash_serv')";
85 85
 		$row = sql_fetsel('recherche', 'spip_resultats AS resultats',
86
-			$where . " AND $where_resultat_recent", '', '', '0,1');
86
+			$where." AND $where_resultat_recent", '', '', '0,1');
87 87
 		if (!$row
88 88
 			or (defined('_VAR_MODE') and _VAR_MODE == 'recalcul')
89 89
 		) {
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 		}
181 181
 
182 182
 		foreach ($listes_ids as $p => $ids) {
183
-			$select .= "+$p*(" .
183
+			$select .= "+$p*(".
184 184
 				sql_in("$table.$primary", $ids, '', $serveur)
185 185
 				. ") ";
186 186
 		}
Please login to merge, or discard this patch.
ecrire/inc/texte.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 /**
32 32
  * Raccourcis dépendant du sens de la langue
33 33
  *
34
- * @return array Tablea ('','')
34
+ * @return string[] Tablea ('','')
35 35
  */
36 36
 function definir_raccourcis_alineas() {
37 37
 	return array('', '');
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
  * Ne fait rien ici. Voir plugin Textwheel
355 355
  *
356 356
  * @param string $letexte
357
- * @param null $forcer
357
+ * @param boolean|null $forcer
358 358
  * @return string
359 359
  */
360 360
 function paragrapher($letexte, $forcer = true) {
Please login to merge, or discard this patch.
Indentation   +220 added lines, -220 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
 include_spip('inc/texte_mini');
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  * @return array Tablea ('','')
35 35
  */
36 36
 function definir_raccourcis_alineas() {
37
-	return array('', '');
37
+    return array('', '');
38 38
 }
39 39
 
40 40
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  * @return string
48 48
  */
49 49
 function traiter_tableau($bloc) {
50
-	return $bloc;
50
+    return $bloc;
51 51
 }
52 52
 
53 53
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
  * @return string
62 62
  */
63 63
 function traiter_listes($texte) {
64
-	return $texte;
64
+    return $texte;
65 65
 }
66 66
 
67 67
 /**
@@ -77,16 +77,16 @@  discard block
 block discarded – undo
77 77
  */
78 78
 function traiter_raccourcis($letexte) {
79 79
 
80
-	// Appeler les fonctions de pre_traitement
81
-	$letexte = pipeline('pre_propre', $letexte);
80
+    // Appeler les fonctions de pre_traitement
81
+    $letexte = pipeline('pre_propre', $letexte);
82 82
 
83
-	// APPELER ICI UN PIPELINE traiter_raccourcis ?
84
-	// $letexte = pipeline('traiter_raccourcis', $letexte);
83
+    // APPELER ICI UN PIPELINE traiter_raccourcis ?
84
+    // $letexte = pipeline('traiter_raccourcis', $letexte);
85 85
 
86
-	// Appeler les fonctions de post-traitement
87
-	$letexte = pipeline('post_propre', $letexte);
86
+    // Appeler les fonctions de post-traitement
87
+    $letexte = pipeline('post_propre', $letexte);
88 88
 
89
-	return $letexte;
89
+    return $letexte;
90 90
 }
91 91
 
92 92
 /*************************************************************************************************************************
@@ -102,19 +102,19 @@  discard block
 block discarded – undo
102 102
  * @return string
103 103
  */
104 104
 function echappe_js($t, $class = ' class = "echappe-js"') {
105
-	foreach (array('script', 'iframe') as $tag) {
106
-		if (stripos($t, "<$tag") !== false
107
-			and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
108
-		) {
109
-			foreach ($r as $regs) {
110
-				$t = str_replace($regs[0],
111
-					"<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
112
-					$t);
113
-			}
114
-		}
115
-	}
116
-
117
-	return $t;
105
+    foreach (array('script', 'iframe') as $tag) {
106
+        if (stripos($t, "<$tag") !== false
107
+            and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
108
+        ) {
109
+            foreach ($r as $regs) {
110
+                $t = str_replace($regs[0],
111
+                    "<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
112
+                    $t);
113
+            }
114
+        }
115
+    }
116
+
117
+    return $t;
118 118
 }
119 119
 
120 120
 
@@ -143,55 +143,55 @@  discard block
 block discarded – undo
143 143
  *     Code protégé
144 144
  **/
145 145
 function interdire_scripts($arg, $mode_filtre=null) {
146
-	// on memorise le resultat sur les arguments non triviaux
147
-	static $dejavu = array();
148
-
149
-	// Attention, si ce n'est pas une chaine, laisser intact
150
-	if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
151
-		return $arg;
152
-	}
153
-
154
-	if (is_null($mode_filtre) or !in_array($mode_filtre, array(-1, 0, 1))) {
155
-		$mode_filtre = $GLOBALS['filtrer_javascript'];
156
-	}
157
-
158
-	if (isset($dejavu[$mode_filtre][$arg])) {
159
-		return $dejavu[$mode_filtre][$arg];
160
-	}
161
-
162
-	// echapper les tags asp/php
163
-	$t = str_replace('<' . '%', '&lt;%', $arg);
164
-
165
-	// echapper le php
166
-	$t = str_replace('<' . '?', '&lt;?', $t);
167
-
168
-	// echapper le < script language=php >
169
-	$t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
170
-
171
-	// Pour le js, trois modes : parano (-1), prive (0), ok (1)
172
-	switch ($mode_filtre) {
173
-		case 0:
174
-			if (!_DIR_RESTREINT) {
175
-				$t = echappe_js($t);
176
-			}
177
-			break;
178
-		case -1:
179
-			$t = echappe_js($t);
180
-			break;
181
-	}
182
-
183
-	// pas de <base href /> svp !
184
-	$t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
185
-
186
-	// Reinserer les echappements des modeles
187
-	if (defined('_PROTEGE_JS_MODELES')) {
188
-		$t = echappe_retour($t, "javascript" . _PROTEGE_JS_MODELES);
189
-	}
190
-	if (defined('_PROTEGE_PHP_MODELES')) {
191
-		$t = echappe_retour($t, "php" . _PROTEGE_PHP_MODELES);
192
-	}
193
-
194
-	return $dejavu[$mode_filtre][$arg] = $t;
146
+    // on memorise le resultat sur les arguments non triviaux
147
+    static $dejavu = array();
148
+
149
+    // Attention, si ce n'est pas une chaine, laisser intact
150
+    if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
151
+        return $arg;
152
+    }
153
+
154
+    if (is_null($mode_filtre) or !in_array($mode_filtre, array(-1, 0, 1))) {
155
+        $mode_filtre = $GLOBALS['filtrer_javascript'];
156
+    }
157
+
158
+    if (isset($dejavu[$mode_filtre][$arg])) {
159
+        return $dejavu[$mode_filtre][$arg];
160
+    }
161
+
162
+    // echapper les tags asp/php
163
+    $t = str_replace('<' . '%', '&lt;%', $arg);
164
+
165
+    // echapper le php
166
+    $t = str_replace('<' . '?', '&lt;?', $t);
167
+
168
+    // echapper le < script language=php >
169
+    $t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
170
+
171
+    // Pour le js, trois modes : parano (-1), prive (0), ok (1)
172
+    switch ($mode_filtre) {
173
+        case 0:
174
+            if (!_DIR_RESTREINT) {
175
+                $t = echappe_js($t);
176
+            }
177
+            break;
178
+        case -1:
179
+            $t = echappe_js($t);
180
+            break;
181
+    }
182
+
183
+    // pas de <base href /> svp !
184
+    $t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
185
+
186
+    // Reinserer les echappements des modeles
187
+    if (defined('_PROTEGE_JS_MODELES')) {
188
+        $t = echappe_retour($t, "javascript" . _PROTEGE_JS_MODELES);
189
+    }
190
+    if (defined('_PROTEGE_PHP_MODELES')) {
191
+        $t = echappe_retour($t, "php" . _PROTEGE_PHP_MODELES);
192
+    }
193
+
194
+    return $dejavu[$mode_filtre][$arg] = $t;
195 195
 }
196 196
 
197 197
 
@@ -220,64 +220,64 @@  discard block
 block discarded – undo
220 220
  *     Texte transformé
221 221
  **/
222 222
 function typo($letexte, $echapper = true, $connect = null, $env = array()) {
223
-	// Plus vite !
224
-	if (!$letexte) {
225
-		return $letexte;
226
-	}
227
-
228
-	// les appels directs a cette fonction depuis le php de l'espace
229
-	// prive etant historiquement ecrit sans argment $connect
230
-	// on utilise la presence de celui-ci pour distinguer les cas
231
-	// ou il faut passer interdire_script explicitement
232
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
233
-	// ne seront pas perturbes
234
-	$interdire_script = false;
235
-	if (is_null($connect)) {
236
-		$connect = '';
237
-		$interdire_script = true;
238
-		$env['espace_prive'] = test_espace_prive();
239
-	}
240
-
241
-	// Echapper les codes <html> etc
242
-	if ($echapper) {
243
-		$letexte = echappe_html($letexte, 'TYPO');
244
-	}
245
-
246
-	//
247
-	// Installer les modeles, notamment images et documents ;
248
-	//
249
-	// NOTE : propre() ne passe pas par ici mais directement par corriger_typo
250
-	// cf. inc/lien
251
-
252
-	$letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect, null, $env);
253
-	if ($letexte != $mem) {
254
-		$echapper = true;
255
-	}
256
-	unset($mem);
257
-
258
-	$letexte = corriger_typo($letexte);
259
-	$letexte = echapper_faux_tags($letexte);
260
-
261
-	// reintegrer les echappements
262
-	if ($echapper) {
263
-		$letexte = echappe_retour($letexte, 'TYPO');
264
-	}
265
-
266
-	// Dans les appels directs hors squelette, securiser ici aussi
267
-	if ($interdire_script) {
268
-		$letexte = interdire_scripts($letexte);
269
-	}
270
-
271
-	// Dans l'espace prive on se mefie de tout contenu dangereux
272
-	// https://core.spip.net/issues/3371
273
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
274
-	// https://core.spip.net/issues/4166
275
-	if ($GLOBALS['filtrer_javascript'] == -1
276
-	  or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)) {
277
-		$letexte = echapper_html_suspect($letexte);
278
-	}
279
-
280
-	return $letexte;
223
+    // Plus vite !
224
+    if (!$letexte) {
225
+        return $letexte;
226
+    }
227
+
228
+    // les appels directs a cette fonction depuis le php de l'espace
229
+    // prive etant historiquement ecrit sans argment $connect
230
+    // on utilise la presence de celui-ci pour distinguer les cas
231
+    // ou il faut passer interdire_script explicitement
232
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
233
+    // ne seront pas perturbes
234
+    $interdire_script = false;
235
+    if (is_null($connect)) {
236
+        $connect = '';
237
+        $interdire_script = true;
238
+        $env['espace_prive'] = test_espace_prive();
239
+    }
240
+
241
+    // Echapper les codes <html> etc
242
+    if ($echapper) {
243
+        $letexte = echappe_html($letexte, 'TYPO');
244
+    }
245
+
246
+    //
247
+    // Installer les modeles, notamment images et documents ;
248
+    //
249
+    // NOTE : propre() ne passe pas par ici mais directement par corriger_typo
250
+    // cf. inc/lien
251
+
252
+    $letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect, null, $env);
253
+    if ($letexte != $mem) {
254
+        $echapper = true;
255
+    }
256
+    unset($mem);
257
+
258
+    $letexte = corriger_typo($letexte);
259
+    $letexte = echapper_faux_tags($letexte);
260
+
261
+    // reintegrer les echappements
262
+    if ($echapper) {
263
+        $letexte = echappe_retour($letexte, 'TYPO');
264
+    }
265
+
266
+    // Dans les appels directs hors squelette, securiser ici aussi
267
+    if ($interdire_script) {
268
+        $letexte = interdire_scripts($letexte);
269
+    }
270
+
271
+    // Dans l'espace prive on se mefie de tout contenu dangereux
272
+    // https://core.spip.net/issues/3371
273
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
274
+    // https://core.spip.net/issues/4166
275
+    if ($GLOBALS['filtrer_javascript'] == -1
276
+      or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)) {
277
+        $letexte = echapper_html_suspect($letexte);
278
+    }
279
+
280
+    return $letexte;
281 281
 }
282 282
 
283 283
 // Correcteur typographique
@@ -302,57 +302,57 @@  discard block
 block discarded – undo
302 302
  */
303 303
 function corriger_typo($letexte, $lang = '') {
304 304
 
305
-	// Plus vite !
306
-	if (!$letexte) {
307
-		return $letexte;
308
-	}
309
-
310
-	$letexte = pipeline('pre_typo', $letexte);
311
-
312
-	// Caracteres de controle "illegaux"
313
-	$letexte = corriger_caracteres($letexte);
314
-
315
-	// Proteger les caracteres typographiques a l'interieur des tags html
316
-	if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
317
-		foreach ($regs as $reg) {
318
-			$insert = $reg[0];
319
-			// hack: on transforme les caracteres a proteger en les remplacant
320
-			// par des caracteres "illegaux". (cf corriger_caracteres())
321
-			$insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
322
-			$letexte = str_replace($reg[0], $insert, $letexte);
323
-		}
324
-	}
325
-
326
-	// trouver les blocs idiomes et les traiter à part
327
-	$letexte = extraire_idiome($ei = $letexte, $lang, true);
328
-	$ei = ($ei !== $letexte);
329
-
330
-	// trouver les blocs multi et les traiter a part
331
-	$letexte = extraire_multi($em = $letexte, $lang, true);
332
-	$em = ($em !== $letexte);
333
-
334
-	// Charger & appliquer les fonctions de typographie
335
-	$typographie = charger_fonction(lang_typo($lang), 'typographie');
336
-	$letexte = $typographie($letexte);
337
-
338
-	// Les citations en une autre langue, s'il y a lieu
339
-	if ($em) {
340
-		$letexte = echappe_retour($letexte, 'multi');
341
-	}
342
-	if ($ei) {
343
-		$letexte = echappe_retour($letexte, 'idiome');
344
-	}
345
-
346
-	// Retablir les caracteres proteges
347
-	$letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
348
-
349
-	// pipeline
350
-	$letexte = pipeline('post_typo', $letexte);
351
-
352
-	# un message pour abs_url - on est passe en mode texte
353
-	$GLOBALS['mode_abs_url'] = 'texte';
354
-
355
-	return $letexte;
305
+    // Plus vite !
306
+    if (!$letexte) {
307
+        return $letexte;
308
+    }
309
+
310
+    $letexte = pipeline('pre_typo', $letexte);
311
+
312
+    // Caracteres de controle "illegaux"
313
+    $letexte = corriger_caracteres($letexte);
314
+
315
+    // Proteger les caracteres typographiques a l'interieur des tags html
316
+    if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
317
+        foreach ($regs as $reg) {
318
+            $insert = $reg[0];
319
+            // hack: on transforme les caracteres a proteger en les remplacant
320
+            // par des caracteres "illegaux". (cf corriger_caracteres())
321
+            $insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
322
+            $letexte = str_replace($reg[0], $insert, $letexte);
323
+        }
324
+    }
325
+
326
+    // trouver les blocs idiomes et les traiter à part
327
+    $letexte = extraire_idiome($ei = $letexte, $lang, true);
328
+    $ei = ($ei !== $letexte);
329
+
330
+    // trouver les blocs multi et les traiter a part
331
+    $letexte = extraire_multi($em = $letexte, $lang, true);
332
+    $em = ($em !== $letexte);
333
+
334
+    // Charger & appliquer les fonctions de typographie
335
+    $typographie = charger_fonction(lang_typo($lang), 'typographie');
336
+    $letexte = $typographie($letexte);
337
+
338
+    // Les citations en une autre langue, s'il y a lieu
339
+    if ($em) {
340
+        $letexte = echappe_retour($letexte, 'multi');
341
+    }
342
+    if ($ei) {
343
+        $letexte = echappe_retour($letexte, 'idiome');
344
+    }
345
+
346
+    // Retablir les caracteres proteges
347
+    $letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
348
+
349
+    // pipeline
350
+    $letexte = pipeline('post_typo', $letexte);
351
+
352
+    # un message pour abs_url - on est passe en mode texte
353
+    $GLOBALS['mode_abs_url'] = 'texte';
354
+
355
+    return $letexte;
356 356
 }
357 357
 
358 358
 
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
  * @return string
369 369
  */
370 370
 function paragrapher($letexte, $forcer = true) {
371
-	return $letexte;
371
+    return $letexte;
372 372
 }
373 373
 
374 374
 /**
@@ -380,11 +380,11 @@  discard block
 block discarded – undo
380 380
  * @return string Texte
381 381
  **/
382 382
 function traiter_retours_chariots($letexte) {
383
-	$letexte = preg_replace(",\r\n?,S", "\n", $letexte);
384
-	$letexte = preg_replace(",<p[>[:space:]],iS", "\n\n\\0", $letexte);
385
-	$letexte = preg_replace(",</p[>[:space:]],iS", "\\0\n\n", $letexte);
383
+    $letexte = preg_replace(",\r\n?,S", "\n", $letexte);
384
+    $letexte = preg_replace(",<p[>[:space:]],iS", "\n\n\\0", $letexte);
385
+    $letexte = preg_replace(",</p[>[:space:]],iS", "\\0\n\n", $letexte);
386 386
 
387
-	return $letexte;
387
+    return $letexte;
388 388
 }
389 389
 
390 390
 
@@ -410,37 +410,37 @@  discard block
 block discarded – undo
410 410
  *     Texte transformé
411 411
  **/
412 412
 function propre($t, $connect = null, $env = array()) {
413
-	// les appels directs a cette fonction depuis le php de l'espace
414
-	// prive etant historiquement ecrits sans argment $connect
415
-	// on utilise la presence de celui-ci pour distinguer les cas
416
-	// ou il faut passer interdire_script explicitement
417
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
418
-	// ne seront pas perturbes
419
-	$interdire_script = false;
420
-	if (is_null($connect)) {
421
-		$connect = '';
422
-		$interdire_script = true;
423
-	}
424
-
425
-	if (!$t) {
426
-		return strval($t);
427
-	}
428
-
429
-	// Dans l'espace prive on se mefie de tout contenu dangereux
430
-	// avant echappement des balises <html>
431
-	// https://core.spip.net/issues/3371
432
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
433
-	// https://core.spip.net/issues/4166
434
-	if ($interdire_script
435
-		or $GLOBALS['filtrer_javascript'] == -1
436
-		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)
437
-		or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript']<=0)) {
438
-		$t = echapper_html_suspect($t, false);
439
-	}
440
-	$t = echappe_html($t);
441
-	$t = expanser_liens($t, $connect, $env);
442
-	$t = traiter_raccourcis($t);
443
-	$t = echappe_retour_modeles($t, $interdire_script);
444
-
445
-	return $t;
413
+    // les appels directs a cette fonction depuis le php de l'espace
414
+    // prive etant historiquement ecrits sans argment $connect
415
+    // on utilise la presence de celui-ci pour distinguer les cas
416
+    // ou il faut passer interdire_script explicitement
417
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
418
+    // ne seront pas perturbes
419
+    $interdire_script = false;
420
+    if (is_null($connect)) {
421
+        $connect = '';
422
+        $interdire_script = true;
423
+    }
424
+
425
+    if (!$t) {
426
+        return strval($t);
427
+    }
428
+
429
+    // Dans l'espace prive on se mefie de tout contenu dangereux
430
+    // avant echappement des balises <html>
431
+    // https://core.spip.net/issues/3371
432
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
433
+    // https://core.spip.net/issues/4166
434
+    if ($interdire_script
435
+        or $GLOBALS['filtrer_javascript'] == -1
436
+        or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)
437
+        or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript']<=0)) {
438
+        $t = echapper_html_suspect($t, false);
439
+    }
440
+    $t = echappe_html($t);
441
+    $t = expanser_liens($t, $connect, $env);
442
+    $t = traiter_raccourcis($t);
443
+    $t = echappe_retour_modeles($t, $interdire_script);
444
+
445
+    return $t;
446 446
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -104,11 +104,11 @@  discard block
 block discarded – undo
104 104
 function echappe_js($t, $class = ' class = "echappe-js"') {
105 105
 	foreach (array('script', 'iframe') as $tag) {
106 106
 		if (stripos($t, "<$tag") !== false
107
-			and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
107
+			and preg_match_all(',<'.$tag.'.*?($|</'.$tag.'.),isS', $t, $r, PREG_SET_ORDER)
108 108
 		) {
109 109
 			foreach ($r as $regs) {
110 110
 				$t = str_replace($regs[0],
111
-					"<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
111
+					"<code$class>".nl2br(spip_htmlspecialchars($regs[0])).'</code>',
112 112
 					$t);
113 113
 			}
114 114
 		}
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
  * @return string
143 143
  *     Code protégé
144 144
  **/
145
-function interdire_scripts($arg, $mode_filtre=null) {
145
+function interdire_scripts($arg, $mode_filtre = null) {
146 146
 	// on memorise le resultat sur les arguments non triviaux
147 147
 	static $dejavu = array();
148 148
 
@@ -160,10 +160,10 @@  discard block
 block discarded – undo
160 160
 	}
161 161
 
162 162
 	// echapper les tags asp/php
163
-	$t = str_replace('<' . '%', '&lt;%', $arg);
163
+	$t = str_replace('<'.'%', '&lt;%', $arg);
164 164
 
165 165
 	// echapper le php
166
-	$t = str_replace('<' . '?', '&lt;?', $t);
166
+	$t = str_replace('<'.'?', '&lt;?', $t);
167 167
 
168 168
 	// echapper le < script language=php >
169 169
 	$t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
@@ -185,10 +185,10 @@  discard block
 block discarded – undo
185 185
 
186 186
 	// Reinserer les echappements des modeles
187 187
 	if (defined('_PROTEGE_JS_MODELES')) {
188
-		$t = echappe_retour($t, "javascript" . _PROTEGE_JS_MODELES);
188
+		$t = echappe_retour($t, "javascript"._PROTEGE_JS_MODELES);
189 189
 	}
190 190
 	if (defined('_PROTEGE_PHP_MODELES')) {
191
-		$t = echappe_retour($t, "php" . _PROTEGE_PHP_MODELES);
191
+		$t = echappe_retour($t, "php"._PROTEGE_PHP_MODELES);
192 192
 	}
193 193
 
194 194
 	return $dejavu[$mode_filtre][$arg] = $t;
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 	// et aussi dans l'espace public si la globale filtrer_javascript = -1
274 274
 	// https://core.spip.net/issues/4166
275 275
 	if ($GLOBALS['filtrer_javascript'] == -1
276
-	  or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)) {
276
+	  or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)) {
277 277
 		$letexte = echapper_html_suspect($letexte);
278 278
 	}
279 279
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 define('_TYPO_PROTEGER', "!':;?~%-");
285 285
 define('_TYPO_PROTECTEUR', "\x1\x2\x3\x4\x5\x6\x7\x8");
286 286
 
287
-define('_TYPO_BALISE', ",</?[a-z!][^<>]*[" . preg_quote(_TYPO_PROTEGER) . "][^<>]*>,imsS");
287
+define('_TYPO_BALISE', ",</?[a-z!][^<>]*[".preg_quote(_TYPO_PROTEGER)."][^<>]*>,imsS");
288 288
 
289 289
 /**
290 290
  * Corrige la typographie
@@ -433,8 +433,8 @@  discard block
 block discarded – undo
433 433
 	// https://core.spip.net/issues/4166
434 434
 	if ($interdire_script
435 435
 		or $GLOBALS['filtrer_javascript'] == -1
436
-		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript']<=0)
437
-		or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript']<=0)) {
436
+		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
437
+		or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript'] <= 0)) {
438 438
 		$t = echapper_html_suspect($t, false);
439 439
 	}
440 440
 	$t = echappe_html($t);
Please login to merge, or discard this patch.
ecrire/inc/xml.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@
 block discarded – undo
245 245
  * @param array $matches
246 246
  *     Branches de l'arbre validant la rexgep
247 247
  * @param bool $init ?
248
- * @return bool
248
+ * @return integer
249 249
  *     false si aucun élément ne valide l'expression régulière, true sinon.
250 250
  **/
251 251
 function spip_xml_match_nodes($regexp, &$arbre, &$matches, $init = true) {
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@
 block discarded – undo
135 135
 				while (
136 136
 					$p !== false
137 137
 					and ($morceau = substr($txt, $d, $p - $d))
138
-					and (($nopen += preg_match_all("{<" . preg_quote($closing_tag) . "(\s*>|\s[^>]*[^/>]>)}is", $morceau,
138
+					and (($nopen += preg_match_all("{<".preg_quote($closing_tag)."(\s*>|\s[^>]*[^/>]>)}is", $morceau,
139 139
 							$matches, PREG_SET_ORDER)) > $nclose)
140 140
 				) {
141 141
 					$nclose++;
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -154,9 +154,11 @@
 block discarded – undo
154 154
 			}
155 155
 			$content = substr($txt, 0, $p);
156 156
 			$txt = substr($txt, $p + $ncclos);
157
-			if ($profondeur == 0 or strpos($content, "<") === false) // eviter une recursion si pas utile
157
+			if ($profondeur == 0 or strpos($content, "<") === false) {
158
+			    // eviter une recursion si pas utile
158 159
 			{
159 160
 				$out[$tag][] = importer_charset($content, $charset);
161
+			}
160 162
 			}//$content;
161 163
 			else {
162 164
 				$out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
Please login to merge, or discard this patch.
Indentation   +153 added lines, -153 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
 
@@ -47,23 +47,23 @@  discard block
 block discarded – undo
47 47
  *     - false si l'arbre xml ne peut être créé ou est vide
48 48
  **/
49 49
 function spip_xml_load($fichier, $strict = true, $clean = true, $taille_max = 1048576, $datas = '', $profondeur = -1) {
50
-	$contenu = "";
51
-	if (tester_url_absolue($fichier)) {
52
-		include_spip('inc/distant');
53
-		$contenu = recuperer_page($fichier, false, false, $taille_max, $datas);
54
-	} else {
55
-		lire_fichier($fichier, $contenu);
56
-	}
57
-	$arbre = array();
58
-	if ($contenu) {
59
-		$arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
60
-	}
50
+    $contenu = "";
51
+    if (tester_url_absolue($fichier)) {
52
+        include_spip('inc/distant');
53
+        $contenu = recuperer_page($fichier, false, false, $taille_max, $datas);
54
+    } else {
55
+        lire_fichier($fichier, $contenu);
56
+    }
57
+    $arbre = array();
58
+    if ($contenu) {
59
+        $arbre = spip_xml_parse($contenu, $strict, $clean, $profondeur);
60
+    }
61 61
 
62
-	return count($arbre) ? $arbre : false;
62
+    return count($arbre) ? $arbre : false;
63 63
 }
64 64
 
65 65
 if (!defined('_SPIP_XML_TAG_SPLIT')) {
66
-	define('_SPIP_XML_TAG_SPLIT', "{<([^:>][^>]*?)>}sS");
66
+    define('_SPIP_XML_TAG_SPLIT', "{<([^:>][^>]*?)>}sS");
67 67
 }
68 68
 
69 69
 /**
@@ -82,150 +82,150 @@  discard block
 block discarded – undo
82 82
  *     - false si l'arbre xml ne peut être créé ou est vide
83 83
  **/
84 84
 function spip_xml_parse(&$texte, $strict = true, $clean = true, $profondeur = -1) {
85
-	$out = array();
86
-	// enlever les commentaires
87
-	$charset = 'AUTO';
88
-	if ($clean === true) {
89
-		if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
90
-			$charset = $regs[2];
91
-		}
92
-		$texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
93
-		$texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
94
-		include_spip('inc/charsets');
95
-		$clean = $charset;
96
-		//$texte = importer_charset($texte,$charset);
97
-	}
98
-	if (is_string($clean)) {
99
-		$charset = $clean;
100
-	}
101
-	$txt = $texte;
85
+    $out = array();
86
+    // enlever les commentaires
87
+    $charset = 'AUTO';
88
+    if ($clean === true) {
89
+        if (preg_match(",<\?xml\s(.*?)encoding=['\"]?(.*?)['\"]?(\s(.*))?\?>,im", $texte, $regs)) {
90
+            $charset = $regs[2];
91
+        }
92
+        $texte = preg_replace(',<!--(.*?)-->,is', '', $texte);
93
+        $texte = preg_replace(',<\?(.*?)\?>,is', '', $texte);
94
+        include_spip('inc/charsets');
95
+        $clean = $charset;
96
+        //$texte = importer_charset($texte,$charset);
97
+    }
98
+    if (is_string($clean)) {
99
+        $charset = $clean;
100
+    }
101
+    $txt = $texte;
102 102
 
103
-	// tant qu'il y a des tags
104
-	$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
105
-	while (count($chars) >= 2) {
106
-		// tag ouvrant
107
-		//$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
103
+    // tant qu'il y a des tags
104
+    $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
105
+    while (count($chars) >= 2) {
106
+        // tag ouvrant
107
+        //$chars = preg_split("{<([^>]*?)>}s",$txt,2,PREG_SPLIT_DELIM_CAPTURE);
108 108
 
109
-		// $before doit etre vide ou des espaces uniquements!
110
-		$before = trim($chars[0]);
109
+        // $before doit etre vide ou des espaces uniquements!
110
+        $before = trim($chars[0]);
111 111
 
112
-		if (strlen($before) > 0) {
113
-			return importer_charset($texte, $charset);
114
-		}//$texte; // before non vide, donc on est dans du texte
112
+        if (strlen($before) > 0) {
113
+            return importer_charset($texte, $charset);
114
+        }//$texte; // before non vide, donc on est dans du texte
115 115
 
116
-		$tag = rtrim($chars[1]);
117
-		$txt = $chars[2];
116
+        $tag = rtrim($chars[1]);
117
+        $txt = $chars[2];
118 118
 
119
-		if (strncmp($tag, '![CDATA[', 8) == 0) {
120
-			return importer_charset($texte, $charset);
121
-		}//$texte;
122
-		if (substr($tag, -1) == '/') { // self closing tag
123
-			$tag = rtrim(substr($tag, 0, strlen($tag) - 1));
124
-			$out[$tag][] = "";
125
-		} else {
126
-			$closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
127
-			$closing_tag = reset($closing_tag);
128
-			// tag fermant
129
-			$ncclos = strlen("</$closing_tag>");
130
-			$p = strpos($txt, "</$closing_tag>");
131
-			if ($p !== false and (strpos($txt, "<") < $p)) {
132
-				$nclose = 0;
133
-				$nopen = 0;
134
-				$d = 0;
135
-				while (
136
-					$p !== false
137
-					and ($morceau = substr($txt, $d, $p - $d))
138
-					and (($nopen += preg_match_all("{<" . preg_quote($closing_tag) . "(\s*>|\s[^>]*[^/>]>)}is", $morceau,
139
-							$matches, PREG_SET_ORDER)) > $nclose)
140
-				) {
141
-					$nclose++;
142
-					$d = $p + $ncclos;
143
-					$p = strpos($txt, "</$closing_tag>", $d);
144
-				}
145
-			}
146
-			if ($p === false) {
147
-				if ($strict) {
148
-					$out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
119
+        if (strncmp($tag, '![CDATA[', 8) == 0) {
120
+            return importer_charset($texte, $charset);
121
+        }//$texte;
122
+        if (substr($tag, -1) == '/') { // self closing tag
123
+            $tag = rtrim(substr($tag, 0, strlen($tag) - 1));
124
+            $out[$tag][] = "";
125
+        } else {
126
+            $closing_tag = preg_split(",\s|\t|\n|\r,", trim($tag));
127
+            $closing_tag = reset($closing_tag);
128
+            // tag fermant
129
+            $ncclos = strlen("</$closing_tag>");
130
+            $p = strpos($txt, "</$closing_tag>");
131
+            if ($p !== false and (strpos($txt, "<") < $p)) {
132
+                $nclose = 0;
133
+                $nopen = 0;
134
+                $d = 0;
135
+                while (
136
+                    $p !== false
137
+                    and ($morceau = substr($txt, $d, $p - $d))
138
+                    and (($nopen += preg_match_all("{<" . preg_quote($closing_tag) . "(\s*>|\s[^>]*[^/>]>)}is", $morceau,
139
+                            $matches, PREG_SET_ORDER)) > $nclose)
140
+                ) {
141
+                    $nclose++;
142
+                    $d = $p + $ncclos;
143
+                    $p = strpos($txt, "</$closing_tag>", $d);
144
+                }
145
+            }
146
+            if ($p === false) {
147
+                if ($strict) {
148
+                    $out[$tag][] = "erreur : tag fermant $tag manquant::$txt";
149 149
 
150
-					return $out;
151
-				} else {
152
-					return importer_charset($texte, $charset);
153
-				}//$texte // un tag qui constitue du texte a reporter dans $before
154
-			}
155
-			$content = substr($txt, 0, $p);
156
-			$txt = substr($txt, $p + $ncclos);
157
-			if ($profondeur == 0 or strpos($content, "<") === false) // eviter une recursion si pas utile
158
-			{
159
-				$out[$tag][] = importer_charset($content, $charset);
160
-			}//$content;
161
-			else {
162
-				$out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
163
-			}
164
-		}
165
-		$chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
166
-	}
167
-	if (count($out) && (strlen(trim($txt)) == 0)) {
168
-		return $out;
169
-	} else {
170
-		return importer_charset($texte, $charset);
171
-	}//$texte;
150
+                    return $out;
151
+                } else {
152
+                    return importer_charset($texte, $charset);
153
+                }//$texte // un tag qui constitue du texte a reporter dans $before
154
+            }
155
+            $content = substr($txt, 0, $p);
156
+            $txt = substr($txt, $p + $ncclos);
157
+            if ($profondeur == 0 or strpos($content, "<") === false) // eviter une recursion si pas utile
158
+            {
159
+                $out[$tag][] = importer_charset($content, $charset);
160
+            }//$content;
161
+            else {
162
+                $out[$tag][] = spip_xml_parse($content, $strict, $clean, $profondeur - 1);
163
+            }
164
+        }
165
+        $chars = preg_split(_SPIP_XML_TAG_SPLIT, $txt, 2, PREG_SPLIT_DELIM_CAPTURE);
166
+    }
167
+    if (count($out) && (strlen(trim($txt)) == 0)) {
168
+        return $out;
169
+    } else {
170
+        return importer_charset($texte, $charset);
171
+    }//$texte;
172 172
 }
173 173
 
174 174
 // https://code.spip.net/@spip_xml_aplatit
175 175
 function spip_xml_aplatit($arbre, $separateur = " ") {
176
-	$s = "";
177
-	if (is_array($arbre)) {
178
-		foreach ($arbre as $tag => $feuille) {
179
-			if (is_array($feuille)) {
180
-				if ($tag !== intval($tag)) {
181
-					$f = spip_xml_aplatit($feuille, $separateur);
182
-					if (strlen($f)) {
183
-						$tagf = explode(" ", $tag);
184
-						$tagf = $tagf[0];
185
-						$s .= "<$tag>$f</$tagf>";
186
-					} else {
187
-						$s .= "<$tag />";
188
-					}
189
-				} else {
190
-					$s .= spip_xml_aplatit($feuille);
191
-				}
192
-				$s .= $separateur;
193
-			} else {
194
-				$s .= "$feuille$separateur";
195
-			}
196
-		}
197
-	}
176
+    $s = "";
177
+    if (is_array($arbre)) {
178
+        foreach ($arbre as $tag => $feuille) {
179
+            if (is_array($feuille)) {
180
+                if ($tag !== intval($tag)) {
181
+                    $f = spip_xml_aplatit($feuille, $separateur);
182
+                    if (strlen($f)) {
183
+                        $tagf = explode(" ", $tag);
184
+                        $tagf = $tagf[0];
185
+                        $s .= "<$tag>$f</$tagf>";
186
+                    } else {
187
+                        $s .= "<$tag />";
188
+                    }
189
+                } else {
190
+                    $s .= spip_xml_aplatit($feuille);
191
+                }
192
+                $s .= $separateur;
193
+            } else {
194
+                $s .= "$feuille$separateur";
195
+            }
196
+        }
197
+    }
198 198
 
199
-	return strlen($separateur) ? substr($s, 0, -strlen($separateur)) : $s;
199
+    return strlen($separateur) ? substr($s, 0, -strlen($separateur)) : $s;
200 200
 }
201 201
 
202 202
 // https://code.spip.net/@spip_xml_tagname
203 203
 function spip_xml_tagname($tag) {
204
-	if (preg_match(',^([a-z][\w:]*),i', $tag, $reg)) {
205
-		return $reg[1];
206
-	}
204
+    if (preg_match(',^([a-z][\w:]*),i', $tag, $reg)) {
205
+        return $reg[1];
206
+    }
207 207
 
208
-	return "";
208
+    return "";
209 209
 }
210 210
 
211 211
 // https://code.spip.net/@spip_xml_decompose_tag
212 212
 function spip_xml_decompose_tag($tag) {
213
-	$tagname = spip_xml_tagname($tag);
214
-	$liste = array();
215
-	$tag = ltrim(strpbrk($tag, " \n\t"));
216
-	$p = strpos($tag, '=');
217
-	while ($p !== false) {
218
-		$attr = trim(substr($tag, 0, $p));
219
-		$tag = ltrim(substr($tag, $p + 1));
220
-		$quote = $tag[0];
221
-		$p = strpos($tag, $quote, 1);
222
-		$cont = substr($tag, 1, $p - 1);
223
-		$liste[$attr] = $cont;
224
-		$tag = substr($tag, $p + 1);
225
-		$p = strpos($tag, '=');
226
-	}
213
+    $tagname = spip_xml_tagname($tag);
214
+    $liste = array();
215
+    $tag = ltrim(strpbrk($tag, " \n\t"));
216
+    $p = strpos($tag, '=');
217
+    while ($p !== false) {
218
+        $attr = trim(substr($tag, 0, $p));
219
+        $tag = ltrim(substr($tag, $p + 1));
220
+        $quote = $tag[0];
221
+        $p = strpos($tag, $quote, 1);
222
+        $cont = substr($tag, 1, $p - 1);
223
+        $liste[$attr] = $cont;
224
+        $tag = substr($tag, $p + 1);
225
+        $p = strpos($tag, '=');
226
+    }
227 227
 
228
-	return array($tagname, $liste);
228
+    return array($tagname, $liste);
229 229
 }
230 230
 
231 231
 /**
@@ -248,21 +248,21 @@  discard block
 block discarded – undo
248 248
  *     false si aucun élément ne valide l'expression régulière, true sinon.
249 249
  **/
250 250
 function spip_xml_match_nodes($regexp, &$arbre, &$matches, $init = true) {
251
-	if ($init) {
252
-		$matches = array();
253
-	}
254
-	if (is_array($arbre) && count($arbre)) {
255
-		foreach (array_keys($arbre) as $tag) {
256
-			if (preg_match($regexp, $tag)) {
257
-				$matches[$tag] = &$arbre[$tag];
258
-			}
259
-			if (is_array($arbre[$tag])) {
260
-				foreach (array_keys($arbre[$tag]) as $occurences) {
261
-					spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
262
-				}
263
-			}
264
-		}
265
-	}
251
+    if ($init) {
252
+        $matches = array();
253
+    }
254
+    if (is_array($arbre) && count($arbre)) {
255
+        foreach (array_keys($arbre) as $tag) {
256
+            if (preg_match($regexp, $tag)) {
257
+                $matches[$tag] = &$arbre[$tag];
258
+            }
259
+            if (is_array($arbre[$tag])) {
260
+                foreach (array_keys($arbre[$tag]) as $occurences) {
261
+                    spip_xml_match_nodes($regexp, $arbre[$tag][$occurences], $matches, false);
262
+                }
263
+            }
264
+        }
265
+    }
266 266
 
267
-	return (count($matches));
267
+    return (count($matches));
268 268
 }
Please login to merge, or discard this patch.
ecrire/iterateur/data.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	/**
134 134
 	 * Déclarer les critères exceptions
135 135
 	 *
136
-	 * @return array
136
+	 * @return string[]
137 137
 	 */
138 138
 	public function exception_des_criteres() {
139 139
 		return array('tableau');
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
  * pour la syntaxe cf la fonction spip preg_files
788 788
  *
789 789
  * @param string $dir
790
- * @param string $regexp
790
+ * @param integer $regexp
791 791
  * @param int $limit
792 792
  * @return array|bool
793 793
  */
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 /**
827 827
  * Object -> tableau
828 828
  *
829
- * @param Object $object
829
+ * @param SimpleXMLIterator $object
830 830
  * @return array|bool
831 831
  */
832 832
 function XMLObjectToArray($object) {
Please login to merge, or discard this patch.
Indentation   +616 added lines, -616 removed lines patch added patch discarded remove patch
@@ -17,11 +17,11 @@  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
 if (!defined('_DATA_SOURCE_MAX_SIZE')) {
24
-	define('_DATA_SOURCE_MAX_SIZE', 2 * 1048576);
24
+    define('_DATA_SOURCE_MAX_SIZE', 2 * 1048576);
25 25
 }
26 26
 
27 27
 
@@ -42,17 +42,17 @@  discard block
 block discarded – undo
42 42
  *     Description de la boucle complétée des champs
43 43
  */
44 44
 function iterateur_DATA_dist($b) {
45
-	$b->iterateur = 'DATA'; # designe la classe d'iterateur
46
-	$b->show = array(
47
-		'field' => array(
48
-			'cle' => 'STRING',
49
-			'valeur' => 'STRING',
50
-			'*' => 'ALL' // Champ joker *
51
-		)
52
-	);
53
-	$b->select[] = '.valeur';
54
-
55
-	return $b;
45
+    $b->iterateur = 'DATA'; # designe la classe d'iterateur
46
+    $b->show = array(
47
+        'field' => array(
48
+            'cle' => 'STRING',
49
+            'valeur' => 'STRING',
50
+            '*' => 'ALL' // Champ joker *
51
+        )
52
+    );
53
+    $b->select[] = '.valeur';
54
+
55
+    return $b;
56 56
 }
57 57
 
58 58
 
@@ -62,505 +62,505 @@  discard block
 block discarded – undo
62 62
  * Pour itérer sur des données quelconques (transformables en tableau)
63 63
  */
64 64
 class IterateurDATA implements Iterator {
65
-	/**
66
-	 * tableau de donnees
67
-	 *
68
-	 * @var array
69
-	 */
70
-	protected $tableau = array();
71
-
72
-	/**
73
-	 * Conditions de filtrage
74
-	 * ie criteres de selection
75
-	 *
76
-	 * @var array
77
-	 */
78
-	protected $filtre = array();
79
-
80
-
81
-	/**
82
-	 * Cle courante
83
-	 *
84
-	 * @var null
85
-	 */
86
-	protected $cle = null;
87
-
88
-	/**
89
-	 * Valeur courante
90
-	 *
91
-	 * @var null
92
-	 */
93
-	protected $valeur = null;
94
-
95
-	/**
96
-	 * Erreur presente ?
97
-	 *
98
-	 * @var bool
99
-	 **/
100
-	public $err = false;
101
-
102
-	/**
103
-	 * Calcul du total des elements
104
-	 *
105
-	 * @var int|null
106
-	 **/
107
-	public $total = null;
108
-
109
-	/**
110
-	 * Constructeur
111
-	 *
112
-	 * @param  $command
113
-	 * @param array $info
114
-	 */
115
-	public function __construct($command, $info = array()) {
116
-		$this->type = 'DATA';
117
-		$this->command = $command;
118
-		$this->info = $info;
119
-
120
-		$this->select($command);
121
-	}
122
-
123
-	/**
124
-	 * Revenir au depart
125
-	 *
126
-	 * @return void
127
-	 */
128
-	public function rewind() {
129
-		reset($this->tableau);
130
-		$this->cle = key($this->tableau);
131
-		$this->valeur = current($this->tableau);
132
-		next($this->tableau);
133
-	}
134
-
135
-	/**
136
-	 * Déclarer les critères exceptions
137
-	 *
138
-	 * @return array
139
-	 */
140
-	public function exception_des_criteres() {
141
-		return array('tableau');
142
-	}
143
-
144
-	/**
145
-	 * Récupérer depuis le cache si possible
146
-	 *
147
-	 * @param string $cle
148
-	 * @return mixed
149
-	 */
150
-	protected function cache_get($cle) {
151
-		if (!$cle) {
152
-			return;
153
-		}
154
-		# utiliser memoization si dispo
155
-		if (!function_exists('cache_get')) {
156
-			return;
157
-		}
158
-
159
-		return cache_get($cle);
160
-	}
161
-
162
-	/**
163
-	 * Stocker en cache si possible
164
-	 *
165
-	 * @param string $cle
166
-	 * @param int $ttl
167
-	 * @param null|mixed $valeur
168
-	 * @return bool
169
-	 */
170
-	protected function cache_set($cle, $ttl, $valeur = null) {
171
-		if (!$cle) {
172
-			return;
173
-		}
174
-		if (is_null($valeur)) {
175
-			$valeur = $this->tableau;
176
-		}
177
-		# utiliser memoization si dispo
178
-		if (!function_exists('cache_set')) {
179
-			return;
180
-		}
181
-
182
-		return cache_set($cle,
183
-			array(
184
-				'data' => $valeur,
185
-				'time' => time(),
186
-				'ttl' => $ttl
187
-			),
188
-			3600 + $ttl);
189
-		# conserver le cache 1h de plus que la validite demandee,
190
-		# pour le cas ou le serveur distant ne reponde plus
191
-	}
192
-
193
-	/**
194
-	 * Aller chercher les données de la boucle DATA
195
-	 *
196
-	 * @throws Exception
197
-	 * @param array $command
198
-	 * @return void
199
-	 */
200
-	protected function select($command) {
201
-
202
-		// l'iterateur DATA peut etre appele en passant (data:type)
203
-		// le type se retrouve dans la commande 'from'
204
-		// dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
205
-		if (isset($this->command['from'][0])) {
206
-			if (isset($this->command['source']) and is_array($this->command['source'])) {
207
-				array_unshift($this->command['source'], $this->command['sourcemode']);
208
-			}
209
-			$this->command['sourcemode'] = $this->command['from'][0];
210
-		}
211
-
212
-		// cherchons differents moyens de creer le tableau de donnees
213
-		// les commandes connues pour l'iterateur DATA
214
-		// sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
215
-
216
-		// {source format, [URL], [arg2]...}
217
-		if (isset($this->command['source'])
218
-			and isset($this->command['sourcemode'])
219
-		) {
220
-			$this->select_source();
221
-		}
222
-
223
-		// Critere {liste X1, X2, X3}
224
-		if (isset($this->command['liste'])) {
225
-			$this->select_liste();
226
-		}
227
-		if (isset($this->command['enum'])) {
228
-			$this->select_enum();
229
-		}
230
-
231
-		// Si a ce stade on n'a pas de table, il y a un bug
232
-		if (!is_array($this->tableau)) {
233
-			$this->err = true;
234
-			spip_log("erreur datasource " . var_export($command, true));
235
-		}
236
-
237
-		// {datapath query.results}
238
-		// extraire le chemin "query.results" du tableau de donnees
239
-		if (!$this->err
240
-			and isset($this->command['datapath'])
241
-			and is_array($this->command['datapath'])
242
-		) {
243
-			$this->select_datapath();
244
-		}
245
-
246
-		// tri {par x}
247
-		if ($this->command['orderby']) {
248
-			$this->select_orderby();
249
-		}
250
-
251
-		// grouper les resultats {fusion /x/y/z} ;
252
-		if ($this->command['groupby']) {
253
-			$this->select_groupby();
254
-		}
255
-
256
-		$this->rewind();
257
-		#var_dump($this->tableau);
258
-	}
259
-
260
-
261
-	/**
262
-	 * Aller chercher les donnees de la boucle DATA
263
-	 * depuis une source
264
-	 * {source format, [URL], [arg2]...}
265
-	 */
266
-	protected function select_source() {
267
-		# un peu crado : avant de charger le cache il faut charger
268
-		# les class indispensables, sinon PHP ne saura pas gerer
269
-		# l'objet en cache ; cf plugins/icalendar
270
-		# perf : pas de fonction table_to_array ! (table est deja un array)
271
-		if (isset($this->command['sourcemode'])
272
-			and !in_array($this->command['sourcemode'], array('table', 'array', 'tableau'))
273
-		) {
274
-			charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
275
-		}
276
-
277
-		# le premier argument peut etre un array, une URL etc.
278
-		$src = $this->command['source'][0];
279
-
280
-		# avons-nous un cache dispo ?
281
-		$cle = null;
282
-		if (is_string($src)) {
283
-			$cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
284
-		}
285
-
286
-		$cache = $this->cache_get($cle);
287
-		if (isset($this->command['datacache'])) {
288
-			$ttl = intval($this->command['datacache']);
289
-		}
290
-		if ($cache
291
-			and ($cache['time'] + (isset($ttl) ? $ttl : $cache['ttl'])
292
-				> time())
293
-			and !(_request('var_mode') === 'recalcul'
294
-				and include_spip('inc/autoriser')
295
-				and autoriser('recalcul')
296
-			)
297
-		) {
298
-			$this->tableau = $cache['data'];
299
-		} else {
300
-			try {
301
-				if (isset($this->command['sourcemode'])
302
-					and in_array($this->command['sourcemode'],
303
-						array('table', 'array', 'tableau'))
304
-				) {
305
-					if (is_array($a = $src)
306
-						or (is_string($a)
307
-							and $a = str_replace('&quot;', '"', $a) # fragile!
308
-							and is_array($a = @unserialize($a)))
309
-					) {
310
-						$this->tableau = $a;
311
-					}
312
-				} else {
313
-					$data = $src;
314
-					if (is_string($src)) { 
315
-						if (tester_url_absolue($src)) {
316
-							include_spip('inc/distant');
317
-							$data = recuperer_page($src, false, false, _DATA_SOURCE_MAX_SIZE);
318
-							if (!$data) {
319
-								throw new Exception("404");
320
-							}
321
-							if (!isset($ttl)) {
322
-								$ttl = 24 * 3600;
323
-							}
324
-						} elseif (@is_dir($src)) {
325
-							$data = $src;
326
-						} elseif (@is_readable($src) && @is_file($src)) {
327
-							$data = spip_file_get_contents($src);
328
-						}
329
-						if (!isset($ttl)) {
330
-							$ttl = 10;
331
-						}
332
-					}
333
-
334
-					if (!$this->err
335
-						and $data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true)
336
-					) {
337
-						$args = $this->command['source'];
338
-						$args[0] = $data;
339
-						if (is_array($a = $data_to_array(...$args))) {
340
-							$this->tableau = $a;
341
-						}
342
-					}
343
-				}
344
-
345
-				if (!is_array($this->tableau)) {
346
-					$this->err = true;
347
-				}
348
-
349
-				if (!$this->err and isset($ttl) and $ttl > 0) {
350
-					$this->cache_set($cle, $ttl);
351
-				}
352
-
353
-			} catch (Exception $e) {
354
-				$e = $e->getMessage();
355
-				$err = sprintf("[%s, %s] $e",
356
-					$src,
357
-					$this->command['sourcemode']);
358
-				erreur_squelette(array($err, array()));
359
-				$this->err = true;
360
-			}
361
-		}
362
-
363
-		# en cas d'erreur, utiliser le cache si encore dispo
364
-		if ($this->err
365
-			and $cache
366
-		) {
367
-			$this->tableau = $cache['data'];
368
-			$this->err = false;
369
-		}
370
-	}
371
-
372
-
373
-	/**
374
-	 * Retourne un tableau donne depuis un critère liste
375
-	 *
376
-	 * Critère `{liste X1, X2, X3}`
377
-	 *
378
-	 * @see critere_DATA_liste_dist()
379
-	 *
380
-	 **/
381
-	protected function select_liste() {
382
-		# s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
383
-		if (!isset($this->command['liste'][1])) {
384
-			if (!is_array($this->command['liste'][0])) {
385
-				$this->command['liste'] = explode(',', $this->command['liste'][0]);
386
-			} else {
387
-				$this->command['liste'] = $this->command['liste'][0];
388
-			}
389
-		}
390
-		$this->tableau = $this->command['liste'];
391
-	}
392
-
393
-	/**
394
-	 * Retourne un tableau donne depuis un critere liste
395
-	 * Critere {enum Xmin, Xmax}
396
-	 *
397
-	 **/
398
-	protected function select_enum() {
399
-		# s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
400
-		if (!isset($this->command['enum'][1])) {
401
-			if (!is_array($this->command['enum'][0])) {
402
-				$this->command['enum'] = explode(',', $this->command['enum'][0]);
403
-			} else {
404
-				$this->command['enum'] = $this->command['enum'][0];
405
-			}
406
-		}
407
-		if (count($this->command['enum']) >= 3) {
408
-			$enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']),
409
-				array_shift($this->command['enum']));
410
-		} else {
411
-			$enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']));
412
-		}
413
-		$this->tableau = $enum;
414
-	}
415
-
416
-
417
-	/**
418
-	 * extraire le chemin "query.results" du tableau de donnees
419
-	 * {datapath query.results}
420
-	 *
421
-	 **/
422
-	protected function select_datapath() {
423
-		$base = reset($this->command['datapath']);
424
-		if (strlen($base = ltrim(trim($base), "/"))) {
425
-			$this->tableau = table_valeur($this->tableau, $base);
426
-			if (!is_array($this->tableau)) {
427
-				$this->tableau = array();
428
-				$this->err = true;
429
-				spip_log("datapath '$base' absent");
430
-			}
431
-		}
432
-	}
433
-
434
-	/**
435
-	 * Ordonner les resultats
436
-	 * {par x}
437
-	 *
438
-	 **/
439
-	protected function select_orderby() {
440
-		$sortfunc = '';
441
-		$aleas = 0;
442
-		foreach ($this->command['orderby'] as $tri) {
443
-			// virer le / initial pour les criteres de la forme {par /xx}
444
-			if (preg_match(',^\.?([/\w]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
445
-				$r = array_pad($r, 3, null);
446
-
447
-				// tri par cle
448
-				if ($r[1] == 'cle') {
449
-					if (isset($r[2]) and $r[2]) {
450
-						krsort($this->tableau);
451
-					} else {
452
-						ksort($this->tableau);
453
-					}
454
-				} # {par hasard}
455
-				else {
456
-					if ($r[1] == 'hasard') {
457
-						$k = array_keys($this->tableau);
458
-						shuffle($k);
459
-						$v = array();
460
-						foreach ($k as $cle) {
461
-							$v[$cle] = $this->tableau[$cle];
462
-						}
463
-						$this->tableau = $v;
464
-					} else {
465
-						# {par valeur}
466
-						if ($r[1] == 'valeur') {
467
-							$tv = '%s';
468
-						} # {par valeur/xx/yy} ??
469
-						else {
470
-							$tv = 'table_valeur(%s, ' . var_export($r[1], true) . ')';
471
-						}
472
-						$sortfunc .= '
65
+    /**
66
+     * tableau de donnees
67
+     *
68
+     * @var array
69
+     */
70
+    protected $tableau = array();
71
+
72
+    /**
73
+     * Conditions de filtrage
74
+     * ie criteres de selection
75
+     *
76
+     * @var array
77
+     */
78
+    protected $filtre = array();
79
+
80
+
81
+    /**
82
+     * Cle courante
83
+     *
84
+     * @var null
85
+     */
86
+    protected $cle = null;
87
+
88
+    /**
89
+     * Valeur courante
90
+     *
91
+     * @var null
92
+     */
93
+    protected $valeur = null;
94
+
95
+    /**
96
+     * Erreur presente ?
97
+     *
98
+     * @var bool
99
+     **/
100
+    public $err = false;
101
+
102
+    /**
103
+     * Calcul du total des elements
104
+     *
105
+     * @var int|null
106
+     **/
107
+    public $total = null;
108
+
109
+    /**
110
+     * Constructeur
111
+     *
112
+     * @param  $command
113
+     * @param array $info
114
+     */
115
+    public function __construct($command, $info = array()) {
116
+        $this->type = 'DATA';
117
+        $this->command = $command;
118
+        $this->info = $info;
119
+
120
+        $this->select($command);
121
+    }
122
+
123
+    /**
124
+     * Revenir au depart
125
+     *
126
+     * @return void
127
+     */
128
+    public function rewind() {
129
+        reset($this->tableau);
130
+        $this->cle = key($this->tableau);
131
+        $this->valeur = current($this->tableau);
132
+        next($this->tableau);
133
+    }
134
+
135
+    /**
136
+     * Déclarer les critères exceptions
137
+     *
138
+     * @return array
139
+     */
140
+    public function exception_des_criteres() {
141
+        return array('tableau');
142
+    }
143
+
144
+    /**
145
+     * Récupérer depuis le cache si possible
146
+     *
147
+     * @param string $cle
148
+     * @return mixed
149
+     */
150
+    protected function cache_get($cle) {
151
+        if (!$cle) {
152
+            return;
153
+        }
154
+        # utiliser memoization si dispo
155
+        if (!function_exists('cache_get')) {
156
+            return;
157
+        }
158
+
159
+        return cache_get($cle);
160
+    }
161
+
162
+    /**
163
+     * Stocker en cache si possible
164
+     *
165
+     * @param string $cle
166
+     * @param int $ttl
167
+     * @param null|mixed $valeur
168
+     * @return bool
169
+     */
170
+    protected function cache_set($cle, $ttl, $valeur = null) {
171
+        if (!$cle) {
172
+            return;
173
+        }
174
+        if (is_null($valeur)) {
175
+            $valeur = $this->tableau;
176
+        }
177
+        # utiliser memoization si dispo
178
+        if (!function_exists('cache_set')) {
179
+            return;
180
+        }
181
+
182
+        return cache_set($cle,
183
+            array(
184
+                'data' => $valeur,
185
+                'time' => time(),
186
+                'ttl' => $ttl
187
+            ),
188
+            3600 + $ttl);
189
+        # conserver le cache 1h de plus que la validite demandee,
190
+        # pour le cas ou le serveur distant ne reponde plus
191
+    }
192
+
193
+    /**
194
+     * Aller chercher les données de la boucle DATA
195
+     *
196
+     * @throws Exception
197
+     * @param array $command
198
+     * @return void
199
+     */
200
+    protected function select($command) {
201
+
202
+        // l'iterateur DATA peut etre appele en passant (data:type)
203
+        // le type se retrouve dans la commande 'from'
204
+        // dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
205
+        if (isset($this->command['from'][0])) {
206
+            if (isset($this->command['source']) and is_array($this->command['source'])) {
207
+                array_unshift($this->command['source'], $this->command['sourcemode']);
208
+            }
209
+            $this->command['sourcemode'] = $this->command['from'][0];
210
+        }
211
+
212
+        // cherchons differents moyens de creer le tableau de donnees
213
+        // les commandes connues pour l'iterateur DATA
214
+        // sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
215
+
216
+        // {source format, [URL], [arg2]...}
217
+        if (isset($this->command['source'])
218
+            and isset($this->command['sourcemode'])
219
+        ) {
220
+            $this->select_source();
221
+        }
222
+
223
+        // Critere {liste X1, X2, X3}
224
+        if (isset($this->command['liste'])) {
225
+            $this->select_liste();
226
+        }
227
+        if (isset($this->command['enum'])) {
228
+            $this->select_enum();
229
+        }
230
+
231
+        // Si a ce stade on n'a pas de table, il y a un bug
232
+        if (!is_array($this->tableau)) {
233
+            $this->err = true;
234
+            spip_log("erreur datasource " . var_export($command, true));
235
+        }
236
+
237
+        // {datapath query.results}
238
+        // extraire le chemin "query.results" du tableau de donnees
239
+        if (!$this->err
240
+            and isset($this->command['datapath'])
241
+            and is_array($this->command['datapath'])
242
+        ) {
243
+            $this->select_datapath();
244
+        }
245
+
246
+        // tri {par x}
247
+        if ($this->command['orderby']) {
248
+            $this->select_orderby();
249
+        }
250
+
251
+        // grouper les resultats {fusion /x/y/z} ;
252
+        if ($this->command['groupby']) {
253
+            $this->select_groupby();
254
+        }
255
+
256
+        $this->rewind();
257
+        #var_dump($this->tableau);
258
+    }
259
+
260
+
261
+    /**
262
+     * Aller chercher les donnees de la boucle DATA
263
+     * depuis une source
264
+     * {source format, [URL], [arg2]...}
265
+     */
266
+    protected function select_source() {
267
+        # un peu crado : avant de charger le cache il faut charger
268
+        # les class indispensables, sinon PHP ne saura pas gerer
269
+        # l'objet en cache ; cf plugins/icalendar
270
+        # perf : pas de fonction table_to_array ! (table est deja un array)
271
+        if (isset($this->command['sourcemode'])
272
+            and !in_array($this->command['sourcemode'], array('table', 'array', 'tableau'))
273
+        ) {
274
+            charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
275
+        }
276
+
277
+        # le premier argument peut etre un array, une URL etc.
278
+        $src = $this->command['source'][0];
279
+
280
+        # avons-nous un cache dispo ?
281
+        $cle = null;
282
+        if (is_string($src)) {
283
+            $cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
284
+        }
285
+
286
+        $cache = $this->cache_get($cle);
287
+        if (isset($this->command['datacache'])) {
288
+            $ttl = intval($this->command['datacache']);
289
+        }
290
+        if ($cache
291
+            and ($cache['time'] + (isset($ttl) ? $ttl : $cache['ttl'])
292
+                > time())
293
+            and !(_request('var_mode') === 'recalcul'
294
+                and include_spip('inc/autoriser')
295
+                and autoriser('recalcul')
296
+            )
297
+        ) {
298
+            $this->tableau = $cache['data'];
299
+        } else {
300
+            try {
301
+                if (isset($this->command['sourcemode'])
302
+                    and in_array($this->command['sourcemode'],
303
+                        array('table', 'array', 'tableau'))
304
+                ) {
305
+                    if (is_array($a = $src)
306
+                        or (is_string($a)
307
+                            and $a = str_replace('&quot;', '"', $a) # fragile!
308
+                            and is_array($a = @unserialize($a)))
309
+                    ) {
310
+                        $this->tableau = $a;
311
+                    }
312
+                } else {
313
+                    $data = $src;
314
+                    if (is_string($src)) { 
315
+                        if (tester_url_absolue($src)) {
316
+                            include_spip('inc/distant');
317
+                            $data = recuperer_page($src, false, false, _DATA_SOURCE_MAX_SIZE);
318
+                            if (!$data) {
319
+                                throw new Exception("404");
320
+                            }
321
+                            if (!isset($ttl)) {
322
+                                $ttl = 24 * 3600;
323
+                            }
324
+                        } elseif (@is_dir($src)) {
325
+                            $data = $src;
326
+                        } elseif (@is_readable($src) && @is_file($src)) {
327
+                            $data = spip_file_get_contents($src);
328
+                        }
329
+                        if (!isset($ttl)) {
330
+                            $ttl = 10;
331
+                        }
332
+                    }
333
+
334
+                    if (!$this->err
335
+                        and $data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true)
336
+                    ) {
337
+                        $args = $this->command['source'];
338
+                        $args[0] = $data;
339
+                        if (is_array($a = $data_to_array(...$args))) {
340
+                            $this->tableau = $a;
341
+                        }
342
+                    }
343
+                }
344
+
345
+                if (!is_array($this->tableau)) {
346
+                    $this->err = true;
347
+                }
348
+
349
+                if (!$this->err and isset($ttl) and $ttl > 0) {
350
+                    $this->cache_set($cle, $ttl);
351
+                }
352
+
353
+            } catch (Exception $e) {
354
+                $e = $e->getMessage();
355
+                $err = sprintf("[%s, %s] $e",
356
+                    $src,
357
+                    $this->command['sourcemode']);
358
+                erreur_squelette(array($err, array()));
359
+                $this->err = true;
360
+            }
361
+        }
362
+
363
+        # en cas d'erreur, utiliser le cache si encore dispo
364
+        if ($this->err
365
+            and $cache
366
+        ) {
367
+            $this->tableau = $cache['data'];
368
+            $this->err = false;
369
+        }
370
+    }
371
+
372
+
373
+    /**
374
+     * Retourne un tableau donne depuis un critère liste
375
+     *
376
+     * Critère `{liste X1, X2, X3}`
377
+     *
378
+     * @see critere_DATA_liste_dist()
379
+     *
380
+     **/
381
+    protected function select_liste() {
382
+        # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
383
+        if (!isset($this->command['liste'][1])) {
384
+            if (!is_array($this->command['liste'][0])) {
385
+                $this->command['liste'] = explode(',', $this->command['liste'][0]);
386
+            } else {
387
+                $this->command['liste'] = $this->command['liste'][0];
388
+            }
389
+        }
390
+        $this->tableau = $this->command['liste'];
391
+    }
392
+
393
+    /**
394
+     * Retourne un tableau donne depuis un critere liste
395
+     * Critere {enum Xmin, Xmax}
396
+     *
397
+     **/
398
+    protected function select_enum() {
399
+        # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
400
+        if (!isset($this->command['enum'][1])) {
401
+            if (!is_array($this->command['enum'][0])) {
402
+                $this->command['enum'] = explode(',', $this->command['enum'][0]);
403
+            } else {
404
+                $this->command['enum'] = $this->command['enum'][0];
405
+            }
406
+        }
407
+        if (count($this->command['enum']) >= 3) {
408
+            $enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']),
409
+                array_shift($this->command['enum']));
410
+        } else {
411
+            $enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']));
412
+        }
413
+        $this->tableau = $enum;
414
+    }
415
+
416
+
417
+    /**
418
+     * extraire le chemin "query.results" du tableau de donnees
419
+     * {datapath query.results}
420
+     *
421
+     **/
422
+    protected function select_datapath() {
423
+        $base = reset($this->command['datapath']);
424
+        if (strlen($base = ltrim(trim($base), "/"))) {
425
+            $this->tableau = table_valeur($this->tableau, $base);
426
+            if (!is_array($this->tableau)) {
427
+                $this->tableau = array();
428
+                $this->err = true;
429
+                spip_log("datapath '$base' absent");
430
+            }
431
+        }
432
+    }
433
+
434
+    /**
435
+     * Ordonner les resultats
436
+     * {par x}
437
+     *
438
+     **/
439
+    protected function select_orderby() {
440
+        $sortfunc = '';
441
+        $aleas = 0;
442
+        foreach ($this->command['orderby'] as $tri) {
443
+            // virer le / initial pour les criteres de la forme {par /xx}
444
+            if (preg_match(',^\.?([/\w]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
445
+                $r = array_pad($r, 3, null);
446
+
447
+                // tri par cle
448
+                if ($r[1] == 'cle') {
449
+                    if (isset($r[2]) and $r[2]) {
450
+                        krsort($this->tableau);
451
+                    } else {
452
+                        ksort($this->tableau);
453
+                    }
454
+                } # {par hasard}
455
+                else {
456
+                    if ($r[1] == 'hasard') {
457
+                        $k = array_keys($this->tableau);
458
+                        shuffle($k);
459
+                        $v = array();
460
+                        foreach ($k as $cle) {
461
+                            $v[$cle] = $this->tableau[$cle];
462
+                        }
463
+                        $this->tableau = $v;
464
+                    } else {
465
+                        # {par valeur}
466
+                        if ($r[1] == 'valeur') {
467
+                            $tv = '%s';
468
+                        } # {par valeur/xx/yy} ??
469
+                        else {
470
+                            $tv = 'table_valeur(%s, ' . var_export($r[1], true) . ')';
471
+                        }
472
+                        $sortfunc .= '
473 473
 					$a = ' . sprintf($tv, '$aa') . ';
474 474
 					$b = ' . sprintf($tv, '$bb') . ';
475 475
 					if ($a <> $b)
476 476
 						return ($a ' . (!empty($r[2]) ? '>' : '<') . ' $b) ? -1 : 1;';
477
-					}
478
-				}
479
-			}
480
-		}
481
-
482
-		if ($sortfunc) {
483
-			$sortfunc .= "\n return 0;";
484
-			uasort($this->tableau, function($aa, $bb) use ($sortfunc) {
485
-				return eval($sortfunc);
486
-			});
487
-		}
488
-	}
489
-
490
-
491
-	/**
492
-	 * Grouper les resultats
493
-	 * {fusion /x/y/z}
494
-	 *
495
-	 **/
496
-	protected function select_groupby() {
497
-		// virer le / initial pour les criteres de la forme {fusion /xx}
498
-		if (strlen($fusion = ltrim($this->command['groupby'][0], '/'))) {
499
-			$vu = array();
500
-			foreach ($this->tableau as $k => $v) {
501
-				$val = table_valeur($v, $fusion);
502
-				if (isset($vu[$val])) {
503
-					unset($this->tableau[$k]);
504
-				} else {
505
-					$vu[$val] = true;
506
-				}
507
-			}
508
-		}
509
-	}
510
-
511
-
512
-	/**
513
-	 * L'iterateur est-il encore valide ?
514
-	 *
515
-	 * @return bool
516
-	 */
517
-	public function valid() {
518
-		return !is_null($this->cle);
519
-	}
520
-
521
-	/**
522
-	 * Retourner la valeur
523
-	 *
524
-	 * @return null
525
-	 */
526
-	public function current() {
527
-		return $this->valeur;
528
-	}
529
-
530
-	/**
531
-	 * Retourner la cle
532
-	 *
533
-	 * @return null
534
-	 */
535
-	public function key() {
536
-		return $this->cle;
537
-	}
538
-
539
-	/**
540
-	 * Passer a la valeur suivante
541
-	 *
542
-	 * @return void
543
-	 */
544
-	public function next() {
545
-		if ($this->valid()) {
546
-			$this->cle = key($this->tableau);
547
-			$this->valeur = current($this->tableau);
548
-			next($this->tableau);
549
-		}
550
-	}
551
-
552
-	/**
553
-	 * Compter le nombre total de resultats
554
-	 *
555
-	 * @return int
556
-	 */
557
-	public function count() {
558
-		if (is_null($this->total)) {
559
-			$this->total = count($this->tableau);
560
-		}
561
-
562
-		return $this->total;
563
-	}
477
+                    }
478
+                }
479
+            }
480
+        }
481
+
482
+        if ($sortfunc) {
483
+            $sortfunc .= "\n return 0;";
484
+            uasort($this->tableau, function($aa, $bb) use ($sortfunc) {
485
+                return eval($sortfunc);
486
+            });
487
+        }
488
+    }
489
+
490
+
491
+    /**
492
+     * Grouper les resultats
493
+     * {fusion /x/y/z}
494
+     *
495
+     **/
496
+    protected function select_groupby() {
497
+        // virer le / initial pour les criteres de la forme {fusion /xx}
498
+        if (strlen($fusion = ltrim($this->command['groupby'][0], '/'))) {
499
+            $vu = array();
500
+            foreach ($this->tableau as $k => $v) {
501
+                $val = table_valeur($v, $fusion);
502
+                if (isset($vu[$val])) {
503
+                    unset($this->tableau[$k]);
504
+                } else {
505
+                    $vu[$val] = true;
506
+                }
507
+            }
508
+        }
509
+    }
510
+
511
+
512
+    /**
513
+     * L'iterateur est-il encore valide ?
514
+     *
515
+     * @return bool
516
+     */
517
+    public function valid() {
518
+        return !is_null($this->cle);
519
+    }
520
+
521
+    /**
522
+     * Retourner la valeur
523
+     *
524
+     * @return null
525
+     */
526
+    public function current() {
527
+        return $this->valeur;
528
+    }
529
+
530
+    /**
531
+     * Retourner la cle
532
+     *
533
+     * @return null
534
+     */
535
+    public function key() {
536
+        return $this->cle;
537
+    }
538
+
539
+    /**
540
+     * Passer a la valeur suivante
541
+     *
542
+     * @return void
543
+     */
544
+    public function next() {
545
+        if ($this->valid()) {
546
+            $this->cle = key($this->tableau);
547
+            $this->valeur = current($this->tableau);
548
+            next($this->tableau);
549
+        }
550
+    }
551
+
552
+    /**
553
+     * Compter le nombre total de resultats
554
+     *
555
+     * @return int
556
+     */
557
+    public function count() {
558
+        if (is_null($this->total)) {
559
+            $this->total = count($this->tableau);
560
+        }
561
+
562
+        return $this->total;
563
+    }
564 564
 }
565 565
 
566 566
 /*
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
  * @return array
575 575
  */
576 576
 function inc_file_to_array_dist($data) {
577
-	return preg_split('/\r?\n/', $data);
577
+    return preg_split('/\r?\n/', $data);
578 578
 }
579 579
 
580 580
 /**
@@ -583,9 +583,9 @@  discard block
 block discarded – undo
583 583
  * @return array
584 584
  */
585 585
 function inc_plugins_to_array_dist() {
586
-	include_spip('inc/plugin');
586
+    include_spip('inc/plugin');
587 587
 
588
-	return liste_chemin_plugin_actifs();
588
+    return liste_chemin_plugin_actifs();
589 589
 }
590 590
 
591 591
 /**
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
  * @return array
596 596
  */
597 597
 function inc_xml_to_array_dist($data) {
598
-	return @XMLObjectToArray(new SimpleXmlIterator($data));
598
+    return @XMLObjectToArray(new SimpleXmlIterator($data));
599 599
 }
600 600
 
601 601
 /**
@@ -607,14 +607,14 @@  discard block
 block discarded – undo
607 607
  *
608 608
  */
609 609
 function inc_object_to_array($object) {
610
-	if (!is_object($object) && !is_array($object)) {
611
-		return $object;
612
-	}
613
-	if (is_object($object)) {
614
-		$object = get_object_vars($object);
615
-	}
616
-
617
-	return array_map('inc_object_to_array', $object);
610
+    if (!is_object($object) && !is_array($object)) {
611
+        return $object;
612
+    }
613
+    if (is_object($object)) {
614
+        $object = get_object_vars($object);
615
+    }
616
+
617
+    return array_map('inc_object_to_array', $object);
618 618
 }
619 619
 
620 620
 /**
@@ -624,20 +624,20 @@  discard block
 block discarded – undo
624 624
  * @return array|bool
625 625
  */
626 626
 function inc_sql_to_array_dist($data) {
627
-	# sortir le connecteur de $data
628
-	preg_match(',^(?:(\w+):)?(.*)$,Sm', $data, $v);
629
-	$serveur = (string)$v[1];
630
-	$req = trim($v[2]);
631
-	if ($s = sql_query($req, $serveur)) {
632
-		$r = array();
633
-		while ($t = sql_fetch($s)) {
634
-			$r[] = $t;
635
-		}
636
-
637
-		return $r;
638
-	}
639
-
640
-	return false;
627
+    # sortir le connecteur de $data
628
+    preg_match(',^(?:(\w+):)?(.*)$,Sm', $data, $v);
629
+    $serveur = (string)$v[1];
630
+    $req = trim($v[2]);
631
+    if ($s = sql_query($req, $serveur)) {
632
+        $r = array();
633
+        while ($t = sql_fetch($s)) {
634
+            $r[] = $t;
635
+        }
636
+
637
+        return $r;
638
+    }
639
+
640
+    return false;
641 641
 }
642 642
 
643 643
 /**
@@ -647,9 +647,9 @@  discard block
 block discarded – undo
647 647
  * @return array|bool
648 648
  */
649 649
 function inc_json_to_array_dist($data) {
650
-	if (is_array($json = json_decode($data, true))) {
651
-		return (array)$json;
652
-	}
650
+    if (is_array($json = json_decode($data, true))) {
651
+        return (array)$json;
652
+    }
653 653
 }
654 654
 
655 655
 /**
@@ -659,30 +659,30 @@  discard block
 block discarded – undo
659 659
  * @return array|bool
660 660
  */
661 661
 function inc_csv_to_array_dist($data) {
662
-	include_spip('inc/csv');
663
-	list($entete, $csv) = analyse_csv($data);
664
-	array_unshift($csv, $entete);
665
-
666
-	include_spip('inc/charsets');
667
-	$i = 1;
668
-	foreach ($entete as $k => $v) {
669
-		if (trim($v) == "") {
670
-			$v = "col" . $i;
671
-		} // reperer des eventuelles cases vides
672
-		if (is_numeric($v) and $v < 0) {
673
-			$v = "__" . $v;
674
-		} // ne pas risquer d'ecraser une cle numerique
675
-		if (is_numeric($v)) {
676
-			$v = "_" . $v;
677
-		} // ne pas risquer d'ecraser une cle numerique
678
-		$v = strtolower(preg_replace(',\W+,', '_', translitteration($v)));
679
-		foreach ($csv as &$item) {
680
-			$item[$v] = &$item[$k];
681
-		}
682
-		$i++;
683
-	}
684
-
685
-	return $csv;
662
+    include_spip('inc/csv');
663
+    list($entete, $csv) = analyse_csv($data);
664
+    array_unshift($csv, $entete);
665
+
666
+    include_spip('inc/charsets');
667
+    $i = 1;
668
+    foreach ($entete as $k => $v) {
669
+        if (trim($v) == "") {
670
+            $v = "col" . $i;
671
+        } // reperer des eventuelles cases vides
672
+        if (is_numeric($v) and $v < 0) {
673
+            $v = "__" . $v;
674
+        } // ne pas risquer d'ecraser une cle numerique
675
+        if (is_numeric($v)) {
676
+            $v = "_" . $v;
677
+        } // ne pas risquer d'ecraser une cle numerique
678
+        $v = strtolower(preg_replace(',\W+,', '_', translitteration($v)));
679
+        foreach ($csv as &$item) {
680
+            $item[$v] = &$item[$k];
681
+        }
682
+        $i++;
683
+    }
684
+
685
+    return $csv;
686 686
 }
687 687
 
688 688
 /**
@@ -692,12 +692,12 @@  discard block
 block discarded – undo
692 692
  * @return array|bool
693 693
  */
694 694
 function inc_rss_to_array_dist($data) {
695
-	include_spip('inc/syndic');
696
-	if (is_array($rss = analyser_backend($data))) {
697
-		$tableau = $rss;
698
-	}
695
+    include_spip('inc/syndic');
696
+    if (is_array($rss = analyser_backend($data))) {
697
+        $tableau = $rss;
698
+    }
699 699
 
700
-	return $tableau;
700
+    return $tableau;
701 701
 }
702 702
 
703 703
 /**
@@ -707,9 +707,9 @@  discard block
 block discarded – undo
707 707
  * @return array|bool
708 708
  */
709 709
 function inc_atom_to_array_dist($data) {
710
-	$rss_to_array = charger_fonction('rss_to_array', 'inc');
710
+    $rss_to_array = charger_fonction('rss_to_array', 'inc');
711 711
 
712
-	return $rss_to_array($data);
712
+    return $rss_to_array($data);
713 713
 }
714 714
 
715 715
 /**
@@ -720,11 +720,11 @@  discard block
 block discarded – undo
720 720
  * @return array|bool
721 721
  */
722 722
 function inc_glob_to_array_dist($data) {
723
-	$a = glob($data,
724
-		GLOB_MARK | GLOB_NOSORT | GLOB_BRACE
725
-	);
723
+    $a = glob($data,
724
+        GLOB_MARK | GLOB_NOSORT | GLOB_BRACE
725
+    );
726 726
 
727
-	return $a ? $a : array();
727
+    return $a ? $a : array();
728 728
 }
729 729
 
730 730
 /**
@@ -735,14 +735,14 @@  discard block
 block discarded – undo
735 735
  * @throws Exception
736 736
  */
737 737
 function inc_yaml_to_array_dist($data) {
738
-	include_spip('inc/yaml-mini');
739
-	if (!function_exists("yaml_decode")) {
740
-		throw new Exception('YAML: impossible de trouver la fonction yaml_decode');
738
+    include_spip('inc/yaml-mini');
739
+    if (!function_exists("yaml_decode")) {
740
+        throw new Exception('YAML: impossible de trouver la fonction yaml_decode');
741 741
 
742
-		return false;
743
-	}
742
+        return false;
743
+    }
744 744
 
745
-	return yaml_decode($data);
745
+    return yaml_decode($data);
746 746
 }
747 747
 
748 748
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
  * @return array|bool
758 758
  */
759 759
 function inc_pregfiles_to_array_dist($dir, $regexp = -1, $limit = 10000) {
760
-	return (array)preg_files($dir, $regexp, $limit);
760
+    return (array)preg_files($dir, $regexp, $limit);
761 761
 }
762 762
 
763 763
 /**
@@ -769,23 +769,23 @@  discard block
 block discarded – undo
769 769
  * @return array|bool
770 770
  */
771 771
 function inc_ls_to_array_dist($data) {
772
-	$glob_to_array = charger_fonction('glob_to_array', 'inc');
773
-	$a = $glob_to_array($data);
774
-	foreach ($a as &$v) {
775
-		$b = (array)@stat($v);
776
-		foreach ($b as $k => $ignore) {
777
-			if (is_numeric($k)) {
778
-				unset($b[$k]);
779
-			}
780
-		}
781
-		$b['file'] = preg_replace('`/$`','',$v) ;
782
-		$v = array_merge(
783
-			pathinfo($v),
784
-			$b
785
-		);
786
-	}
787
-
788
-	return $a;
772
+    $glob_to_array = charger_fonction('glob_to_array', 'inc');
773
+    $a = $glob_to_array($data);
774
+    foreach ($a as &$v) {
775
+        $b = (array)@stat($v);
776
+        foreach ($b as $k => $ignore) {
777
+            if (is_numeric($k)) {
778
+                unset($b[$k]);
779
+            }
780
+        }
781
+        $b['file'] = preg_replace('`/$`','',$v) ;
782
+        $v = array_merge(
783
+            pathinfo($v),
784
+            $b
785
+        );
786
+    }
787
+
788
+    return $a;
789 789
 }
790 790
 
791 791
 /**
@@ -795,24 +795,24 @@  discard block
 block discarded – undo
795 795
  * @return array|bool
796 796
  */
797 797
 function XMLObjectToArray($object) {
798
-	$xml_array = array();
799
-	for ($object->rewind(); $object->valid(); $object->next()) {
800
-		if (array_key_exists($key = $object->key(), $xml_array)) {
801
-			$key .= '-' . uniqid();
802
-		}
803
-		$vars = get_object_vars($object->current());
804
-		if (isset($vars['@attributes'])) {
805
-			foreach ($vars['@attributes'] as $k => $v) {
806
-				$xml_array[$key][$k] = $v;
807
-			}
808
-		}
809
-		if ($object->hasChildren()) {
810
-			$xml_array[$key][] = XMLObjectToArray(
811
-				$object->current());
812
-		} else {
813
-			$xml_array[$key][] = strval($object->current());
814
-		}
815
-	}
816
-
817
-	return $xml_array;
798
+    $xml_array = array();
799
+    for ($object->rewind(); $object->valid(); $object->next()) {
800
+        if (array_key_exists($key = $object->key(), $xml_array)) {
801
+            $key .= '-' . uniqid();
802
+        }
803
+        $vars = get_object_vars($object->current());
804
+        if (isset($vars['@attributes'])) {
805
+            foreach ($vars['@attributes'] as $k => $v) {
806
+                $xml_array[$key][$k] = $v;
807
+            }
808
+        }
809
+        if ($object->hasChildren()) {
810
+            $xml_array[$key][] = XMLObjectToArray(
811
+                $object->current());
812
+        } else {
813
+            $xml_array[$key][] = strval($object->current());
814
+        }
815
+    }
816
+
817
+    return $xml_array;
818 818
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 		// Si a ce stade on n'a pas de table, il y a un bug
232 232
 		if (!is_array($this->tableau)) {
233 233
 			$this->err = true;
234
-			spip_log("erreur datasource " . var_export($command, true));
234
+			spip_log("erreur datasource ".var_export($command, true));
235 235
 		}
236 236
 
237 237
 		// {datapath query.results}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 		if (isset($this->command['sourcemode'])
272 272
 			and !in_array($this->command['sourcemode'], array('table', 'array', 'tableau'))
273 273
 		) {
274
-			charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
274
+			charger_fonction($this->command['sourcemode'].'_to_array', 'inc', true);
275 275
 		}
276 276
 
277 277
 		# le premier argument peut etre un array, une URL etc.
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		# avons-nous un cache dispo ?
281 281
 		$cle = null;
282 282
 		if (is_string($src)) {
283
-			$cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
283
+			$cle = 'datasource_'.md5($this->command['sourcemode'].':'.var_export($this->command['source'], true));
284 284
 		}
285 285
 
286 286
 		$cache = $this->cache_get($cle);
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 					}
333 333
 
334 334
 					if (!$this->err
335
-						and $data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true)
335
+						and $data_to_array = charger_fonction($this->command['sourcemode'].'_to_array', 'inc', true)
336 336
 					) {
337 337
 						$args = $this->command['source'];
338 338
 						$args[0] = $data;
@@ -467,13 +467,13 @@  discard block
 block discarded – undo
467 467
 							$tv = '%s';
468 468
 						} # {par valeur/xx/yy} ??
469 469
 						else {
470
-							$tv = 'table_valeur(%s, ' . var_export($r[1], true) . ')';
470
+							$tv = 'table_valeur(%s, '.var_export($r[1], true).')';
471 471
 						}
472 472
 						$sortfunc .= '
473
-					$a = ' . sprintf($tv, '$aa') . ';
474
-					$b = ' . sprintf($tv, '$bb') . ';
473
+					$a = ' . sprintf($tv, '$aa').';
474
+					$b = ' . sprintf($tv, '$bb').';
475 475
 					if ($a <> $b)
476
-						return ($a ' . (!empty($r[2]) ? '>' : '<') . ' $b) ? -1 : 1;';
476
+						return ($a ' . (!empty($r[2]) ? '>' : '<').' $b) ? -1 : 1;';
477 477
 					}
478 478
 				}
479 479
 			}
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 function inc_sql_to_array_dist($data) {
627 627
 	# sortir le connecteur de $data
628 628
 	preg_match(',^(?:(\w+):)?(.*)$,Sm', $data, $v);
629
-	$serveur = (string)$v[1];
629
+	$serveur = (string) $v[1];
630 630
 	$req = trim($v[2]);
631 631
 	if ($s = sql_query($req, $serveur)) {
632 632
 		$r = array();
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
  */
649 649
 function inc_json_to_array_dist($data) {
650 650
 	if (is_array($json = json_decode($data, true))) {
651
-		return (array)$json;
651
+		return (array) $json;
652 652
 	}
653 653
 }
654 654
 
@@ -667,13 +667,13 @@  discard block
 block discarded – undo
667 667
 	$i = 1;
668 668
 	foreach ($entete as $k => $v) {
669 669
 		if (trim($v) == "") {
670
-			$v = "col" . $i;
670
+			$v = "col".$i;
671 671
 		} // reperer des eventuelles cases vides
672 672
 		if (is_numeric($v) and $v < 0) {
673
-			$v = "__" . $v;
673
+			$v = "__".$v;
674 674
 		} // ne pas risquer d'ecraser une cle numerique
675 675
 		if (is_numeric($v)) {
676
-			$v = "_" . $v;
676
+			$v = "_".$v;
677 677
 		} // ne pas risquer d'ecraser une cle numerique
678 678
 		$v = strtolower(preg_replace(',\W+,', '_', translitteration($v)));
679 679
 		foreach ($csv as &$item) {
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
  * @return array|bool
758 758
  */
759 759
 function inc_pregfiles_to_array_dist($dir, $regexp = -1, $limit = 10000) {
760
-	return (array)preg_files($dir, $regexp, $limit);
760
+	return (array) preg_files($dir, $regexp, $limit);
761 761
 }
762 762
 
763 763
 /**
@@ -772,13 +772,13 @@  discard block
 block discarded – undo
772 772
 	$glob_to_array = charger_fonction('glob_to_array', 'inc');
773 773
 	$a = $glob_to_array($data);
774 774
 	foreach ($a as &$v) {
775
-		$b = (array)@stat($v);
775
+		$b = (array) @stat($v);
776 776
 		foreach ($b as $k => $ignore) {
777 777
 			if (is_numeric($k)) {
778 778
 				unset($b[$k]);
779 779
 			}
780 780
 		}
781
-		$b['file'] = preg_replace('`/$`','',$v) ;
781
+		$b['file'] = preg_replace('`/$`', '', $v);
782 782
 		$v = array_merge(
783 783
 			pathinfo($v),
784 784
 			$b
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 	$xml_array = array();
799 799
 	for ($object->rewind(); $object->valid(); $object->next()) {
800 800
 		if (array_key_exists($key = $object->key(), $xml_array)) {
801
-			$key .= '-' . uniqid();
801
+			$key .= '-'.uniqid();
802 802
 		}
803 803
 		$vars = get_object_vars($object->current());
804 804
 		if (isset($vars['@attributes'])) {
Please login to merge, or discard this patch.
ecrire/public/iterateur.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -457,6 +457,10 @@
 block discarded – undo
457 457
 	 * aller a la position $n en parcourant
458 458
 	 * un par un tous les elements
459 459
 	 */
460
+
461
+	/**
462
+	 * @param integer $n
463
+	 */
460 464
 	private function seek_loop($n) {
461 465
 		if ($this->pos > $n) {
462 466
 			$this->rewind();
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 			// chercher la classe d'iterateur
80 80
 			// IterateurXXX
81 81
 			// definie dans le fichier iterateurs/xxx.php
82
-			$class = "Iterateur" . $iterateur;
82
+			$class = "Iterateur".$iterateur;
83 83
 			if (!class_exists($class)) {
84
-				if (!include_spip("iterateur/" . strtolower($iterateur))
84
+				if (!include_spip("iterateur/".strtolower($iterateur))
85 85
 					or !class_exists($class)
86 86
 				) {
87 87
 					die("Iterateur $iterateur non trouv&#233;");
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 				return $this->iter->$nom();
209 209
 			} catch (Exception $e) {
210 210
 				// #GETCHILDREN sur un fichier de DirectoryIterator ...
211
-				spip_log("Methode $nom en echec sur " . get_class($this->iter));
211
+				spip_log("Methode $nom en echec sur ".get_class($this->iter));
212 212
 				spip_log("Cela peut être normal : retour d'une ligne de resultat ne pouvant pas calculer cette methode");
213 213
 
214 214
 				return '';
@@ -290,8 +290,8 @@  discard block
 block discarded – undo
290 290
 
291 291
 		// Creer la fonction de filtrage sur $this
292 292
 		if ($this->filtre) {
293
-			$filtres = 'return (' . join(') AND (', $this->filtre) . ');';
294
-			$this->func_filtre = function () use ($filtres) {
293
+			$filtres = 'return ('.join(') AND (', $this->filtre).');';
294
+			$this->func_filtre = function() use ($filtres) {
295 295
 				return eval($filtres);
296 296
 			};
297 297
 		}
@@ -313,28 +313,28 @@  discard block
 block discarded – undo
313 313
 		# if (!in_array($cle, array('cle', 'valeur')))
314 314
 		#	return;
315 315
 
316
-		$a = '$this->get_select(\'' . $cle . '\')';
316
+		$a = '$this->get_select(\''.$cle.'\')';
317 317
 
318 318
 		$filtre = '';
319 319
 
320 320
 		if ($op == 'REGEXP') {
321
-			$filtre = 'filtrer("match", ' . $a . ', ' . str_replace('\"', '"', $valeur) . ')';
321
+			$filtre = 'filtrer("match", '.$a.', '.str_replace('\"', '"', $valeur).')';
322 322
 			$op = '';
323 323
 		} else {
324 324
 			if ($op == 'LIKE') {
325 325
 				$valeur = str_replace(array('\"', '_', '%'), array('"', '.', '.*'), preg_quote($valeur));
326
-				$filtre = 'filtrer("match", ' . $a . ', ' . $valeur . ')';
326
+				$filtre = 'filtrer("match", '.$a.', '.$valeur.')';
327 327
 				$op = '';
328 328
 			} else {
329 329
 				if ($op == '=') {
330 330
 					$op = '==';
331 331
 				} else {
332 332
 					if ($op == 'IN') {
333
-						$filtre = 'in_array(' . $a . ', array' . $valeur . ')';
333
+						$filtre = 'in_array('.$a.', array'.$valeur.')';
334 334
 						$op = '';
335 335
 					} else {
336 336
 						if (!in_array($op, array('<', '<=', '>', '>='))) {
337
-							spip_log('operateur non reconnu ' . $op); // [todo] mettre une erreur de squelette
337
+							spip_log('operateur non reconnu '.$op); // [todo] mettre une erreur de squelette
338 338
 							$op = '';
339 339
 						}
340 340
 					}
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 		}
344 344
 
345 345
 		if ($op) {
346
-			$filtre = $a . $op . str_replace('\"', '"', $valeur);
346
+			$filtre = $a.$op.str_replace('\"', '"', $valeur);
347 347
 		}
348 348
 
349 349
 		if ($not) {
Please login to merge, or discard this patch.
Indentation   +564 added lines, -564 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 \***************************************************************************/
13 13
 
14 14
 if (!defined('_ECRIRE_INC_VERSION')) {
15
-	return;
15
+    return;
16 16
 }
17 17
 
18 18
 /**
@@ -22,578 +22,578 @@  discard block
 block discarded – undo
22 22
  *
23 23
  */
24 24
 class IterFactory {
25
-	public static function create($iterateur, $command, $info = null) {
26
-
27
-		// cas des SI {si expression} analises tres tot
28
-		// pour eviter le chargement de tout iterateur
29
-		if (isset($command['si'])) {
30
-			foreach ($command['si'] as $si) {
31
-				if (!$si) {
32
-					// $command pour boucle SQL peut generer des erreurs de compilation
33
-					// s'il est transmis alors qu'on est dans un iterateur vide
34
-					return new IterDecorator(new EmptyIterator(), array(), $info);
35
-				}
36
-			}
37
-		}
38
-
39
-		// chercher un iterateur PHP existant (par exemple dans SPL)
40
-		// (il faudrait passer l'argument ->sql_serveur
41
-		// pour etre certain qu'on est sur un "php:")
42
-		if (class_exists($iterateur)) {
43
-			$a = isset($command['args']) ? $command['args'] : array();
44
-
45
-			// permettre de passer un Iterateur directement {args #ITERATEUR} :
46
-			// si on recoit deja un iterateur en argument, on l'utilise
47
-			if (count($a) == 1 and is_object($a[0]) and is_subclass_of($a[0], 'Iterator')) {
48
-				$iter = $a[0];
49
-
50
-				// sinon, on cree un iterateur du type donne
51
-			} else {
52
-				// arguments de creation de l'iterateur...
53
-				// (pas glop)
54
-				try {
55
-					switch (count($a)) {
56
-						case 0:
57
-							$iter = new $iterateur();
58
-							break;
59
-						case 1:
60
-							$iter = new $iterateur($a[0]);
61
-							break;
62
-						case 2:
63
-							$iter = new $iterateur($a[0], $a[1]);
64
-							break;
65
-						case 3:
66
-							$iter = new $iterateur($a[0], $a[1], $a[2]);
67
-							break;
68
-						case 4:
69
-							$iter = new $iterateur($a[0], $a[1], $a[2], $a[3]);
70
-							break;
71
-					}
72
-				} catch (Exception $e) {
73
-					spip_log("Erreur de chargement de l'iterateur $iterateur");
74
-					spip_log($e->getMessage());
75
-					$iter = new EmptyIterator();
76
-				}
77
-			}
78
-		} else {
79
-			// chercher la classe d'iterateur
80
-			// IterateurXXX
81
-			// definie dans le fichier iterateurs/xxx.php
82
-			$class = "Iterateur" . $iterateur;
83
-			if (!class_exists($class)) {
84
-				if (!include_spip("iterateur/" . strtolower($iterateur))
85
-					or !class_exists($class)
86
-				) {
87
-					die("Iterateur $iterateur non trouv&#233;");
88
-					// si l'iterateur n'existe pas, on se rabat sur le generique
89
-					# $iter = new EmptyIterator();
90
-				}
91
-			}
92
-			$iter = new $class($command, $info);
93
-		}
94
-
95
-		return new IterDecorator($iter, $command, $info);
96
-	}
25
+    public static function create($iterateur, $command, $info = null) {
26
+
27
+        // cas des SI {si expression} analises tres tot
28
+        // pour eviter le chargement de tout iterateur
29
+        if (isset($command['si'])) {
30
+            foreach ($command['si'] as $si) {
31
+                if (!$si) {
32
+                    // $command pour boucle SQL peut generer des erreurs de compilation
33
+                    // s'il est transmis alors qu'on est dans un iterateur vide
34
+                    return new IterDecorator(new EmptyIterator(), array(), $info);
35
+                }
36
+            }
37
+        }
38
+
39
+        // chercher un iterateur PHP existant (par exemple dans SPL)
40
+        // (il faudrait passer l'argument ->sql_serveur
41
+        // pour etre certain qu'on est sur un "php:")
42
+        if (class_exists($iterateur)) {
43
+            $a = isset($command['args']) ? $command['args'] : array();
44
+
45
+            // permettre de passer un Iterateur directement {args #ITERATEUR} :
46
+            // si on recoit deja un iterateur en argument, on l'utilise
47
+            if (count($a) == 1 and is_object($a[0]) and is_subclass_of($a[0], 'Iterator')) {
48
+                $iter = $a[0];
49
+
50
+                // sinon, on cree un iterateur du type donne
51
+            } else {
52
+                // arguments de creation de l'iterateur...
53
+                // (pas glop)
54
+                try {
55
+                    switch (count($a)) {
56
+                        case 0:
57
+                            $iter = new $iterateur();
58
+                            break;
59
+                        case 1:
60
+                            $iter = new $iterateur($a[0]);
61
+                            break;
62
+                        case 2:
63
+                            $iter = new $iterateur($a[0], $a[1]);
64
+                            break;
65
+                        case 3:
66
+                            $iter = new $iterateur($a[0], $a[1], $a[2]);
67
+                            break;
68
+                        case 4:
69
+                            $iter = new $iterateur($a[0], $a[1], $a[2], $a[3]);
70
+                            break;
71
+                    }
72
+                } catch (Exception $e) {
73
+                    spip_log("Erreur de chargement de l'iterateur $iterateur");
74
+                    spip_log($e->getMessage());
75
+                    $iter = new EmptyIterator();
76
+                }
77
+            }
78
+        } else {
79
+            // chercher la classe d'iterateur
80
+            // IterateurXXX
81
+            // definie dans le fichier iterateurs/xxx.php
82
+            $class = "Iterateur" . $iterateur;
83
+            if (!class_exists($class)) {
84
+                if (!include_spip("iterateur/" . strtolower($iterateur))
85
+                    or !class_exists($class)
86
+                ) {
87
+                    die("Iterateur $iterateur non trouv&#233;");
88
+                    // si l'iterateur n'existe pas, on se rabat sur le generique
89
+                    # $iter = new EmptyIterator();
90
+                }
91
+            }
92
+            $iter = new $class($command, $info);
93
+        }
94
+
95
+        return new IterDecorator($iter, $command, $info);
96
+    }
97 97
 }
98 98
 
99 99
 
100 100
 class IterDecorator extends FilterIterator {
101
-	private $iter;
102
-
103
-	/**
104
-	 * Conditions de filtrage
105
-	 * ie criteres de selection
106
-	 *
107
-	 * @var array
108
-	 */
109
-	protected $filtre = array();
110
-
111
-	/**
112
-	 * Fonction de filtrage compilee a partir des criteres de filtre
113
-	 *
114
-	 * @var string
115
-	 */
116
-	protected $func_filtre = null;
117
-
118
-	/**
119
-	 * Critere {offset, limit}
120
-	 *
121
-	 * @var int
122
-	 * @var int
123
-	 */
124
-	protected $offset = null;
125
-	protected $limit = null;
126
-
127
-	/**
128
-	 * nombre d'elements recuperes depuis la position 0,
129
-	 * en tenant compte des filtres
130
-	 *
131
-	 * @var int
132
-	 */
133
-	protected $fetched = 0;
134
-
135
-	/**
136
-	 * Y a t'il une erreur ?
137
-	 *
138
-	 * @var bool
139
-	 **/
140
-	protected $err = false;
141
-
142
-	/**
143
-	 * Drapeau a activer en cas d'echec
144
-	 * (select SQL errone, non chargement des DATA, etc)
145
-	 */
146
-	public function err() {
147
-		if (method_exists($this->iter, 'err')) {
148
-			return $this->iter->err();
149
-		}
150
-		if (property_exists($this->iter, 'err')) {
151
-			return $this->iter->err;
152
-		}
153
-
154
-		return false;
155
-	}
156
-
157
-	public function __construct(Iterator $iter, $command, $info) {
158
-		parent::__construct($iter);
159
-		parent::rewind(); // remettre a la premiere position (bug? connu de FilterIterator)
160
-
161
-		// recuperer l'iterateur transmis
162
-		$this->iter = $this->getInnerIterator();
163
-		$this->command = $command;
164
-		$this->info = $info;
165
-		$this->pos = 0;
166
-		$this->fetched = 0;
167
-
168
-		// chercher la liste des champs a retourner par
169
-		// fetch si l'objet ne les calcule pas tout seul
170
-		if (!method_exists($this->iter, 'fetch')) {
171
-			$this->calculer_select();
172
-			$this->calculer_filtres();
173
-		}
174
-
175
-		// emptyIterator critere {si} faux n'a pas d'erreur !
176
-		if (isset($this->iter->err)) {
177
-			$this->err = $this->iter->err;
178
-		}
179
-
180
-		// pas d'init a priori, le calcul ne sera fait qu'en cas de besoin (provoque une double requete souvent inutile en sqlite)
181
-		//$this->total = $this->count();
182
-	}
183
-
184
-
185
-	// calcule les elements a retournes par fetch()
186
-	// enleve les elements inutiles du select()
187
-	// 
188
-	private function calculer_select() {
189
-		if ($select = &$this->command['select']) {
190
-			foreach ($select as $s) {
191
-				// /!\ $s = '.nom'
192
-				if ($s[0] == '.') {
193
-					$s = substr($s, 1);
194
-				}
195
-				$this->select[] = $s;
196
-			}
197
-		}
198
-	}
199
-
200
-	// recuperer la valeur d'une balise #X
201
-	// en fonction des methodes 
202
-	// et proprietes disponibles
203
-	public function get_select($nom) {
204
-		if (is_object($this->iter)
205
-			and method_exists($this->iter, $nom)
206
-		) {
207
-			try {
208
-				return $this->iter->$nom();
209
-			} catch (Exception $e) {
210
-				// #GETCHILDREN sur un fichier de DirectoryIterator ...
211
-				spip_log("Methode $nom en echec sur " . get_class($this->iter));
212
-				spip_log("Cela peut être normal : retour d'une ligne de resultat ne pouvant pas calculer cette methode");
213
-
214
-				return '';
215
-			}
216
-		}
217
-		/*
101
+    private $iter;
102
+
103
+    /**
104
+     * Conditions de filtrage
105
+     * ie criteres de selection
106
+     *
107
+     * @var array
108
+     */
109
+    protected $filtre = array();
110
+
111
+    /**
112
+     * Fonction de filtrage compilee a partir des criteres de filtre
113
+     *
114
+     * @var string
115
+     */
116
+    protected $func_filtre = null;
117
+
118
+    /**
119
+     * Critere {offset, limit}
120
+     *
121
+     * @var int
122
+     * @var int
123
+     */
124
+    protected $offset = null;
125
+    protected $limit = null;
126
+
127
+    /**
128
+     * nombre d'elements recuperes depuis la position 0,
129
+     * en tenant compte des filtres
130
+     *
131
+     * @var int
132
+     */
133
+    protected $fetched = 0;
134
+
135
+    /**
136
+     * Y a t'il une erreur ?
137
+     *
138
+     * @var bool
139
+     **/
140
+    protected $err = false;
141
+
142
+    /**
143
+     * Drapeau a activer en cas d'echec
144
+     * (select SQL errone, non chargement des DATA, etc)
145
+     */
146
+    public function err() {
147
+        if (method_exists($this->iter, 'err')) {
148
+            return $this->iter->err();
149
+        }
150
+        if (property_exists($this->iter, 'err')) {
151
+            return $this->iter->err;
152
+        }
153
+
154
+        return false;
155
+    }
156
+
157
+    public function __construct(Iterator $iter, $command, $info) {
158
+        parent::__construct($iter);
159
+        parent::rewind(); // remettre a la premiere position (bug? connu de FilterIterator)
160
+
161
+        // recuperer l'iterateur transmis
162
+        $this->iter = $this->getInnerIterator();
163
+        $this->command = $command;
164
+        $this->info = $info;
165
+        $this->pos = 0;
166
+        $this->fetched = 0;
167
+
168
+        // chercher la liste des champs a retourner par
169
+        // fetch si l'objet ne les calcule pas tout seul
170
+        if (!method_exists($this->iter, 'fetch')) {
171
+            $this->calculer_select();
172
+            $this->calculer_filtres();
173
+        }
174
+
175
+        // emptyIterator critere {si} faux n'a pas d'erreur !
176
+        if (isset($this->iter->err)) {
177
+            $this->err = $this->iter->err;
178
+        }
179
+
180
+        // pas d'init a priori, le calcul ne sera fait qu'en cas de besoin (provoque une double requete souvent inutile en sqlite)
181
+        //$this->total = $this->count();
182
+    }
183
+
184
+
185
+    // calcule les elements a retournes par fetch()
186
+    // enleve les elements inutiles du select()
187
+    // 
188
+    private function calculer_select() {
189
+        if ($select = &$this->command['select']) {
190
+            foreach ($select as $s) {
191
+                // /!\ $s = '.nom'
192
+                if ($s[0] == '.') {
193
+                    $s = substr($s, 1);
194
+                }
195
+                $this->select[] = $s;
196
+            }
197
+        }
198
+    }
199
+
200
+    // recuperer la valeur d'une balise #X
201
+    // en fonction des methodes 
202
+    // et proprietes disponibles
203
+    public function get_select($nom) {
204
+        if (is_object($this->iter)
205
+            and method_exists($this->iter, $nom)
206
+        ) {
207
+            try {
208
+                return $this->iter->$nom();
209
+            } catch (Exception $e) {
210
+                // #GETCHILDREN sur un fichier de DirectoryIterator ...
211
+                spip_log("Methode $nom en echec sur " . get_class($this->iter));
212
+                spip_log("Cela peut être normal : retour d'une ligne de resultat ne pouvant pas calculer cette methode");
213
+
214
+                return '';
215
+            }
216
+        }
217
+        /*
218 218
 		if (property_exists($this->iter, $nom)) {
219 219
 			return $this->iter->$nom;
220 220
 		}*/
221
-		// cle et valeur par defaut
222
-		// ICI PLANTAGE SI ON NE CONTROLE PAS $nom
223
-		if (in_array($nom, array('cle', 'valeur'))
224
-			and method_exists($this, $nom)
225
-		) {
226
-			return $this->$nom();
227
-		}
228
-
229
-		// Par defaut chercher en xpath dans la valeur()
230
-		return table_valeur($this->valeur(), $nom, null);
231
-	}
232
-
233
-
234
-	private function calculer_filtres() {
235
-
236
-		// Issu de calculer_select() de public/composer L.519
237
-		// TODO: externaliser...
238
-		//
239
-		// retirer les criteres vides:
240
-		// {X ?} avec X absent de l'URL
241
-		// {par #ENV{X}} avec X absent de l'URL
242
-		// IN sur collection vide (ce dernier devrait pouvoir etre fait a la compil)
243
-		if ($where = &$this->command['where']) {
244
-			foreach ($where as $k => $v) {
245
-				if (is_array($v)) {
246
-					if ((count($v) >= 2) && ($v[0] == 'REGEXP') && ($v[2] == "'.*'")) {
247
-						$op = false;
248
-					} elseif ((count($v) >= 2) && ($v[0] == 'LIKE') && ($v[2] == "'%'")) {
249
-						$op = false;
250
-					} else {
251
-						$op = $v[0] ? $v[0] : $v;
252
-					}
253
-				} else {
254
-					$op = $v;
255
-				}
256
-				if ((!$op) or ($op == 1) or ($op == '0=0')) {
257
-					unset($where[$k]);
258
-				}
259
-				// traiter {cle IN a,b} ou {valeur !IN a,b}
260
-				if (preg_match(',^\(([\w/]+)(\s+NOT)?\s+IN\s+(\(.*\))\)$,', $op, $regs)) {
261
-					$this->ajouter_filtre($regs[1], 'IN', $regs[3], $regs[2]);
262
-					unset($op, $where[$k]);
263
-				}
264
-			}
265
-			foreach ($where as $k => $v) {
266
-				// 3 possibilites : count($v) =
267
-				// * 1 : {x y} ; on recoit $v[0] = y
268
-				// * 2 : {x !op y} ; on recoit $v[0] = 'NOT', $v[1] = array() // array du type {x op y}
269
-				// * 3 : {x op y} ; on recoit $v[0] = 'op', $v[1] = x, $v[2] = y
270
-
271
-				// 1 : forcement traite par un critere, on passe
272
-				if (!$v or count($v) == 1) {
273
-					continue;
274
-				}
275
-				if (count($v) == 2 and is_array($v[1])) {
276
-					$this->ajouter_filtre($v[1][1], $v[1][0], $v[1][2], 'NOT');
277
-				}
278
-				if (count($v) == 3) {
279
-					$this->ajouter_filtre($v[1], $v[0], $v[2]);
280
-				}
281
-			}
282
-		}
283
-
284
-		// critere {2,7}
285
-		if (isset($this->command['limit']) and $this->command['limit']) {
286
-			$limit = explode(',', $this->command['limit']);
287
-			$this->offset = $limit[0];
288
-			$this->limit = $limit[1];
289
-		}
290
-
291
-		// Creer la fonction de filtrage sur $this
292
-		if ($this->filtre) {
293
-			$filtres = 'return (' . join(') AND (', $this->filtre) . ');';
294
-			$this->func_filtre = function () use ($filtres) {
295
-				return eval($filtres);
296
-			};
297
-		}
298
-	}
299
-
300
-
301
-	protected function ajouter_filtre($cle, $op, $valeur, $not = false) {
302
-		if (method_exists($this->iter, 'exception_des_criteres')) {
303
-			if (in_array($cle, $this->iter->exception_des_criteres())) {
304
-				return;
305
-			}
306
-		}
307
-		// TODO: analyser le filtre pour refuser ce qu'on ne sait pas traiter ?
308
-		# mais c'est normalement deja opere par calculer_critere_infixe()
309
-		# qui regarde la description 'desc' (en casse reelle d'ailleurs : {isDir=1}
310
-		# ne sera pas vu si l'on a defini desc['field']['isdir'] pour que #ISDIR soit present.
311
-		# il faudrait peut etre definir les 2 champs isDir et isdir... a reflechir...
312
-
313
-		# if (!in_array($cle, array('cle', 'valeur')))
314
-		#	return;
315
-
316
-		$a = '$this->get_select(\'' . $cle . '\')';
317
-
318
-		$filtre = '';
319
-
320
-		if ($op == 'REGEXP') {
321
-			$filtre = 'filtrer("match", ' . $a . ', ' . str_replace('\"', '"', $valeur) . ')';
322
-			$op = '';
323
-		} else {
324
-			if ($op == 'LIKE') {
325
-				$valeur = str_replace(array('\"', '_', '%'), array('"', '.', '.*'), preg_quote($valeur));
326
-				$filtre = 'filtrer("match", ' . $a . ', ' . $valeur . ')';
327
-				$op = '';
328
-			} else {
329
-				if ($op == '=') {
330
-					$op = '==';
331
-				} else {
332
-					if ($op == 'IN') {
333
-						$filtre = 'in_array(' . $a . ', array' . $valeur . ')';
334
-						$op = '';
335
-					} else {
336
-						if (!in_array($op, array('<', '<=', '>', '>='))) {
337
-							spip_log('operateur non reconnu ' . $op); // [todo] mettre une erreur de squelette
338
-							$op = '';
339
-						}
340
-					}
341
-				}
342
-			}
343
-		}
344
-
345
-		if ($op) {
346
-			$filtre = $a . $op . str_replace('\"', '"', $valeur);
347
-		}
348
-
349
-		if ($not) {
350
-			$filtre = "!($filtre)";
351
-		}
352
-
353
-		if ($filtre) {
354
-			$this->filtre[] = $filtre;
355
-		}
356
-	}
357
-
358
-
359
-	public function next() {
360
-		$this->pos++;
361
-		parent::next();
362
-	}
363
-
364
-	/**
365
-	 * revient au depart
366
-	 *
367
-	 * @return void
368
-	 */
369
-	public function rewind() {
370
-		$this->pos = 0;
371
-		$this->fetched = 0;
372
-		parent::rewind();
373
-	}
374
-
375
-
376
-	# Extension SPIP des iterateurs PHP
377
-	/**
378
-	 * type de l'iterateur
379
-	 *
380
-	 * @var string
381
-	 */
382
-	protected $type;
383
-
384
-	/**
385
-	 * parametres de l'iterateur
386
-	 *
387
-	 * @var array
388
-	 */
389
-	protected $command;
390
-
391
-	/**
392
-	 * infos de compilateur
393
-	 *
394
-	 * @var array
395
-	 */
396
-	protected $info;
397
-
398
-	/**
399
-	 * position courante de l'iterateur
400
-	 *
401
-	 * @var int
402
-	 */
403
-	protected $pos = null;
404
-
405
-	/**
406
-	 * nombre total resultats dans l'iterateur
407
-	 *
408
-	 * @var int
409
-	 */
410
-	protected $total = null;
411
-
412
-	/**
413
-	 * nombre maximal de recherche pour $total
414
-	 * si l'iterateur n'implemente pas de fonction specifique
415
-	 */
416
-	protected $max = 100000;
417
-
418
-
419
-	/**
420
-	 * Liste des champs a inserer dans les $row
421
-	 * retournes par ->fetch()
422
-	 */
423
-	protected $select = array();
424
-
425
-
426
-	/**
427
-	 * aller a la position absolue n,
428
-	 * comptee depuis le debut
429
-	 *
430
-	 * @param int $n
431
-	 *   absolute pos
432
-	 * @param string $continue
433
-	 *   param for sql_ api
434
-	 * @return bool
435
-	 *   success or fail if not implemented
436
-	 */
437
-	public function seek($n = 0, $continue = null) {
438
-		if ($this->func_filtre or !method_exists($this->iter, 'seek') or !$this->iter->seek($n)) {
439
-			$this->seek_loop($n);
440
-		}
441
-		$this->pos = $n;
442
-		$this->fetched = $n;
443
-
444
-		return true;
445
-	}
446
-
447
-	/*
221
+        // cle et valeur par defaut
222
+        // ICI PLANTAGE SI ON NE CONTROLE PAS $nom
223
+        if (in_array($nom, array('cle', 'valeur'))
224
+            and method_exists($this, $nom)
225
+        ) {
226
+            return $this->$nom();
227
+        }
228
+
229
+        // Par defaut chercher en xpath dans la valeur()
230
+        return table_valeur($this->valeur(), $nom, null);
231
+    }
232
+
233
+
234
+    private function calculer_filtres() {
235
+
236
+        // Issu de calculer_select() de public/composer L.519
237
+        // TODO: externaliser...
238
+        //
239
+        // retirer les criteres vides:
240
+        // {X ?} avec X absent de l'URL
241
+        // {par #ENV{X}} avec X absent de l'URL
242
+        // IN sur collection vide (ce dernier devrait pouvoir etre fait a la compil)
243
+        if ($where = &$this->command['where']) {
244
+            foreach ($where as $k => $v) {
245
+                if (is_array($v)) {
246
+                    if ((count($v) >= 2) && ($v[0] == 'REGEXP') && ($v[2] == "'.*'")) {
247
+                        $op = false;
248
+                    } elseif ((count($v) >= 2) && ($v[0] == 'LIKE') && ($v[2] == "'%'")) {
249
+                        $op = false;
250
+                    } else {
251
+                        $op = $v[0] ? $v[0] : $v;
252
+                    }
253
+                } else {
254
+                    $op = $v;
255
+                }
256
+                if ((!$op) or ($op == 1) or ($op == '0=0')) {
257
+                    unset($where[$k]);
258
+                }
259
+                // traiter {cle IN a,b} ou {valeur !IN a,b}
260
+                if (preg_match(',^\(([\w/]+)(\s+NOT)?\s+IN\s+(\(.*\))\)$,', $op, $regs)) {
261
+                    $this->ajouter_filtre($regs[1], 'IN', $regs[3], $regs[2]);
262
+                    unset($op, $where[$k]);
263
+                }
264
+            }
265
+            foreach ($where as $k => $v) {
266
+                // 3 possibilites : count($v) =
267
+                // * 1 : {x y} ; on recoit $v[0] = y
268
+                // * 2 : {x !op y} ; on recoit $v[0] = 'NOT', $v[1] = array() // array du type {x op y}
269
+                // * 3 : {x op y} ; on recoit $v[0] = 'op', $v[1] = x, $v[2] = y
270
+
271
+                // 1 : forcement traite par un critere, on passe
272
+                if (!$v or count($v) == 1) {
273
+                    continue;
274
+                }
275
+                if (count($v) == 2 and is_array($v[1])) {
276
+                    $this->ajouter_filtre($v[1][1], $v[1][0], $v[1][2], 'NOT');
277
+                }
278
+                if (count($v) == 3) {
279
+                    $this->ajouter_filtre($v[1], $v[0], $v[2]);
280
+                }
281
+            }
282
+        }
283
+
284
+        // critere {2,7}
285
+        if (isset($this->command['limit']) and $this->command['limit']) {
286
+            $limit = explode(',', $this->command['limit']);
287
+            $this->offset = $limit[0];
288
+            $this->limit = $limit[1];
289
+        }
290
+
291
+        // Creer la fonction de filtrage sur $this
292
+        if ($this->filtre) {
293
+            $filtres = 'return (' . join(') AND (', $this->filtre) . ');';
294
+            $this->func_filtre = function () use ($filtres) {
295
+                return eval($filtres);
296
+            };
297
+        }
298
+    }
299
+
300
+
301
+    protected function ajouter_filtre($cle, $op, $valeur, $not = false) {
302
+        if (method_exists($this->iter, 'exception_des_criteres')) {
303
+            if (in_array($cle, $this->iter->exception_des_criteres())) {
304
+                return;
305
+            }
306
+        }
307
+        // TODO: analyser le filtre pour refuser ce qu'on ne sait pas traiter ?
308
+        # mais c'est normalement deja opere par calculer_critere_infixe()
309
+        # qui regarde la description 'desc' (en casse reelle d'ailleurs : {isDir=1}
310
+        # ne sera pas vu si l'on a defini desc['field']['isdir'] pour que #ISDIR soit present.
311
+        # il faudrait peut etre definir les 2 champs isDir et isdir... a reflechir...
312
+
313
+        # if (!in_array($cle, array('cle', 'valeur')))
314
+        #	return;
315
+
316
+        $a = '$this->get_select(\'' . $cle . '\')';
317
+
318
+        $filtre = '';
319
+
320
+        if ($op == 'REGEXP') {
321
+            $filtre = 'filtrer("match", ' . $a . ', ' . str_replace('\"', '"', $valeur) . ')';
322
+            $op = '';
323
+        } else {
324
+            if ($op == 'LIKE') {
325
+                $valeur = str_replace(array('\"', '_', '%'), array('"', '.', '.*'), preg_quote($valeur));
326
+                $filtre = 'filtrer("match", ' . $a . ', ' . $valeur . ')';
327
+                $op = '';
328
+            } else {
329
+                if ($op == '=') {
330
+                    $op = '==';
331
+                } else {
332
+                    if ($op == 'IN') {
333
+                        $filtre = 'in_array(' . $a . ', array' . $valeur . ')';
334
+                        $op = '';
335
+                    } else {
336
+                        if (!in_array($op, array('<', '<=', '>', '>='))) {
337
+                            spip_log('operateur non reconnu ' . $op); // [todo] mettre une erreur de squelette
338
+                            $op = '';
339
+                        }
340
+                    }
341
+                }
342
+            }
343
+        }
344
+
345
+        if ($op) {
346
+            $filtre = $a . $op . str_replace('\"', '"', $valeur);
347
+        }
348
+
349
+        if ($not) {
350
+            $filtre = "!($filtre)";
351
+        }
352
+
353
+        if ($filtre) {
354
+            $this->filtre[] = $filtre;
355
+        }
356
+    }
357
+
358
+
359
+    public function next() {
360
+        $this->pos++;
361
+        parent::next();
362
+    }
363
+
364
+    /**
365
+     * revient au depart
366
+     *
367
+     * @return void
368
+     */
369
+    public function rewind() {
370
+        $this->pos = 0;
371
+        $this->fetched = 0;
372
+        parent::rewind();
373
+    }
374
+
375
+
376
+    # Extension SPIP des iterateurs PHP
377
+    /**
378
+     * type de l'iterateur
379
+     *
380
+     * @var string
381
+     */
382
+    protected $type;
383
+
384
+    /**
385
+     * parametres de l'iterateur
386
+     *
387
+     * @var array
388
+     */
389
+    protected $command;
390
+
391
+    /**
392
+     * infos de compilateur
393
+     *
394
+     * @var array
395
+     */
396
+    protected $info;
397
+
398
+    /**
399
+     * position courante de l'iterateur
400
+     *
401
+     * @var int
402
+     */
403
+    protected $pos = null;
404
+
405
+    /**
406
+     * nombre total resultats dans l'iterateur
407
+     *
408
+     * @var int
409
+     */
410
+    protected $total = null;
411
+
412
+    /**
413
+     * nombre maximal de recherche pour $total
414
+     * si l'iterateur n'implemente pas de fonction specifique
415
+     */
416
+    protected $max = 100000;
417
+
418
+
419
+    /**
420
+     * Liste des champs a inserer dans les $row
421
+     * retournes par ->fetch()
422
+     */
423
+    protected $select = array();
424
+
425
+
426
+    /**
427
+     * aller a la position absolue n,
428
+     * comptee depuis le debut
429
+     *
430
+     * @param int $n
431
+     *   absolute pos
432
+     * @param string $continue
433
+     *   param for sql_ api
434
+     * @return bool
435
+     *   success or fail if not implemented
436
+     */
437
+    public function seek($n = 0, $continue = null) {
438
+        if ($this->func_filtre or !method_exists($this->iter, 'seek') or !$this->iter->seek($n)) {
439
+            $this->seek_loop($n);
440
+        }
441
+        $this->pos = $n;
442
+        $this->fetched = $n;
443
+
444
+        return true;
445
+    }
446
+
447
+    /*
448 448
 	 * aller a la position $n en parcourant
449 449
 	 * un par un tous les elements
450 450
 	 */
451
-	private function seek_loop($n) {
452
-		if ($this->pos > $n) {
453
-			$this->rewind();
454
-		}
455
-
456
-		while ($this->pos < $n and $this->valid()) {
457
-			$this->next();
458
-		}
459
-
460
-		return true;
461
-	}
462
-
463
-	/**
464
-	 * Avancer de $saut pas
465
-	 *
466
-	 * @param  $saut
467
-	 * @param  $max
468
-	 * @return int
469
-	 */
470
-	public function skip($saut, $max = null) {
471
-		// pas de saut en arriere autorise pour cette fonction
472
-		if (($saut = intval($saut)) <= 0) {
473
-			return $this->pos;
474
-		}
475
-		$seek = $this->pos + $saut;
476
-		// si le saut fait depasser le maxi, on libere la resource
477
-		// et on sort
478
-		if (is_null($max)) {
479
-			$max = $this->count();
480
-		}
481
-
482
-		if ($seek >= $max or $seek >= $this->count()) {
483
-			// sortie plus rapide que de faire next() jusqu'a la fin !
484
-			$this->free();
485
-
486
-			return $max;
487
-		}
488
-
489
-		$this->seek($seek);
490
-
491
-		return $this->pos;
492
-	}
493
-
494
-	/**
495
-	 * Renvoyer un tableau des donnees correspondantes
496
-	 * a la position courante de l'iterateur
497
-	 * en controlant si on respecte le filtre
498
-	 * Appliquer aussi le critere {offset,limit}
499
-	 *
500
-	 * @return array|bool
501
-	 */
502
-	public function fetch() {
503
-		if (method_exists($this->iter, 'fetch')) {
504
-			return $this->iter->fetch();
505
-		} else {
506
-
507
-			while ($this->valid()
508
-				and (
509
-					!$this->accept()
510
-					or (isset($this->offset) and $this->fetched++ < $this->offset)
511
-				)) {
512
-				$this->next();
513
-			}
514
-
515
-			if (!$this->valid()) {
516
-				return false;
517
-			}
518
-
519
-			if (isset($this->limit)
520
-				and $this->fetched > $this->offset + $this->limit
521
-			) {
522
-				return false;
523
-			}
524
-
525
-			$r = array();
526
-			foreach ($this->select as $nom) {
527
-				$r[$nom] = $this->get_select($nom);
528
-			}
529
-			$this->next();
530
-
531
-			return $r;
532
-		}
533
-	}
534
-
535
-	// retourner la cle pour #CLE
536
-	public function cle() {
537
-		return $this->key();
538
-	}
539
-
540
-	// retourner la valeur pour #VALEUR
541
-	public function valeur() {
542
-		return $this->current();
543
-	}
544
-
545
-	/**
546
-	 * Accepte-t-on l'entree courante lue ?
547
-	 * On execute les filtres pour le savoir.
548
-	 **/
549
-	public function accept() {
550
-		if ($f = $this->func_filtre) {
551
-			return $f();
552
-		}
553
-
554
-		return true;
555
-	}
556
-
557
-	/**
558
-	 * liberer la ressource
559
-	 *
560
-	 * @return bool
561
-	 */
562
-	public function free() {
563
-		if (method_exists($this->iter, 'free')) {
564
-			$this->iter->free();
565
-		}
566
-		$this->pos = $this->total = 0;
567
-
568
-		return true;
569
-	}
570
-
571
-	/**
572
-	 * Compter le nombre total de resultats
573
-	 * pour #TOTAL_BOUCLE
574
-	 *
575
-	 * @return int
576
-	 */
577
-	public function count() {
578
-		if (is_null($this->total)) {
579
-			if (method_exists($this->iter, 'count')
580
-				and !$this->func_filtre
581
-			) {
582
-				return $this->total = $this->iter->count();
583
-			} else {
584
-				// compter les lignes et rembobiner
585
-				$total = 0;
586
-				$pos = $this->pos; // sauver la position
587
-				$this->rewind();
588
-				while ($this->fetch() and $total < $this->max) {
589
-					$total++;
590
-				}
591
-				$this->seek($pos);
592
-				$this->total = $total;
593
-			}
594
-		}
595
-
596
-		return $this->total;
597
-	}
451
+    private function seek_loop($n) {
452
+        if ($this->pos > $n) {
453
+            $this->rewind();
454
+        }
455
+
456
+        while ($this->pos < $n and $this->valid()) {
457
+            $this->next();
458
+        }
459
+
460
+        return true;
461
+    }
462
+
463
+    /**
464
+     * Avancer de $saut pas
465
+     *
466
+     * @param  $saut
467
+     * @param  $max
468
+     * @return int
469
+     */
470
+    public function skip($saut, $max = null) {
471
+        // pas de saut en arriere autorise pour cette fonction
472
+        if (($saut = intval($saut)) <= 0) {
473
+            return $this->pos;
474
+        }
475
+        $seek = $this->pos + $saut;
476
+        // si le saut fait depasser le maxi, on libere la resource
477
+        // et on sort
478
+        if (is_null($max)) {
479
+            $max = $this->count();
480
+        }
481
+
482
+        if ($seek >= $max or $seek >= $this->count()) {
483
+            // sortie plus rapide que de faire next() jusqu'a la fin !
484
+            $this->free();
485
+
486
+            return $max;
487
+        }
488
+
489
+        $this->seek($seek);
490
+
491
+        return $this->pos;
492
+    }
493
+
494
+    /**
495
+     * Renvoyer un tableau des donnees correspondantes
496
+     * a la position courante de l'iterateur
497
+     * en controlant si on respecte le filtre
498
+     * Appliquer aussi le critere {offset,limit}
499
+     *
500
+     * @return array|bool
501
+     */
502
+    public function fetch() {
503
+        if (method_exists($this->iter, 'fetch')) {
504
+            return $this->iter->fetch();
505
+        } else {
506
+
507
+            while ($this->valid()
508
+                and (
509
+                    !$this->accept()
510
+                    or (isset($this->offset) and $this->fetched++ < $this->offset)
511
+                )) {
512
+                $this->next();
513
+            }
514
+
515
+            if (!$this->valid()) {
516
+                return false;
517
+            }
518
+
519
+            if (isset($this->limit)
520
+                and $this->fetched > $this->offset + $this->limit
521
+            ) {
522
+                return false;
523
+            }
524
+
525
+            $r = array();
526
+            foreach ($this->select as $nom) {
527
+                $r[$nom] = $this->get_select($nom);
528
+            }
529
+            $this->next();
530
+
531
+            return $r;
532
+        }
533
+    }
534
+
535
+    // retourner la cle pour #CLE
536
+    public function cle() {
537
+        return $this->key();
538
+    }
539
+
540
+    // retourner la valeur pour #VALEUR
541
+    public function valeur() {
542
+        return $this->current();
543
+    }
544
+
545
+    /**
546
+     * Accepte-t-on l'entree courante lue ?
547
+     * On execute les filtres pour le savoir.
548
+     **/
549
+    public function accept() {
550
+        if ($f = $this->func_filtre) {
551
+            return $f();
552
+        }
553
+
554
+        return true;
555
+    }
556
+
557
+    /**
558
+     * liberer la ressource
559
+     *
560
+     * @return bool
561
+     */
562
+    public function free() {
563
+        if (method_exists($this->iter, 'free')) {
564
+            $this->iter->free();
565
+        }
566
+        $this->pos = $this->total = 0;
567
+
568
+        return true;
569
+    }
570
+
571
+    /**
572
+     * Compter le nombre total de resultats
573
+     * pour #TOTAL_BOUCLE
574
+     *
575
+     * @return int
576
+     */
577
+    public function count() {
578
+        if (is_null($this->total)) {
579
+            if (method_exists($this->iter, 'count')
580
+                and !$this->func_filtre
581
+            ) {
582
+                return $this->total = $this->iter->count();
583
+            } else {
584
+                // compter les lignes et rembobiner
585
+                $total = 0;
586
+                $pos = $this->pos; // sauver la position
587
+                $this->rewind();
588
+                while ($this->fetch() and $total < $this->max) {
589
+                    $total++;
590
+                }
591
+                $this->seek($pos);
592
+                $this->total = $total;
593
+            }
594
+        }
595
+
596
+        return $this->total;
597
+    }
598 598
 
599 599
 }
Please login to merge, or discard this patch.