Completed
Pull Request — master (#36)
by
unknown
06:08
created
ecrire/req/pg.exp.php 4 patches
Doc Comments   +32 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,6 +132,11 @@  discard block
 block discarded – undo
132 132
 
133 133
 // Par ou ca passe une fois les traductions faites
134 134
 // http://code.spip.net/@spip_pg_trace_query
135
+/**
136
+ * @param string $query
137
+ *
138
+ * @return resource
139
+ */
135 140
 function spip_pg_trace_query($query, $serveur = '') {
136 141
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
137 142
 	$prefixe = $connexion['prefixe'];
@@ -290,6 +295,9 @@  discard block
 block discarded – undo
290 295
 }
291 296
 
292 297
 // http://code.spip.net/@spip_pg_alter_change
298
+/**
299
+ * @param string $arg
300
+ */
293 301
 function spip_pg_alter_change($table, $arg, $serveur = '', $requeter = true) {
294 302
 	if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
295 303
 		spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
@@ -416,6 +424,7 @@  discard block
 block discarded – undo
416 424
  * @param string /array $champs : liste de champs sur lesquels s'applique l'index
417 425
  * @param string $serveur : nom de la connexion sql utilisee
418 426
  * @param bool $requeter : true pour executer la requete ou false pour retourner le texte de la requete
427
+ * @param string $champs
419 428
  *
420 429
  * @return bool ou requete
421 430
  */
@@ -591,6 +600,9 @@  discard block
 block discarded – undo
591 600
 }
592 601
 
593 602
 // http://code.spip.net/@spip_pg_orderby
603
+/**
604
+ * @param string $order
605
+ */
594 606
 function spip_pg_orderby($order, $select) {
595 607
 	$res = array();
596 608
 	$arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
@@ -765,6 +777,9 @@  discard block
 block discarded – undo
765 777
 }
766 778
 
767 779
 // http://code.spip.net/@calculer_pg_where
780
+/**
781
+ * @param string $v
782
+ */
768 783
 function calculer_pg_where($v) {
769 784
 	if (!is_array($v)) {
770 785
 		return spip_pg_frommysql($v);
@@ -790,6 +805,9 @@  discard block
 block discarded – undo
790 805
 
791 806
 
792 807
 // http://code.spip.net/@calculer_pg_expression
808
+/**
809
+ * @param string $expression
810
+ */
793 811
 function calculer_pg_expression($expression, $v, $join = 'AND') {
794 812
 	if (empty($v)) {
795 813
 		return '';
@@ -841,6 +859,9 @@  discard block
 block discarded – undo
841 859
 }
842 860
 
843 861
 // http://code.spip.net/@spip_pg_fetch
862
+/**
863
+ * @param resource $res
864
+ */
844 865
 function spip_pg_fetch($res, $t = '', $serveur = '', $requeter = true) {
845 866
 
846 867
 	if ($res) {
@@ -912,6 +933,10 @@  discard block
 block discarded – undo
912 933
 }
913 934
 
914 935
 // http://code.spip.net/@spip_pg_insert
936
+/**
937
+ * @param string $champs
938
+ * @param string $valeurs
939
+ */
915 940
 function spip_pg_insert($table, $champs, $valeurs, $desc = array(), $serveur = '', $requeter = true) {
916 941
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
917 942
 	$prefixe = $connexion['prefixe'];
@@ -1148,6 +1173,9 @@  discard block
 block discarded – undo
1148 1173
 // Pas extensible pour le moment,
1149 1174
 
1150 1175
 // http://code.spip.net/@spip_pg_sequence
1176
+/**
1177
+ * @return string
1178
+ */
1151 1179
 function spip_pg_sequence($table, $raw = false) {
1152 1180
 
1153 1181
 	include_spip('base/serial');
@@ -1261,6 +1289,9 @@  discard block
 block discarded – undo
1261 1289
 }
1262 1290
 
1263 1291
 // http://code.spip.net/@spip_pg_error
1292
+/**
1293
+ * @param string $serveur
1294
+ */
1264 1295
 function spip_pg_error($query = '', $serveur, $requeter = true) {
1265 1296
 	$link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1266 1297
 	$s = $link ? pg_last_error($link) : pg_last_error();
@@ -1311,7 +1342,7 @@  discard block
 block discarded – undo
1311 1342
  * @param bool $requeter
1312 1343
  *     true pour éxecuter la requête
1313 1344
  *     false pour retourner le texte de la requête.
1314
- * @return ressource
1345
+ * @return resource
1315 1346
  *     Ressource à utiliser avec sql_fetch()
1316 1347
  **/
1317 1348
 function spip_pg_showbase($match, $serveur = '', $requeter = true) {
Please login to merge, or discard this patch.
Spacing   +81 added lines, -82 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 	if (!$link) {
66 66
 		$erreurs[] = pg_last_error();
67 67
 		foreach ($erreurs as $e) {
68
-			spip_log('Echec pg_connect. Erreur : ' . $e, 'pg.' . _LOG_HS);
68
+			spip_log('Echec pg_connect. Erreur : '.$e, 'pg.'._LOG_HS);
69 69
 		}
70 70
 
71 71
 		return false;
@@ -82,8 +82,8 @@  discard block
 block discarded – undo
82 82
 		);
83 83
 	}
84 84
 
85
-	spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),
86
-		'pg.' . _LOG_DEBUG);
85
+	spip_log("Connexion vers $host, base $db, prefixe $prefixe ".($link ? 'operationnelle' : 'impossible'),
86
+		'pg.'._LOG_DEBUG);
87 87
 
88 88
 	return !$link ? false : array(
89 89
 		'db' => $db,
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 	} else {
172 172
 		$suite = '';
173 173
 	}
174
-	$query = preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
174
+	$query = preg_replace('/([,\s])spip_/', '\1'.$prefixe.'_', $query).$suite;
175 175
 
176 176
 	// renvoyer la requete inerte si demandee
177 177
 	if (!$requeter) {
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 	// ou revoir l'api de sql_alter en creant un 
242 242
 	// sql_alter_table($table,array($actions));
243 243
 	if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)) {
244
-		spip_log("$query mal comprise", 'pg.' . _LOG_ERREUR);
244
+		spip_log("$query mal comprise", 'pg.'._LOG_ERREUR);
245 245
 
246 246
 		return false;
247 247
 	}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	$i = 0;
255 255
 	$ouverte = false;
256 256
 	while ($do = array_shift($todo)) {
257
-		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do;
257
+		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i].",".$do : $do;
258 258
 		$o = (false !== strpos($do, "("));
259 259
 		$f = (false !== strpos($do, ")"));
260 260
 		if ($o and !$f) {
@@ -267,24 +267,24 @@  discard block
 block discarded – undo
267 267
 		}
268 268
 	}
269 269
 	$todo = $todo2;
270
-	$query = $debut . ' ' . array_shift($todo);
270
+	$query = $debut.' '.array_shift($todo);
271 271
 
272 272
 	if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) {
273
-		spip_log("$query incompris", 'pg.' . _LOG_ERREUR);
273
+		spip_log("$query incompris", 'pg.'._LOG_ERREUR);
274 274
 	} else {
275 275
 		if ($r[1]) {
276
-			spip_log("j'ignore IGNORE dans $query", 'pg.' . _LOG_AVERTISSEMENT);
276
+			spip_log("j'ignore IGNORE dans $query", 'pg.'._LOG_AVERTISSEMENT);
277 277
 		}
278
-		$f = 'spip_pg_alter_' . strtolower($r[3]);
278
+		$f = 'spip_pg_alter_'.strtolower($r[3]);
279 279
 		if (function_exists($f)) {
280 280
 			$f($r[2], $r[4], $serveur, $requeter);
281 281
 		} else {
282
-			spip_log("$query non prevu", 'pg.' . _LOG_ERREUR);
282
+			spip_log("$query non prevu", 'pg.'._LOG_ERREUR);
283 283
 		}
284 284
 	}
285 285
 	// Alter a plusieurs args. Faudrait optimiser.
286 286
 	if ($todo) {
287
-		spip_pg_alter("TABLE $table " . join(',', $todo));
287
+		spip_pg_alter("TABLE $table ".join(',', $todo));
288 288
 	}
289 289
 
290 290
 }
@@ -292,10 +292,10 @@  discard block
 block discarded – undo
292 292
 // http://code.spip.net/@spip_pg_alter_change
293 293
 function spip_pg_alter_change($table, $arg, $serveur = '', $requeter = true) {
294 294
 	if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
295
-		spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
295
+		spip_log("alter change: $arg  incompris", 'pg.'._LOG_ERREUR);
296 296
 	} else {
297 297
 		list(, $old, $new, $type, $default, $null, $def2) = $r;
298
-		$actions = array("ALTER $old TYPE " . mysql2pg_type($type));
298
+		$actions = array("ALTER $old TYPE ".mysql2pg_type($type));
299 299
 		if ($null) {
300 300
 			$actions[] = "ALTER $old SET NOT NULL";
301 301
 		} else {
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 			$actions[] = "ALTER $old DROP DEFAULT";
309 309
 		}
310 310
 
311
-		spip_pg_query("ALTER TABLE $table " . join(', ', $actions));
311
+		spip_pg_query("ALTER TABLE $table ".join(', ', $actions));
312 312
 
313 313
 		if ($old != $new) {
314 314
 			spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur);
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 // http://code.spip.net/@spip_pg_alter_add
320 320
 function spip_pg_alter_add($table, $arg, $serveur = '', $requeter = true) {
321 321
 	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) {
322
-		spip_log("alter add $arg  incompris", 'pg.' . _LOG_ERREUR);
322
+		spip_log("alter add $arg  incompris", 'pg.'._LOG_ERREUR);
323 323
 
324 324
 		return null;
325 325
 	}
@@ -329,13 +329,13 @@  discard block
 block discarded – undo
329 329
 			$m[2] = $n[1];
330 330
 		}
331 331
 
332
-		return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter);
332
+		return spip_pg_query("ALTER TABLE $table ADD ".$m[1].' '.mysql2pg_type($m[2]), $serveur, $requeter);
333 333
 	} elseif ($r[1][0] == 'P') {
334 334
 		// la primary peut etre sur plusieurs champs
335 335
 		$r[2] = trim(str_replace('`', '', $r[2]));
336 336
 		$m = ($r[2][0] == '(') ? substr($r[2], 1, -1) : $r[2];
337 337
 
338
-		return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" . '_pkey PRIMARY KEY (' . $m . ')', $serveur,
338
+		return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table".'_pkey PRIMARY KEY ('.$m.')', $serveur,
339 339
 			$requeter);
340 340
 	} else {
341 341
 		preg_match('/([^\s,]*)\s*(.*)?/', $r[2], $m);
@@ -369,23 +369,23 @@  discard block
 block discarded – undo
369 369
 // http://code.spip.net/@spip_pg_alter_drop
370 370
 function spip_pg_alter_drop($table, $arg, $serveur = '', $requeter = true) {
371 371
 	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) {
372
-		spip_log("alter drop: $arg  incompris", 'pg.' . _LOG_ERREUR);
372
+		spip_log("alter drop: $arg  incompris", 'pg.'._LOG_ERREUR);
373 373
 	} else {
374 374
 		if (!$r[1] or $r[1] == 'COLUMN') {
375
-			return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur);
375
+			return spip_pg_query("ALTER TABLE $table DROP ".$r[2], $serveur);
376 376
 		} elseif ($r[1][0] == 'P') {
377
-			return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur);
377
+			return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table".'_pkey', $serveur);
378 378
 		} else {
379
-			return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur);
379
+			return spip_pg_query("DROP INDEX ".$table.'_'.$r[2], $serveur);
380 380
 		}
381 381
 	}
382 382
 }
383 383
 
384 384
 function spip_pg_alter_modify($table, $arg, $serveur = '', $requeter = true) {
385 385
 	if (!preg_match('/^`?(\w+)`?\s+(.*)$/', $arg, $r)) {
386
-		spip_log("alter modify: $arg  incompris", 'pg.' . _LOG_ERREUR);
386
+		spip_log("alter modify: $arg  incompris", 'pg.'._LOG_ERREUR);
387 387
 	} else {
388
-		return spip_pg_alter_change($table, $r[1] . ' ' . $arg, $serveur = '', $requeter = true);
388
+		return spip_pg_alter_change($table, $r[1].' '.$arg, $serveur = '', $requeter = true);
389 389
 	}
390 390
 }
391 391
 
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 	} elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) {
402 402
 		$rename = $r[2];
403 403
 	} else {
404
-		spip_log("alter rename: $arg  incompris", 'pg.' . _LOG_ERREUR);
404
+		spip_log("alter rename: $arg  incompris", 'pg.'._LOG_ERREUR);
405 405
 	}
406 406
 
407 407
 	return $rename ? spip_pg_query("ALTER TABLE $table RENAME TO $rename") : false;
@@ -421,8 +421,8 @@  discard block
 block discarded – undo
421 421
  */
422 422
 function spip_pg_create_index($nom, $table, $champs, $serveur = '', $requeter = true) {
423 423
 	if (!($nom or $table or $champs)) {
424
-		spip_log("Champ manquant pour creer un index pg ($nom, $table, (" . @join(',', $champs) . "))",
425
-			'pg.' . _LOG_ERREUR);
424
+		spip_log("Champ manquant pour creer un index pg ($nom, $table, (".@join(',', $champs)."))",
425
+			'pg.'._LOG_ERREUR);
426 426
 
427 427
 		return false;
428 428
 	}
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 
433 433
 	// PG ne differentie pas noms des index en fonction des tables
434 434
 	// il faut donc creer des noms uniques d'index pour une base pg
435
-	$nom = $table . '_' . $nom;
435
+	$nom = $table.'_'.$nom;
436 436
 	// enlever d'eventuelles parentheses deja presentes sur champs
437 437
 	if (!is_array($champs)) {
438 438
 		if ($champs[0] == "(") {
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 		}
441 441
 		$champs = array($champs);
442 442
 	}
443
-	$query = "CREATE INDEX $nom ON $table (" . join(',', $champs) . ")";
443
+	$query = "CREATE INDEX $nom ON $table (".join(',', $champs).")";
444 444
 	if (!$requeter) {
445 445
 		return $query;
446 446
 	}
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
 	} else {
465 465
 		$suite = '';
466 466
 	}
467
-	$query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
467
+	$query = 'EXPLAIN '.preg_replace('/([,\s])spip_/', '\1'.$prefixe.'_', $query).$suite;
468 468
 
469 469
 	if (!$requeter) {
470 470
 		return $query;
@@ -559,14 +559,14 @@  discard block
 block discarded – undo
559 559
 		}
560 560
 	}
561 561
 	$from = spip_pg_from($from, $prefixe);
562
-	$query = "SELECT " . $select
562
+	$query = "SELECT ".$select
563 563
 		. (!$from ? '' : "\nFROM $from")
564
-		. (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
564
+		. (!$where ? '' : ("\nWHERE ".(!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
565 565
 				array_map('calculer_pg_where', $where))))))
566 566
 		. spip_pg_groupby($groupby, $from, $select)
567 567
 		. (!$having ? '' : "\nHAVING $having")
568 568
 		. ($orderby ? ("\nORDER BY $orderby") : '')
569
-		. (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset")));
569
+		. (!$limit ? '' : (" LIMIT $count".(!$offset ? '' : " OFFSET $offset")));
570 570
 
571 571
 	// renvoyer la requete inerte si demandee
572 572
 	if ($requeter === false) {
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 
576 576
 	$r = spip_pg_trace_query($query, $serveur);
577 577
 
578
-	return $r ? $r : $query;;
578
+	return $r ? $r : $query; ;
579 579
 }
580 580
 
581 581
 // Le traitement des prefixes de table dans un Select se limite au FROM
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
 		$from = spip_pg_select_as($from);
588 588
 	}
589 589
 
590
-	return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1' . $prefixe . '_', $from);
590
+	return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1'.$prefixe.'_', $from);
591 591
 }
592 592
 
593 593
 // http://code.spip.net/@spip_pg_orderby
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 	$arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
597 597
 
598 598
 	foreach ($arg as $v) {
599
-		if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v . '/', $select, $m)) {
599
+		if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+'.$v.'/', $select, $m)) {
600 600
 
601 601
 			$res[] = $m[1];
602 602
 		} else {
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 			$n++;
758 758
 			$res .= "\nwhen $index=$v then $n";
759 759
 		}
760
-		$arg = $m[1] . "case $res else 0 end "
760
+		$arg = $m[1]."case $res else 0 end "
761 761
 			. substr($arg, strlen($m[0]));
762 762
 	}
763 763
 
@@ -802,9 +802,9 @@  discard block
 block discarded – undo
802 802
 	}
803 803
 
804 804
 	if (strtoupper($join) === 'AND') {
805
-		return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v));
805
+		return $exp.join("\n\t$join ", array_map('calculer_pg_where', $v));
806 806
 	} else {
807
-		return $exp . join($join, $v);
807
+		return $exp.join($join, $v);
808 808
 	}
809 809
 }
810 810
 
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
 		if (substr($k, -1) == '@') {
816 816
 			// c'est une jointure qui se refere au from precedent
817 817
 			// pas de virgule
818
-			$argsas .= '  ' . $v;
818
+			$argsas .= '  '.$v;
819 819
 		} else {
820 820
 			$as = '';
821 821
 			//  spip_log("$k : $v", _LOG_DEBUG);
@@ -825,7 +825,7 @@  discard block
 block discarded – undo
825 825
 				} elseif ($v != $k) {
826 826
 					$p = strpos($v, " ");
827 827
 					if ($p) {
828
-						$v = substr($v, 0, $p) . " AS $k" . substr($v, $p);
828
+						$v = substr($v, 0, $p)." AS $k".substr($v, $p);
829 829
 					} else {
830 830
 						$as = " AS $k";
831 831
 					}
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 			}
834 834
 			// spip_log("subs $k : $v avec $as", _LOG_DEBUG);
835 835
 			// if (strpos($v, 'JOIN') === false)  $argsas .= ', ';
836
-			$argsas .= ', ' . $v . $as;
836
+			$argsas .= ', '.$v.$as;
837 837
 		}
838 838
 	}
839 839
 
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 	$serveur = '',
867 867
 	$requeter = true
868 868
 ) {
869
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
869
+	$c = !$groupby ? '*' : ('DISTINCT '.(is_string($groupby) ? $groupby : join(',', $groupby)));
870 870
 	$r = spip_pg_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
871 871
 	if (!$requeter) {
872 872
 		return $r;
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
 	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
971 971
 	$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
972 972
 
973
-	return spip_pg_insert($table, "(" . join(',', array_keys($couples)) . ")", "(" . join(',', $couples) . ")", $desc,
973
+	return spip_pg_insert($table, "(".join(',', array_keys($couples)).")", "(".join(',', $couples).")", $desc,
974 974
 		$serveur, $requeter);
975 975
 }
976 976
 
@@ -991,7 +991,7 @@  discard block
 block discarded – undo
991 991
 	$c = isset($tab_couples[0]) ? $tab_couples[0] : array();
992 992
 	$les_cles = spip_pg_ajouter_champs_timestamp($table, $c, $desc, $serveur);
993 993
 
994
-	$cles = "(" . join(',', array_keys($les_cles)) . ')';
994
+	$cles = "(".join(',', array_keys($les_cles)).')';
995 995
 	$valeurs = array();
996 996
 	foreach ($tab_couples as $couples) {
997 997
 		foreach ($couples as $champ => $val) {
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
 		// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1001 1001
 		$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1002 1002
 
1003
-		$valeurs[] = '(' . join(',', $couples) . ')';
1003
+		$valeurs[] = '('.join(',', $couples).')';
1004 1004
 	}
1005 1005
 	$valeurs = implode(', ', $valeurs);
1006 1006
 
@@ -1022,7 +1022,7 @@  discard block
 block discarded – undo
1022 1022
 
1023 1023
 	$set = array();
1024 1024
 	foreach ($couples as $champ => $val) {
1025
-		$set[] = $champ . '=' . $val;
1025
+		$set[] = $champ.'='.$val;
1026 1026
 	}
1027 1027
 
1028 1028
 	$query = calculer_pg_expression('UPDATE', $table, ',')
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
 // http://code.spip.net/@spip_pg_replace
1060 1060
 function spip_pg_replace($table, $values, $desc, $serveur = '', $requeter = true) {
1061 1061
 	if (!$values) {
1062
-		spip_log("replace vide $table", 'pg.' . _LOG_AVERTISSEMENT);
1062
+		spip_log("replace vide $table", 'pg.'._LOG_AVERTISSEMENT);
1063 1063
 
1064 1064
 		return 0;
1065 1065
 	}
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
 
1092 1092
 	$where = join(' AND ', $prims);
1093 1093
 	if (!$where) {
1094
-		return spip_pg_insert($table, "(" . join(',', array_keys($values)) . ")", "(" . join(',', $values) . ")", $desc,
1094
+		return spip_pg_insert($table, "(".join(',', array_keys($values)).")", "(".join(',', $values).")", $desc,
1095 1095
 			$serveur);
1096 1096
 	}
1097 1097
 	$couples = join(',', $noprims);
@@ -1110,10 +1110,9 @@  discard block
 block discarded – undo
1110 1110
 		$couples = pg_affected_rows($couples);
1111 1111
 	}
1112 1112
 	if (!$couples) {
1113
-		$ret = !$seq ? '' :
1114
-			(" RETURNING nextval('$seq') < $prim");
1115
-		$connexion['last'] = $q = "INSERT INTO $table (" . join(',', array_keys($values)) . ') VALUES (' . join(',',
1116
-				$values) . ")$ret";
1113
+		$ret = !$seq ? '' : (" RETURNING nextval('$seq') < $prim");
1114
+		$connexion['last'] = $q = "INSERT INTO $table (".join(',', array_keys($values)).') VALUES ('.join(',',
1115
+				$values).")$ret";
1117 1116
 		$couples = spip_pg_query_simple($link, $q);
1118 1117
 		if (!$couples) {
1119 1118
 			return false;
@@ -1161,7 +1160,7 @@  discard block
 block discarded – undo
1161 1160
 	) {
1162 1161
 		return '';
1163 1162
 	} else {
1164
-		return $raw ? $prim : $table . '_' . $prim . "_seq";
1163
+		return $raw ? $prim : $table.'_'.$prim."_seq";
1165 1164
 	}
1166 1165
 }
1167 1166
 
@@ -1179,22 +1178,22 @@  discard block
 block discarded – undo
1179 1178
 			return spip_pg_frommysql($v);
1180 1179
 		} else {
1181 1180
 			if (strncmp($v, '0000', 4) == 0) {
1182
-				$v = "0001" . substr($v, 4);
1181
+				$v = "0001".substr($v, 4);
1183 1182
 			}
1184 1183
 			if (strpos($v, "-00-00") === 4) {
1185
-				$v = substr($v, 0, 4) . "-01-01" . substr($v, 10);
1184
+				$v = substr($v, 0, 4)."-01-01".substr($v, 10);
1186 1185
 			}
1187 1186
 
1188 1187
 			return "timestamp '$v'";
1189 1188
 		}
1190 1189
 	} elseif (!sql_test_int($t)) {
1191
-		return ("'" . pg_escape_string($v) . "'");
1190
+		return ("'".pg_escape_string($v)."'");
1192 1191
 	} elseif (is_numeric($v) or (strpos($v, 'CAST(') === 0)) {
1193 1192
 		return $v;
1194 1193
 	} elseif ($v[0] == '0' and $v[1] !== 'x' and ctype_xdigit(substr($v, 1))) {
1195 1194
 		return substr($v, 1);
1196 1195
 	} else {
1197
-		spip_log("Warning: '$v'  n'est pas de type $t", 'pg.' . _LOG_AVERTISSEMENT);
1196
+		spip_log("Warning: '$v'  n'est pas de type $t", 'pg.'._LOG_AVERTISSEMENT);
1198 1197
 
1199 1198
 		return intval($v);
1200 1199
 	}
@@ -1202,7 +1201,7 @@  discard block
 block discarded – undo
1202 1201
 
1203 1202
 // http://code.spip.net/@spip_pg_hex
1204 1203
 function spip_pg_hex($v) {
1205
-	return "CAST(x'" . $v . "' as bigint)";
1204
+	return "CAST(x'".$v."' as bigint)";
1206 1205
 }
1207 1206
 
1208 1207
 function spip_pg_quote($v, $type = '') {
@@ -1241,15 +1240,15 @@  discard block
 block discarded – undo
1241 1240
 		return $not ? '0=0' : '0=1';
1242 1241
 	}
1243 1242
 	if (strpos($valeurs, "CAST(x'") !== false) {
1244
-		return "($val=" . join("OR $val=", explode(',', $valeurs)) . ')';
1243
+		return "($val=".join("OR $val=", explode(',', $valeurs)).')';
1245 1244
 	}
1246 1245
 	$n = $i = 0;
1247 1246
 	$in_sql = "";
1248 1247
 	while ($n = strpos($valeurs, ',', $n + 1)) {
1249 1248
 		if ((++$i) >= 255) {
1250
-			$in_sql .= "($val $not IN (" .
1251
-				substr($valeurs, 0, $n) .
1252
-				"))\n" .
1249
+			$in_sql .= "($val $not IN (".
1250
+				substr($valeurs, 0, $n).
1251
+				"))\n".
1253 1252
 				($not ? "AND\t" : "OR\t");
1254 1253
 			$valeurs = substr($valeurs, $n + 1);
1255 1254
 			$i = $n = 0;
@@ -1266,7 +1265,7 @@  discard block
 block discarded – undo
1266 1265
 	$s = $link ? pg_last_error($link) : pg_last_error();
1267 1266
 	if ($s) {
1268 1267
 		$s = str_replace('ERROR', 'errcode: 1000 ', $s);
1269
-		spip_log("$s - $query", 'pg.' . _LOG_ERREUR);
1268
+		spip_log("$s - $query", 'pg.'._LOG_ERREUR);
1270 1269
 	}
1271 1270
 
1272 1271
 	return $s;
@@ -1317,7 +1316,7 @@  discard block
 block discarded – undo
1317 1316
 function spip_pg_showbase($match, $serveur = '', $requeter = true) {
1318 1317
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1319 1318
 	$link = $connexion['link'];
1320
-	$connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE " . _q($match);
1319
+	$connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE "._q($match);
1321 1320
 
1322 1321
 	return spip_pg_query_simple($link, $q);
1323 1322
 }
@@ -1326,7 +1325,7 @@  discard block
 block discarded – undo
1326 1325
 function spip_pg_showtable($nom_table, $serveur = '', $requeter = true) {
1327 1326
 	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1328 1327
 	$link = $connexion['link'];
1329
-	$connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table);
1328
+	$connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE "._q($nom_table);
1330 1329
 
1331 1330
 	$res = spip_pg_query_simple($link, $q);
1332 1331
 	if (!$res) {
@@ -1337,15 +1336,15 @@  discard block
 block discarded – undo
1337 1336
 	// il faut en tenir compte dans le return
1338 1337
 	$fields = array();
1339 1338
 	while ($field = pg_fetch_array($res, null, PGSQL_NUM)) {
1340
-		$fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1]));
1339
+		$fields[$field[0]] = $field[2].(!$field[1] ? '' : (" DEFAULT ".$field[1]));
1341 1340
 	}
1342
-	$connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table);
1341
+	$connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE "._q($nom_table);
1343 1342
 	$res = spip_pg_query_simple($link, $q);
1344 1343
 	$keys = array();
1345 1344
 	while ($index = pg_fetch_array($res, null, PGSQL_NUM)) {
1346 1345
 		if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0], $r)) {
1347
-			$nom = str_replace($nom_table . '_', '', $r[2]);
1348
-			$keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3];
1346
+			$nom = str_replace($nom_table.'_', '', $r[2]);
1347
+			$keys[($r[1] ? "PRIMARY KEY" : ("KEY ".$nom))] = $r[3];
1349 1348
 		}
1350 1349
 	}
1351 1350
 
@@ -1378,16 +1377,16 @@  discard block
 block discarded – undo
1378 1377
 		if (strpos($k, "KEY ") === 0) {
1379 1378
 			$n = str_replace('`', '', $k);
1380 1379
 			$v = str_replace('`', '"', $v);
1381
-			$i = $nom . preg_replace("/KEY +/", '_', $n);
1380
+			$i = $nom.preg_replace("/KEY +/", '_', $n);
1382 1381
 			if ($k != $n) {
1383 1382
 				$i = "\"$i\"";
1384 1383
 			}
1385 1384
 			$keys[] = "CREATE INDEX $i ON $nom ($v);";
1386 1385
 		} elseif (strpos($k, "UNIQUE ") === 0) {
1387 1386
 			$k = preg_replace("/^UNIQUE +/", '', $k);
1388
-			$prim .= "$s\n\t\tCONSTRAINT " . str_replace('`', '"', $k) . " UNIQUE ($v)";
1387
+			$prim .= "$s\n\t\tCONSTRAINT ".str_replace('`', '"', $k)." UNIQUE ($v)";
1389 1388
 		} else {
1390
-			$prim .= "$s\n\t\t" . str_replace('`', '"', $k) . " ($v)";
1389
+			$prim .= "$s\n\t\t".str_replace('`', '"', $k)." ($v)";
1391 1390
 		}
1392 1391
 		if ($k == "PRIMARY KEY") {
1393 1392
 			$prim_name = $v;
@@ -1398,17 +1397,17 @@  discard block
 block discarded – undo
1398 1397
 
1399 1398
 	$character_set = "";
1400 1399
 	if (@$GLOBALS['meta']['charset_sql_base']) {
1401
-		$character_set .= " CHARACTER SET " . $GLOBALS['meta']['charset_sql_base'];
1400
+		$character_set .= " CHARACTER SET ".$GLOBALS['meta']['charset_sql_base'];
1402 1401
 	}
1403 1402
 	if (@$GLOBALS['meta']['charset_collation_sql_base']) {
1404
-		$character_set .= " COLLATE " . $GLOBALS['meta']['charset_collation_sql_base'];
1403
+		$character_set .= " COLLATE ".$GLOBALS['meta']['charset_collation_sql_base'];
1405 1404
 	}
1406 1405
 
1407 1406
 	foreach ($champs as $k => $v) {
1408 1407
 		$k = str_replace('`', '"', $k);
1409 1408
 		if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
1410 1409
 			if (preg_match(',(char|text),i', $defs[1]) and !preg_match(',binary,i', $defs[1])) {
1411
-				$v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
1410
+				$v = $defs[1].$character_set.' '.substr($v, strlen($defs[1]));
1412 1411
 			}
1413 1412
 		}
1414 1413
 
@@ -1423,7 +1422,7 @@  discard block
 block discarded – undo
1423 1422
 
1424 1423
 	// En l'absence de "if not exists" en PG, on neutralise les erreurs
1425 1424
 
1426
-	$q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")" .
1425
+	$q = "CREATE $temporary TABLE $nom ($query".($prim ? ",$prim" : '').")".
1427 1426
 		($character_set ? " DEFAULT $character_set" : "")
1428 1427
 		. "\n";
1429 1428
 
@@ -1434,7 +1433,7 @@  discard block
 block discarded – undo
1434 1433
 	$r = @pg_query($link, $q);
1435 1434
 
1436 1435
 	if (!$r) {
1437
-		spip_log("Impossible de creer cette table: $q", 'pg.' . _LOG_ERREUR);
1436
+		spip_log("Impossible de creer cette table: $q", 'pg.'._LOG_ERREUR);
1438 1437
 	} else {
1439 1438
 		foreach ($keys as $index) {
1440 1439
 			pg_query($link, $index);
@@ -1458,13 +1457,13 @@  discard block
 block discarded – undo
1458 1457
 	// vue deja presente
1459 1458
 	if (sql_showtable($nom, false, $serveur)) {
1460 1459
 		if ($requeter) {
1461
-			spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.' . _LOG_ERREUR);
1460
+			spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.'._LOG_ERREUR);
1462 1461
 		}
1463 1462
 
1464 1463
 		return false;
1465 1464
 	}
1466 1465
 
1467
-	$query = "CREATE VIEW $nom AS " . $query_select;
1466
+	$query = "CREATE VIEW $nom AS ".$query_select;
1468 1467
 
1469 1468
 	return spip_pg_query($query, $serveur, $requeter);
1470 1469
 }
@@ -1472,7 +1471,7 @@  discard block
 block discarded – undo
1472 1471
 
1473 1472
 // http://code.spip.net/@spip_pg_set_connect_charset
1474 1473
 function spip_pg_set_connect_charset($charset, $serveur = '', $requeter = true) {
1475
-	spip_log("changement de charset sql a ecrire en PG", 'pg.' . _LOG_ERREUR);
1474
+	spip_log("changement de charset sql a ecrire en PG", 'pg.'._LOG_ERREUR);
1476 1475
 }
1477 1476
 
1478 1477
 
@@ -1486,7 +1485,7 @@  discard block
 block discarded – undo
1486 1485
  **/
1487 1486
 // http://code.spip.net/@spip_sqlite_optimize
1488 1487
 function spip_pg_optimize($table, $serveur = '', $requeter = true) {
1489
-	return spip_pg_query("VACUUM " . $table, $serveur, $requeter);
1488
+	return spip_pg_query("VACUUM ".$table, $serveur, $requeter);
1490 1489
 }
1491 1490
 
1492 1491
 // Selectionner la sous-chaine dans $objet
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -616,10 +616,12 @@
 block discarded – undo
616 616
 function spip_pg_groupby($groupby, $from, $select) {
617 617
 	$join = strpos($from, ",");
618 618
 	// ismplifier avant de decouper
619
-	if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne
619
+	if (is_string($select)) {
620
+	    // fct SQL sur colonne et constante apostrophee ==> la colonne
620 621
 	{
621 622
 		$select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $select);
622 623
 	}
624
+	}
623 625
 
624 626
 	if ($join or $groupby) {
625 627
 		$join = is_array($select) ? $select : explode(", ", $select);
Please login to merge, or discard this patch.
Indentation   +1112 added lines, -1112 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  */
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 define('_DEFAULT_DB', 'spip');
@@ -32,128 +32,128 @@  discard block
 block discarded – undo
32 32
 
33 33
 // http://code.spip.net/@req_pg_dist
34 34
 function req_pg_dist($addr, $port, $login, $pass, $db = '', $prefixe = '') {
35
-	static $last_connect = array();
36
-	if (!extension_loaded('pgsql')) {
37
-		return false;
38
-	}
39
-
40
-	// si provient de selectdb
41
-	if (empty($addr) && empty($port) && empty($login) && empty($pass)) {
42
-		foreach (array('addr', 'port', 'login', 'pass', 'prefixe') as $a) {
43
-			$$a = $last_connect[$a];
44
-		}
45
-	}
46
-	@list($host, $p) = explode(';', $addr);
47
-	if ($p > 0) {
48
-		$port = " port=$p";
49
-	} else {
50
-		$port = '';
51
-	}
52
-	$erreurs = array();
53
-	if ($db) {
54
-		@$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
55
-	} elseif (!@$link = pg_connect("host=$host$port user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
56
-		$erreurs[] = pg_last_error();
57
-		if (@$link = pg_connect("host=$host$port dbname=$login user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
58
-			$db = $login;
59
-		} else {
60
-			$erreurs[] = pg_last_error();
61
-			$db = _DEFAULT_DB;
62
-			$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
63
-		}
64
-	}
65
-	if (!$link) {
66
-		$erreurs[] = pg_last_error();
67
-		foreach ($erreurs as $e) {
68
-			spip_log('Echec pg_connect. Erreur : ' . $e, 'pg.' . _LOG_HS);
69
-		}
70
-
71
-		return false;
72
-	}
73
-
74
-	if ($link) {
75
-		$last_connect = array(
76
-			'addr' => $addr,
77
-			'port' => $port,
78
-			'login' => $login,
79
-			'pass' => $pass,
80
-			'db' => $db,
81
-			'prefixe' => $prefixe,
82
-		);
83
-	}
84
-
85
-	spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),
86
-		'pg.' . _LOG_DEBUG);
87
-
88
-	return !$link ? false : array(
89
-		'db' => $db,
90
-		'prefixe' => $prefixe ? $prefixe : $db,
91
-		'link' => $link,
92
-	);
35
+    static $last_connect = array();
36
+    if (!extension_loaded('pgsql')) {
37
+        return false;
38
+    }
39
+
40
+    // si provient de selectdb
41
+    if (empty($addr) && empty($port) && empty($login) && empty($pass)) {
42
+        foreach (array('addr', 'port', 'login', 'pass', 'prefixe') as $a) {
43
+            $$a = $last_connect[$a];
44
+        }
45
+    }
46
+    @list($host, $p) = explode(';', $addr);
47
+    if ($p > 0) {
48
+        $port = " port=$p";
49
+    } else {
50
+        $port = '';
51
+    }
52
+    $erreurs = array();
53
+    if ($db) {
54
+        @$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
55
+    } elseif (!@$link = pg_connect("host=$host$port user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
56
+        $erreurs[] = pg_last_error();
57
+        if (@$link = pg_connect("host=$host$port dbname=$login user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
58
+            $db = $login;
59
+        } else {
60
+            $erreurs[] = pg_last_error();
61
+            $db = _DEFAULT_DB;
62
+            $link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
63
+        }
64
+    }
65
+    if (!$link) {
66
+        $erreurs[] = pg_last_error();
67
+        foreach ($erreurs as $e) {
68
+            spip_log('Echec pg_connect. Erreur : ' . $e, 'pg.' . _LOG_HS);
69
+        }
70
+
71
+        return false;
72
+    }
73
+
74
+    if ($link) {
75
+        $last_connect = array(
76
+            'addr' => $addr,
77
+            'port' => $port,
78
+            'login' => $login,
79
+            'pass' => $pass,
80
+            'db' => $db,
81
+            'prefixe' => $prefixe,
82
+        );
83
+    }
84
+
85
+    spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),
86
+        'pg.' . _LOG_DEBUG);
87
+
88
+    return !$link ? false : array(
89
+        'db' => $db,
90
+        'prefixe' => $prefixe ? $prefixe : $db,
91
+        'link' => $link,
92
+    );
93 93
 }
94 94
 
95 95
 $GLOBALS['spip_pg_functions_1'] = array(
96
-	'alter' => 'spip_pg_alter',
97
-	'count' => 'spip_pg_count',
98
-	'countsel' => 'spip_pg_countsel',
99
-	'create' => 'spip_pg_create',
100
-	'create_base' => 'spip_pg_create_base',
101
-	'create_view' => 'spip_pg_create_view',
102
-	'date_proche' => 'spip_pg_date_proche',
103
-	'delete' => 'spip_pg_delete',
104
-	'drop_table' => 'spip_pg_drop_table',
105
-	'drop_view' => 'spip_pg_drop_view',
106
-	'errno' => 'spip_pg_errno',
107
-	'error' => 'spip_pg_error',
108
-	'explain' => 'spip_pg_explain',
109
-	'fetch' => 'spip_pg_fetch',
110
-	'seek' => 'spip_pg_seek',
111
-	'free' => 'spip_pg_free',
112
-	'hex' => 'spip_pg_hex',
113
-	'in' => 'spip_pg_in',
114
-	'insert' => 'spip_pg_insert',
115
-	'insertq' => 'spip_pg_insertq',
116
-	'insertq_multi' => 'spip_pg_insertq_multi',
117
-	'listdbs' => 'spip_pg_listdbs',
118
-	'multi' => 'spip_pg_multi',
119
-	'optimize' => 'spip_pg_optimize',
120
-	'query' => 'spip_pg_query',
121
-	'quote' => 'spip_pg_quote',
122
-	'replace' => 'spip_pg_replace',
123
-	'replace_multi' => 'spip_pg_replace_multi',
124
-	'select' => 'spip_pg_select',
125
-	'selectdb' => 'spip_pg_selectdb',
126
-	'set_connect_charset' => 'spip_pg_set_connect_charset',
127
-	'showbase' => 'spip_pg_showbase',
128
-	'showtable' => 'spip_pg_showtable',
129
-	'update' => 'spip_pg_update',
130
-	'updateq' => 'spip_pg_updateq',
96
+    'alter' => 'spip_pg_alter',
97
+    'count' => 'spip_pg_count',
98
+    'countsel' => 'spip_pg_countsel',
99
+    'create' => 'spip_pg_create',
100
+    'create_base' => 'spip_pg_create_base',
101
+    'create_view' => 'spip_pg_create_view',
102
+    'date_proche' => 'spip_pg_date_proche',
103
+    'delete' => 'spip_pg_delete',
104
+    'drop_table' => 'spip_pg_drop_table',
105
+    'drop_view' => 'spip_pg_drop_view',
106
+    'errno' => 'spip_pg_errno',
107
+    'error' => 'spip_pg_error',
108
+    'explain' => 'spip_pg_explain',
109
+    'fetch' => 'spip_pg_fetch',
110
+    'seek' => 'spip_pg_seek',
111
+    'free' => 'spip_pg_free',
112
+    'hex' => 'spip_pg_hex',
113
+    'in' => 'spip_pg_in',
114
+    'insert' => 'spip_pg_insert',
115
+    'insertq' => 'spip_pg_insertq',
116
+    'insertq_multi' => 'spip_pg_insertq_multi',
117
+    'listdbs' => 'spip_pg_listdbs',
118
+    'multi' => 'spip_pg_multi',
119
+    'optimize' => 'spip_pg_optimize',
120
+    'query' => 'spip_pg_query',
121
+    'quote' => 'spip_pg_quote',
122
+    'replace' => 'spip_pg_replace',
123
+    'replace_multi' => 'spip_pg_replace_multi',
124
+    'select' => 'spip_pg_select',
125
+    'selectdb' => 'spip_pg_selectdb',
126
+    'set_connect_charset' => 'spip_pg_set_connect_charset',
127
+    'showbase' => 'spip_pg_showbase',
128
+    'showtable' => 'spip_pg_showtable',
129
+    'update' => 'spip_pg_update',
130
+    'updateq' => 'spip_pg_updateq',
131 131
 );
132 132
 
133 133
 // Par ou ca passe une fois les traductions faites
134 134
 // http://code.spip.net/@spip_pg_trace_query
135 135
 function spip_pg_trace_query($query, $serveur = '') {
136
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
137
-	$prefixe = $connexion['prefixe'];
138
-	$link = $connexion['link'];
139
-	$db = $connexion['db'];
140
-
141
-	if (isset($_GET['var_profile'])) {
142
-		include_spip('public/tracer');
143
-		$t = trace_query_start();
144
-		$e = '';
145
-	} else {
146
-		$t = 0;
147
-	}
148
-
149
-	$connexion['last'] = $query;
150
-	$r = spip_pg_query_simple($link, $query);
151
-
152
-	// Log de l'erreur eventuelle
153
-	if ($e = spip_pg_errno($serveur)) {
154
-		$e .= spip_pg_error($query, $serveur);
155
-	} // et du fautif
156
-	return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
136
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
137
+    $prefixe = $connexion['prefixe'];
138
+    $link = $connexion['link'];
139
+    $db = $connexion['db'];
140
+
141
+    if (isset($_GET['var_profile'])) {
142
+        include_spip('public/tracer');
143
+        $t = trace_query_start();
144
+        $e = '';
145
+    } else {
146
+        $t = 0;
147
+    }
148
+
149
+    $connexion['last'] = $query;
150
+    $r = spip_pg_query_simple($link, $query);
151
+
152
+    // Log de l'erreur eventuelle
153
+    if ($e = spip_pg_errno($serveur)) {
154
+        $e .= spip_pg_error($query, $serveur);
155
+    } // et du fautif
156
+    return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
157 157
 }
158 158
 
159 159
 // Fonction de requete generale quand on est sur que c'est SQL standard.
@@ -161,30 +161,30 @@  discard block
 block discarded – undo
161 161
 
162 162
 // http://code.spip.net/@spip_pg_query
163 163
 function spip_pg_query($query, $serveur = '', $requeter = true) {
164
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
165
-	$prefixe = $connexion['prefixe'];
166
-	$link = $connexion['link'];
167
-	$db = $connexion['db'];
168
-
169
-	if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
170
-		$suite = strstr($query, $regs[0]);
171
-		$query = substr($query, 0, -strlen($suite));
172
-	} else {
173
-		$suite = '';
174
-	}
175
-	$query = preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
176
-
177
-	// renvoyer la requete inerte si demandee
178
-	if (!$requeter) {
179
-		return $query;
180
-	}
181
-
182
-	return spip_pg_trace_query($query, $serveur);
164
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
165
+    $prefixe = $connexion['prefixe'];
166
+    $link = $connexion['link'];
167
+    $db = $connexion['db'];
168
+
169
+    if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
170
+        $suite = strstr($query, $regs[0]);
171
+        $query = substr($query, 0, -strlen($suite));
172
+    } else {
173
+        $suite = '';
174
+    }
175
+    $query = preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
176
+
177
+    // renvoyer la requete inerte si demandee
178
+    if (!$requeter) {
179
+        return $query;
180
+    }
181
+
182
+    return spip_pg_trace_query($query, $serveur);
183 183
 }
184 184
 
185 185
 function spip_pg_query_simple($link, $query) {
186
-	#spip_log(var_export($query,true), 'pg.'._LOG_DEBUG);
187
-	return pg_query($link, $query);
186
+    #spip_log(var_export($query,true), 'pg.'._LOG_DEBUG);
187
+    return pg_query($link, $query);
188 188
 }
189 189
 
190 190
 /*
@@ -196,198 +196,198 @@  discard block
 block discarded – undo
196 196
  * de requetes showtable intempestives
197 197
  */
198 198
 function spip_pg_ajouter_champs_timestamp($table, $couples, $desc = '', $serveur = '') {
199
-	static $tables = array();
200
-
201
-	if (!isset($tables[$table])) {
202
-
203
-		if (!$desc) {
204
-			$trouver_table = charger_fonction('trouver_table', 'base');
205
-			$desc = $trouver_table($table, $serveur);
206
-			// si pas de description, on ne fait rien, ou on die() ?
207
-			if (!$desc) {
208
-				return $couples;
209
-			}
210
-		}
211
-
212
-		// recherche des champs avec simplement 'TIMESTAMP'
213
-		// cependant, il faudra peut etre etendre
214
-		// avec la gestion de DEFAULT et ON UPDATE
215
-		// mais ceux-ci ne sont pas utilises dans le core
216
-		$tables[$table] = array();
217
-		foreach ($desc['field'] as $k => $v) {
218
-			$v = strtolower(ltrim($v));
219
-			// ne pas ajouter de timestamp now() si un default est specifie
220
-			if (strpos($v, 'timestamp') === 0 and strpos($v, 'default') === false) {
221
-				$tables[$table][] = $k;
222
-			}
223
-		}
224
-	}
225
-
226
-	// ajout des champs type 'timestamp' absents
227
-	foreach ($tables[$table] as $maj) {
228
-		if (!array_key_exists($maj, $couples)) {
229
-			$couples[$maj] = "NOW()";
230
-		}
231
-	}
232
-
233
-	return $couples;
199
+    static $tables = array();
200
+
201
+    if (!isset($tables[$table])) {
202
+
203
+        if (!$desc) {
204
+            $trouver_table = charger_fonction('trouver_table', 'base');
205
+            $desc = $trouver_table($table, $serveur);
206
+            // si pas de description, on ne fait rien, ou on die() ?
207
+            if (!$desc) {
208
+                return $couples;
209
+            }
210
+        }
211
+
212
+        // recherche des champs avec simplement 'TIMESTAMP'
213
+        // cependant, il faudra peut etre etendre
214
+        // avec la gestion de DEFAULT et ON UPDATE
215
+        // mais ceux-ci ne sont pas utilises dans le core
216
+        $tables[$table] = array();
217
+        foreach ($desc['field'] as $k => $v) {
218
+            $v = strtolower(ltrim($v));
219
+            // ne pas ajouter de timestamp now() si un default est specifie
220
+            if (strpos($v, 'timestamp') === 0 and strpos($v, 'default') === false) {
221
+                $tables[$table][] = $k;
222
+            }
223
+        }
224
+    }
225
+
226
+    // ajout des champs type 'timestamp' absents
227
+    foreach ($tables[$table] as $maj) {
228
+        if (!array_key_exists($maj, $couples)) {
229
+            $couples[$maj] = "NOW()";
230
+        }
231
+    }
232
+
233
+    return $couples;
234 234
 }
235 235
 
236 236
 
237 237
 // Alter en PG ne traite pas les index
238 238
 // http://code.spip.net/@spip_pg_alter
239 239
 function spip_pg_alter($query, $serveur = '', $requeter = true) {
240
-	// il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
241
-	// tout en cassant en deux alter distincts "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... 
242
-	// ou revoir l'api de sql_alter en creant un 
243
-	// sql_alter_table($table,array($actions));
244
-	if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)) {
245
-		spip_log("$query mal comprise", 'pg.' . _LOG_ERREUR);
246
-
247
-		return false;
248
-	}
249
-	$debut = $regs[1];
250
-	$table = $regs[3];
251
-	$suite = $regs[4];
252
-	$todo = explode(',', $suite);
253
-	// on remet les morceaux dechires ensembles... que c'est laid !
254
-	$todo2 = array();
255
-	$i = 0;
256
-	$ouverte = false;
257
-	while ($do = array_shift($todo)) {
258
-		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do;
259
-		$o = (false !== strpos($do, "("));
260
-		$f = (false !== strpos($do, ")"));
261
-		if ($o and !$f) {
262
-			$ouverte = true;
263
-		} elseif ($f) {
264
-			$ouverte = false;
265
-		}
266
-		if (!$ouverte) {
267
-			$i++;
268
-		}
269
-	}
270
-	$todo = $todo2;
271
-	$query = $debut . ' ' . array_shift($todo);
272
-
273
-	if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) {
274
-		spip_log("$query incompris", 'pg.' . _LOG_ERREUR);
275
-	} else {
276
-		if ($r[1]) {
277
-			spip_log("j'ignore IGNORE dans $query", 'pg.' . _LOG_AVERTISSEMENT);
278
-		}
279
-		$f = 'spip_pg_alter_' . strtolower($r[3]);
280
-		if (function_exists($f)) {
281
-			$f($r[2], $r[4], $serveur, $requeter);
282
-		} else {
283
-			spip_log("$query non prevu", 'pg.' . _LOG_ERREUR);
284
-		}
285
-	}
286
-	// Alter a plusieurs args. Faudrait optimiser.
287
-	if ($todo) {
288
-		spip_pg_alter("TABLE $table " . join(',', $todo));
289
-	}
240
+    // il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
241
+    // tout en cassant en deux alter distincts "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... 
242
+    // ou revoir l'api de sql_alter en creant un 
243
+    // sql_alter_table($table,array($actions));
244
+    if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)) {
245
+        spip_log("$query mal comprise", 'pg.' . _LOG_ERREUR);
246
+
247
+        return false;
248
+    }
249
+    $debut = $regs[1];
250
+    $table = $regs[3];
251
+    $suite = $regs[4];
252
+    $todo = explode(',', $suite);
253
+    // on remet les morceaux dechires ensembles... que c'est laid !
254
+    $todo2 = array();
255
+    $i = 0;
256
+    $ouverte = false;
257
+    while ($do = array_shift($todo)) {
258
+        $todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do;
259
+        $o = (false !== strpos($do, "("));
260
+        $f = (false !== strpos($do, ")"));
261
+        if ($o and !$f) {
262
+            $ouverte = true;
263
+        } elseif ($f) {
264
+            $ouverte = false;
265
+        }
266
+        if (!$ouverte) {
267
+            $i++;
268
+        }
269
+    }
270
+    $todo = $todo2;
271
+    $query = $debut . ' ' . array_shift($todo);
272
+
273
+    if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) {
274
+        spip_log("$query incompris", 'pg.' . _LOG_ERREUR);
275
+    } else {
276
+        if ($r[1]) {
277
+            spip_log("j'ignore IGNORE dans $query", 'pg.' . _LOG_AVERTISSEMENT);
278
+        }
279
+        $f = 'spip_pg_alter_' . strtolower($r[3]);
280
+        if (function_exists($f)) {
281
+            $f($r[2], $r[4], $serveur, $requeter);
282
+        } else {
283
+            spip_log("$query non prevu", 'pg.' . _LOG_ERREUR);
284
+        }
285
+    }
286
+    // Alter a plusieurs args. Faudrait optimiser.
287
+    if ($todo) {
288
+        spip_pg_alter("TABLE $table " . join(',', $todo));
289
+    }
290 290
 
291 291
 }
292 292
 
293 293
 // http://code.spip.net/@spip_pg_alter_change
294 294
 function spip_pg_alter_change($table, $arg, $serveur = '', $requeter = true) {
295
-	if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
296
-		spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
297
-	} else {
298
-		list(, $old, $new, $type, $default, $null, $def2) = $r;
299
-		$actions = array("ALTER $old TYPE " . mysql2pg_type($type));
300
-		if ($null) {
301
-			$actions[] = "ALTER $old SET NOT NULL";
302
-		} else {
303
-			$actions[] = "ALTER $old DROP NOT NULL";
304
-		}
305
-
306
-		if ($d = ($default ? $default : $def2)) {
307
-			$actions[] = "ALTER $old SET $d";
308
-		} else {
309
-			$actions[] = "ALTER $old DROP DEFAULT";
310
-		}
311
-
312
-		spip_pg_query("ALTER TABLE $table " . join(', ', $actions));
313
-
314
-		if ($old != $new) {
315
-			spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur);
316
-		}
317
-	}
295
+    if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
296
+        spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
297
+    } else {
298
+        list(, $old, $new, $type, $default, $null, $def2) = $r;
299
+        $actions = array("ALTER $old TYPE " . mysql2pg_type($type));
300
+        if ($null) {
301
+            $actions[] = "ALTER $old SET NOT NULL";
302
+        } else {
303
+            $actions[] = "ALTER $old DROP NOT NULL";
304
+        }
305
+
306
+        if ($d = ($default ? $default : $def2)) {
307
+            $actions[] = "ALTER $old SET $d";
308
+        } else {
309
+            $actions[] = "ALTER $old DROP DEFAULT";
310
+        }
311
+
312
+        spip_pg_query("ALTER TABLE $table " . join(', ', $actions));
313
+
314
+        if ($old != $new) {
315
+            spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur);
316
+        }
317
+    }
318 318
 }
319 319
 
320 320
 // http://code.spip.net/@spip_pg_alter_add
321 321
 function spip_pg_alter_add($table, $arg, $serveur = '', $requeter = true) {
322
-	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) {
323
-		spip_log("alter add $arg  incompris", 'pg.' . _LOG_ERREUR);
324
-
325
-		return null;
326
-	}
327
-	if (!$r[1] or $r[1] == 'COLUMN') {
328
-		preg_match('/`?(\w+)`?(.*)/', $r[2], $m);
329
-		if (preg_match('/^(.*)(BEFORE|AFTER|FIRST)(.*)$/is', $m[2], $n)) {
330
-			$m[2] = $n[1];
331
-		}
332
-
333
-		return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter);
334
-	} elseif ($r[1][0] == 'P') {
335
-		// la primary peut etre sur plusieurs champs
336
-		$r[2] = trim(str_replace('`', '', $r[2]));
337
-		$m = ($r[2][0] == '(') ? substr($r[2], 1, -1) : $r[2];
338
-
339
-		return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" . '_pkey PRIMARY KEY (' . $m . ')', $serveur,
340
-			$requeter);
341
-	} else {
342
-		preg_match('/([^\s,]*)\s*(.*)?/', $r[2], $m);
343
-		// peut etre "(colonne)" ou "nom_index (colonnes)"
344
-		// bug potentiel si qqn met "(colonne, colonne)"
345
-		//
346
-		// nom_index (colonnes)
347
-		if ($m[2]) {
348
-			$colonnes = substr($m[2], 1, -1);
349
-			$nom_index = $m[1];
350
-		} else {
351
-			// (colonne)
352
-			if ($m[1][0] == "(") {
353
-				$colonnes = substr($m[1], 1, -1);
354
-				if (false !== strpos(",", $colonnes)) {
355
-					spip_log(_LOG_GRAVITE_ERREUR, "PG : Erreur, impossible de creer un index sur plusieurs colonnes"
356
-						. " sans qu'il ait de nom ($table, ($colonnes))", 'pg');
357
-				} else {
358
-					$nom_index = $colonnes;
359
-				}
360
-			} // nom_index
361
-			else {
362
-				$nom_index = $colonnes = $m[1];
363
-			}
364
-		}
365
-
366
-		return spip_pg_create_index($nom_index, $table, $colonnes, $serveur, $requeter);
367
-	}
322
+    if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) {
323
+        spip_log("alter add $arg  incompris", 'pg.' . _LOG_ERREUR);
324
+
325
+        return null;
326
+    }
327
+    if (!$r[1] or $r[1] == 'COLUMN') {
328
+        preg_match('/`?(\w+)`?(.*)/', $r[2], $m);
329
+        if (preg_match('/^(.*)(BEFORE|AFTER|FIRST)(.*)$/is', $m[2], $n)) {
330
+            $m[2] = $n[1];
331
+        }
332
+
333
+        return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter);
334
+    } elseif ($r[1][0] == 'P') {
335
+        // la primary peut etre sur plusieurs champs
336
+        $r[2] = trim(str_replace('`', '', $r[2]));
337
+        $m = ($r[2][0] == '(') ? substr($r[2], 1, -1) : $r[2];
338
+
339
+        return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" . '_pkey PRIMARY KEY (' . $m . ')', $serveur,
340
+            $requeter);
341
+    } else {
342
+        preg_match('/([^\s,]*)\s*(.*)?/', $r[2], $m);
343
+        // peut etre "(colonne)" ou "nom_index (colonnes)"
344
+        // bug potentiel si qqn met "(colonne, colonne)"
345
+        //
346
+        // nom_index (colonnes)
347
+        if ($m[2]) {
348
+            $colonnes = substr($m[2], 1, -1);
349
+            $nom_index = $m[1];
350
+        } else {
351
+            // (colonne)
352
+            if ($m[1][0] == "(") {
353
+                $colonnes = substr($m[1], 1, -1);
354
+                if (false !== strpos(",", $colonnes)) {
355
+                    spip_log(_LOG_GRAVITE_ERREUR, "PG : Erreur, impossible de creer un index sur plusieurs colonnes"
356
+                        . " sans qu'il ait de nom ($table, ($colonnes))", 'pg');
357
+                } else {
358
+                    $nom_index = $colonnes;
359
+                }
360
+            } // nom_index
361
+            else {
362
+                $nom_index = $colonnes = $m[1];
363
+            }
364
+        }
365
+
366
+        return spip_pg_create_index($nom_index, $table, $colonnes, $serveur, $requeter);
367
+    }
368 368
 }
369 369
 
370 370
 // http://code.spip.net/@spip_pg_alter_drop
371 371
 function spip_pg_alter_drop($table, $arg, $serveur = '', $requeter = true) {
372
-	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) {
373
-		spip_log("alter drop: $arg  incompris", 'pg.' . _LOG_ERREUR);
374
-	} else {
375
-		if (!$r[1] or $r[1] == 'COLUMN') {
376
-			return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur);
377
-		} elseif ($r[1][0] == 'P') {
378
-			return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur);
379
-		} else {
380
-			return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur);
381
-		}
382
-	}
372
+    if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) {
373
+        spip_log("alter drop: $arg  incompris", 'pg.' . _LOG_ERREUR);
374
+    } else {
375
+        if (!$r[1] or $r[1] == 'COLUMN') {
376
+            return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur);
377
+        } elseif ($r[1][0] == 'P') {
378
+            return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur);
379
+        } else {
380
+            return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur);
381
+        }
382
+    }
383 383
 }
384 384
 
385 385
 function spip_pg_alter_modify($table, $arg, $serveur = '', $requeter = true) {
386
-	if (!preg_match('/^`?(\w+)`?\s+(.*)$/', $arg, $r)) {
387
-		spip_log("alter modify: $arg  incompris", 'pg.' . _LOG_ERREUR);
388
-	} else {
389
-		return spip_pg_alter_change($table, $r[1] . ' ' . $arg, $serveur = '', $requeter = true);
390
-	}
386
+    if (!preg_match('/^`?(\w+)`?\s+(.*)$/', $arg, $r)) {
387
+        spip_log("alter modify: $arg  incompris", 'pg.' . _LOG_ERREUR);
388
+    } else {
389
+        return spip_pg_alter_change($table, $r[1] . ' ' . $arg, $serveur = '', $requeter = true);
390
+    }
391 391
 }
392 392
 
393 393
 // attention (en pg) : 
@@ -395,17 +395,17 @@  discard block
 block discarded – undo
395 395
 // - alter table A rename X to Y = changer le nom de la colonne X en Y 
396 396
 // pour l'instant, traiter simplement RENAME TO X
397 397
 function spip_pg_alter_rename($table, $arg, $serveur = '', $requeter = true) {
398
-	$rename = "";
399
-	// si TO, mais pas au debut
400
-	if (!stripos($arg, 'TO ')) {
401
-		$rename = $arg;
402
-	} elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) {
403
-		$rename = $r[2];
404
-	} else {
405
-		spip_log("alter rename: $arg  incompris", 'pg.' . _LOG_ERREUR);
406
-	}
407
-
408
-	return $rename ? spip_pg_query("ALTER TABLE $table RENAME TO $rename") : false;
398
+    $rename = "";
399
+    // si TO, mais pas au debut
400
+    if (!stripos($arg, 'TO ')) {
401
+        $rename = $arg;
402
+    } elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) {
403
+        $rename = $r[2];
404
+    } else {
405
+        spip_log("alter rename: $arg  incompris", 'pg.' . _LOG_ERREUR);
406
+    }
407
+
408
+    return $rename ? spip_pg_query("ALTER TABLE $table RENAME TO $rename") : false;
409 409
 }
410 410
 
411 411
 
@@ -421,58 +421,58 @@  discard block
 block discarded – undo
421 421
  * @return bool ou requete
422 422
  */
423 423
 function spip_pg_create_index($nom, $table, $champs, $serveur = '', $requeter = true) {
424
-	if (!($nom or $table or $champs)) {
425
-		spip_log("Champ manquant pour creer un index pg ($nom, $table, (" . @join(',', $champs) . "))",
426
-			'pg.' . _LOG_ERREUR);
427
-
428
-		return false;
429
-	}
430
-
431
-	$nom = str_replace("`", "", $nom);
432
-	$champs = str_replace("`", "", $champs);
433
-
434
-	// PG ne differentie pas noms des index en fonction des tables
435
-	// il faut donc creer des noms uniques d'index pour une base pg
436
-	$nom = $table . '_' . $nom;
437
-	// enlever d'eventuelles parentheses deja presentes sur champs
438
-	if (!is_array($champs)) {
439
-		if ($champs[0] == "(") {
440
-			$champs = substr($champs, 1, -1);
441
-		}
442
-		$champs = array($champs);
443
-	}
444
-	$query = "CREATE INDEX $nom ON $table (" . join(',', $champs) . ")";
445
-	if (!$requeter) {
446
-		return $query;
447
-	}
448
-	$res = spip_pg_query($query, $serveur, $requeter);
449
-
450
-	return $res;
424
+    if (!($nom or $table or $champs)) {
425
+        spip_log("Champ manquant pour creer un index pg ($nom, $table, (" . @join(',', $champs) . "))",
426
+            'pg.' . _LOG_ERREUR);
427
+
428
+        return false;
429
+    }
430
+
431
+    $nom = str_replace("`", "", $nom);
432
+    $champs = str_replace("`", "", $champs);
433
+
434
+    // PG ne differentie pas noms des index en fonction des tables
435
+    // il faut donc creer des noms uniques d'index pour une base pg
436
+    $nom = $table . '_' . $nom;
437
+    // enlever d'eventuelles parentheses deja presentes sur champs
438
+    if (!is_array($champs)) {
439
+        if ($champs[0] == "(") {
440
+            $champs = substr($champs, 1, -1);
441
+        }
442
+        $champs = array($champs);
443
+    }
444
+    $query = "CREATE INDEX $nom ON $table (" . join(',', $champs) . ")";
445
+    if (!$requeter) {
446
+        return $query;
447
+    }
448
+    $res = spip_pg_query($query, $serveur, $requeter);
449
+
450
+    return $res;
451 451
 }
452 452
 
453 453
 
454 454
 // http://code.spip.net/@spip_pg_explain
455 455
 function spip_pg_explain($query, $serveur = '', $requeter = true) {
456
-	if (strpos(ltrim($query), 'SELECT') !== 0) {
457
-		return array();
458
-	}
459
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
460
-	$prefixe = $connexion['prefixe'];
461
-	$link = $connexion['link'];
462
-	if (preg_match('/\s(SET|VALUES|WHERE)\s/i', $query, $regs)) {
463
-		$suite = strstr($query, $regs[0]);
464
-		$query = substr($query, 0, -strlen($suite));
465
-	} else {
466
-		$suite = '';
467
-	}
468
-	$query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
469
-
470
-	if (!$requeter) {
471
-		return $query;
472
-	}
473
-	$r = spip_pg_query_simple($link, $query);
474
-
475
-	return spip_pg_fetch($r, null, $serveur);
456
+    if (strpos(ltrim($query), 'SELECT') !== 0) {
457
+        return array();
458
+    }
459
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
460
+    $prefixe = $connexion['prefixe'];
461
+    $link = $connexion['link'];
462
+    if (preg_match('/\s(SET|VALUES|WHERE)\s/i', $query, $regs)) {
463
+        $suite = strstr($query, $regs[0]);
464
+        $query = substr($query, 0, -strlen($suite));
465
+    } else {
466
+        $suite = '';
467
+    }
468
+    $query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
469
+
470
+    if (!$requeter) {
471
+        return $query;
472
+    }
473
+    $r = spip_pg_query_simple($link, $query);
474
+
475
+    return spip_pg_fetch($r, null, $serveur);
476 476
 }
477 477
 
478 478
 
@@ -491,92 +491,92 @@  discard block
 block discarded – undo
491 491
  *     - False en cas d'erreur.
492 492
  **/
493 493
 function spip_pg_selectdb($db, $serveur = '', $requeter = true) {
494
-	// se connecter a la base indiquee
495
-	// avec les identifiants connus
496
-	$index = $serveur ? strtolower($serveur) : 0;
497
-
498
-	if ($link = spip_connect_db('', '', '', '', $db, 'pg', '', '')) {
499
-		if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
500
-			return $db;
501
-		}
502
-	} else {
503
-		return false;
504
-	}
494
+    // se connecter a la base indiquee
495
+    // avec les identifiants connus
496
+    $index = $serveur ? strtolower($serveur) : 0;
497
+
498
+    if ($link = spip_connect_db('', '', '', '', $db, 'pg', '', '')) {
499
+        if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
500
+            return $db;
501
+        }
502
+    } else {
503
+        return false;
504
+    }
505 505
 }
506 506
 
507 507
 // Qu'une seule base pour le moment
508 508
 
509 509
 // http://code.spip.net/@spip_pg_listdbs
510 510
 function spip_pg_listdbs($serveur) {
511
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
512
-	$link = $connexion['link'];
513
-	$dbs = array();
514
-	$res = spip_pg_query_simple($link, "select * From pg_database");
515
-	while ($row = pg_fetch_array($res, null, PGSQL_NUM)) {
516
-		$dbs[] = reset($row);
517
-	}
518
-
519
-	return $dbs;
511
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
512
+    $link = $connexion['link'];
513
+    $dbs = array();
514
+    $res = spip_pg_query_simple($link, "select * From pg_database");
515
+    while ($row = pg_fetch_array($res, null, PGSQL_NUM)) {
516
+        $dbs[] = reset($row);
517
+    }
518
+
519
+    return $dbs;
520 520
 }
521 521
 
522 522
 // http://code.spip.net/@spip_pg_select
523 523
 function spip_pg_select(
524
-	$select,
525
-	$from,
526
-	$where = '',
527
-	$groupby = array(),
528
-	$orderby = '',
529
-	$limit = '',
530
-	$having = '',
531
-	$serveur = '',
532
-	$requeter = true
524
+    $select,
525
+    $from,
526
+    $where = '',
527
+    $groupby = array(),
528
+    $orderby = '',
529
+    $limit = '',
530
+    $having = '',
531
+    $serveur = '',
532
+    $requeter = true
533 533
 ) {
534 534
 
535
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
536
-	$prefixe = $connexion['prefixe'];
537
-	$link = $connexion['link'];
538
-	$db = $connexion['db'];
539
-
540
-	$limit = preg_match("/^\s*(([0-9]+),)?\s*([0-9]+)\s*$/", $limit, $limatch);
541
-	if ($limit) {
542
-		$offset = $limatch[2];
543
-		$count = $limatch[3];
544
-	}
545
-
546
-	$select = spip_pg_frommysql($select);
547
-
548
-	// si pas de tri explicitement demande, le GROUP BY ne
549
-	// contient que la clef primaire.
550
-	// lui ajouter alors le champ de tri par defaut
551
-	if (preg_match("/FIELD\(([a-z]+\.[a-z]+),/i", $orderby[0], $groupbyplus)) {
552
-		$groupby[] = $groupbyplus[1];
553
-	}
554
-
555
-	$orderby = spip_pg_orderby($orderby, $select);
556
-
557
-	if ($having) {
558
-		if (is_array($having)) {
559
-			$having = join("\n\tAND ", array_map('calculer_pg_where', $having));
560
-		}
561
-	}
562
-	$from = spip_pg_from($from, $prefixe);
563
-	$query = "SELECT " . $select
564
-		. (!$from ? '' : "\nFROM $from")
565
-		. (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
566
-				array_map('calculer_pg_where', $where))))))
567
-		. spip_pg_groupby($groupby, $from, $select)
568
-		. (!$having ? '' : "\nHAVING $having")
569
-		. ($orderby ? ("\nORDER BY $orderby") : '')
570
-		. (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset")));
571
-
572
-	// renvoyer la requete inerte si demandee
573
-	if ($requeter === false) {
574
-		return $query;
575
-	}
576
-
577
-	$r = spip_pg_trace_query($query, $serveur);
578
-
579
-	return $r ? $r : $query;;
535
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
536
+    $prefixe = $connexion['prefixe'];
537
+    $link = $connexion['link'];
538
+    $db = $connexion['db'];
539
+
540
+    $limit = preg_match("/^\s*(([0-9]+),)?\s*([0-9]+)\s*$/", $limit, $limatch);
541
+    if ($limit) {
542
+        $offset = $limatch[2];
543
+        $count = $limatch[3];
544
+    }
545
+
546
+    $select = spip_pg_frommysql($select);
547
+
548
+    // si pas de tri explicitement demande, le GROUP BY ne
549
+    // contient que la clef primaire.
550
+    // lui ajouter alors le champ de tri par defaut
551
+    if (preg_match("/FIELD\(([a-z]+\.[a-z]+),/i", $orderby[0], $groupbyplus)) {
552
+        $groupby[] = $groupbyplus[1];
553
+    }
554
+
555
+    $orderby = spip_pg_orderby($orderby, $select);
556
+
557
+    if ($having) {
558
+        if (is_array($having)) {
559
+            $having = join("\n\tAND ", array_map('calculer_pg_where', $having));
560
+        }
561
+    }
562
+    $from = spip_pg_from($from, $prefixe);
563
+    $query = "SELECT " . $select
564
+        . (!$from ? '' : "\nFROM $from")
565
+        . (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
566
+                array_map('calculer_pg_where', $where))))))
567
+        . spip_pg_groupby($groupby, $from, $select)
568
+        . (!$having ? '' : "\nHAVING $having")
569
+        . ($orderby ? ("\nORDER BY $orderby") : '')
570
+        . (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset")));
571
+
572
+    // renvoyer la requete inerte si demandee
573
+    if ($requeter === false) {
574
+        return $query;
575
+    }
576
+
577
+    $r = spip_pg_trace_query($query, $serveur);
578
+
579
+    return $r ? $r : $query;;
580 580
 }
581 581
 
582 582
 // Le traitement des prefixes de table dans un Select se limite au FROM
@@ -584,28 +584,28 @@  discard block
 block discarded – undo
584 584
 
585 585
 // http://code.spip.net/@spip_pg_from
586 586
 function spip_pg_from($from, $prefixe) {
587
-	if (is_array($from)) {
588
-		$from = spip_pg_select_as($from);
589
-	}
587
+    if (is_array($from)) {
588
+        $from = spip_pg_select_as($from);
589
+    }
590 590
 
591
-	return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1' . $prefixe . '_', $from);
591
+    return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1' . $prefixe . '_', $from);
592 592
 }
593 593
 
594 594
 // http://code.spip.net/@spip_pg_orderby
595 595
 function spip_pg_orderby($order, $select) {
596
-	$res = array();
597
-	$arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
596
+    $res = array();
597
+    $arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
598 598
 
599
-	foreach ($arg as $v) {
600
-		if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v . '/', $select, $m)) {
599
+    foreach ($arg as $v) {
600
+        if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v . '/', $select, $m)) {
601 601
 
602
-			$res[] = $m[1];
603
-		} else {
604
-			$res[] = $v;
605
-		}
606
-	}
602
+            $res[] = $m[1];
603
+        } else {
604
+            $res[] = $v;
605
+        }
606
+    }
607 607
 
608
-	return spip_pg_frommysql(join(',', $res));
608
+    return spip_pg_frommysql(join(',', $res));
609 609
 }
610 610
 
611 611
 // Conversion a l'arrach' des jointures MySQL en jointures PG
@@ -614,57 +614,57 @@  discard block
 block discarded – undo
614 614
 
615 615
 // http://code.spip.net/@spip_pg_groupby
616 616
 function spip_pg_groupby($groupby, $from, $select) {
617
-	$join = strpos($from, ",");
618
-	// ismplifier avant de decouper
619
-	if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne
620
-	{
621
-		$select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $select);
622
-	}
623
-
624
-	if ($join or $groupby) {
625
-		$join = is_array($select) ? $select : explode(", ", $select);
626
-	}
627
-	if ($join) {
628
-		// enlever les 0 as points, '', ...
629
-		foreach ($join as $k => $v) {
630
-			$v = str_replace('DISTINCT ', '', $v);
631
-			// fct SQL sur colonne et constante apostrophee ==> la colonne
632
-			$v = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $v);
633
-			$v = preg_replace('/CAST\(\s*([^(),\' ]*\s+)as\s*\w+\)/', '\\1', $v);
634
-			// resultat d'agregat ne sont pas a mettre dans le groupby
635
-			$v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)(\s*AS\s+\w+)\s*,?/i', '', $v);
636
-			// idem sans AS (fetch numerique)
637
-			$v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)\s*,?/i', '', $v);
638
-			// des AS simples : on garde le cote droit du AS
639
-			$v = preg_replace('/^.*\sAS\s+(\w+)\s*$/i', '\\1', $v);
640
-			// ne reste plus que les vrais colonnes, ou des constantes a virer
641
-			if (preg_match(',^[\'"],', $v) or is_numeric($v)) {
642
-				unset($join[$k]);
643
-			} else {
644
-				$join[$k] = trim($v);
645
-			}
646
-		}
647
-		$join = array_diff($join, array(''));
648
-		$join = implode(',', $join);
649
-	}
650
-	if (is_array($groupby)) {
651
-		$groupby = join(',', $groupby);
652
-	}
653
-	if ($join) {
654
-		$groupby = $groupby ? "$groupby, $join" : $join;
655
-	}
656
-	if (!$groupby) {
657
-		return '';
658
-	}
659
-
660
-	$groupby = spip_pg_frommysql($groupby);
661
-	// Ne pas mettre dans le Group-By des valeurs numeriques
662
-	// issue de prepare_recherche
663
-	$groupby = preg_replace('/^\s*\d+\s+AS\s+\w+\s*,?\s*/i', '', $groupby);
664
-	$groupby = preg_replace('/,\s*\d+\s+AS\s+\w+\s*/i', '', $groupby);
665
-	$groupby = preg_replace('/\s+AS\s+\w+\s*/i', '', $groupby);
666
-
667
-	return "\nGROUP BY $groupby";
617
+    $join = strpos($from, ",");
618
+    // ismplifier avant de decouper
619
+    if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne
620
+    {
621
+        $select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $select);
622
+    }
623
+
624
+    if ($join or $groupby) {
625
+        $join = is_array($select) ? $select : explode(", ", $select);
626
+    }
627
+    if ($join) {
628
+        // enlever les 0 as points, '', ...
629
+        foreach ($join as $k => $v) {
630
+            $v = str_replace('DISTINCT ', '', $v);
631
+            // fct SQL sur colonne et constante apostrophee ==> la colonne
632
+            $v = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $v);
633
+            $v = preg_replace('/CAST\(\s*([^(),\' ]*\s+)as\s*\w+\)/', '\\1', $v);
634
+            // resultat d'agregat ne sont pas a mettre dans le groupby
635
+            $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)(\s*AS\s+\w+)\s*,?/i', '', $v);
636
+            // idem sans AS (fetch numerique)
637
+            $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)\s*,?/i', '', $v);
638
+            // des AS simples : on garde le cote droit du AS
639
+            $v = preg_replace('/^.*\sAS\s+(\w+)\s*$/i', '\\1', $v);
640
+            // ne reste plus que les vrais colonnes, ou des constantes a virer
641
+            if (preg_match(',^[\'"],', $v) or is_numeric($v)) {
642
+                unset($join[$k]);
643
+            } else {
644
+                $join[$k] = trim($v);
645
+            }
646
+        }
647
+        $join = array_diff($join, array(''));
648
+        $join = implode(',', $join);
649
+    }
650
+    if (is_array($groupby)) {
651
+        $groupby = join(',', $groupby);
652
+    }
653
+    if ($join) {
654
+        $groupby = $groupby ? "$groupby, $join" : $join;
655
+    }
656
+    if (!$groupby) {
657
+        return '';
658
+    }
659
+
660
+    $groupby = spip_pg_frommysql($groupby);
661
+    // Ne pas mettre dans le Group-By des valeurs numeriques
662
+    // issue de prepare_recherche
663
+    $groupby = preg_replace('/^\s*\d+\s+AS\s+\w+\s*,?\s*/i', '', $groupby);
664
+    $groupby = preg_replace('/,\s*\d+\s+AS\s+\w+\s*/i', '', $groupby);
665
+    $groupby = preg_replace('/\s+AS\s+\w+\s*/i', '', $groupby);
666
+
667
+    return "\nGROUP BY $groupby";
668 668
 }
669 669
 
670 670
 // Conversion des operateurs MySQL en PG
@@ -676,472 +676,472 @@  discard block
 block discarded – undo
676 676
 
677 677
 // http://code.spip.net/@spip_pg_frommysql
678 678
 function spip_pg_frommysql($arg) {
679
-	if (is_array($arg)) {
680
-		$arg = join(", ", $arg);
681
-	}
679
+    if (is_array($arg)) {
680
+        $arg = join(", ", $arg);
681
+    }
682 682
 
683
-	$res = spip_pg_fromfield($arg);
683
+    $res = spip_pg_fromfield($arg);
684 684
 
685
-	$res = preg_replace('/\brand[(][)]/i', 'random()', $res);
685
+    $res = preg_replace('/\brand[(][)]/i', 'random()', $res);
686 686
 
687
-	$res = preg_replace('/\b0\.0[+]([a-zA-Z0-9_.]+)\s*/',
688
-		'CAST(substring(\1, \'^ *[0-9.]+\') as float)',
689
-		$res);
690
-	$res = preg_replace('/\b0[+]([a-zA-Z0-9_.]+)\s*/',
691
-		'CAST(substring(\1, \'^ *[0-9]+\') as int)',
692
-		$res);
693
-	$res = preg_replace('/\bconv[(]([^,]*)[^)]*[)]/i',
694
-		'CAST(substring(\1, \'^ *[0-9]+\') as int)',
695
-		$res);
687
+    $res = preg_replace('/\b0\.0[+]([a-zA-Z0-9_.]+)\s*/',
688
+        'CAST(substring(\1, \'^ *[0-9.]+\') as float)',
689
+        $res);
690
+    $res = preg_replace('/\b0[+]([a-zA-Z0-9_.]+)\s*/',
691
+        'CAST(substring(\1, \'^ *[0-9]+\') as int)',
692
+        $res);
693
+    $res = preg_replace('/\bconv[(]([^,]*)[^)]*[)]/i',
694
+        'CAST(substring(\1, \'^ *[0-9]+\') as int)',
695
+        $res);
696 696
 
697
-	$res = preg_replace('/UNIX_TIMESTAMP\s*[(]\s*[)]/',
698
-		' EXTRACT(epoch FROM NOW())', $res);
697
+    $res = preg_replace('/UNIX_TIMESTAMP\s*[(]\s*[)]/',
698
+        ' EXTRACT(epoch FROM NOW())', $res);
699 699
 
700
-	// la fonction md5(integer) n'est pas connu en pg
701
-	// il faut donc forcer les types en text (cas de md5(id_article))
702
-	$res = preg_replace('/md5\s*[(]([^)]*)[)]/i',
703
-		'MD5(CAST(\1 AS text))', $res);
700
+    // la fonction md5(integer) n'est pas connu en pg
701
+    // il faut donc forcer les types en text (cas de md5(id_article))
702
+    $res = preg_replace('/md5\s*[(]([^)]*)[)]/i',
703
+        'MD5(CAST(\1 AS text))', $res);
704 704
 
705
-	$res = preg_replace('/UNIX_TIMESTAMP\s*[(]([^)]*)[)]/',
706
-		' EXTRACT(epoch FROM \1)', $res);
705
+    $res = preg_replace('/UNIX_TIMESTAMP\s*[(]([^)]*)[)]/',
706
+        ' EXTRACT(epoch FROM \1)', $res);
707 707
 
708
-	$res = preg_replace('/\bDAYOFMONTH\s*[(]([^()]*([(][^()]*[)][^()]*)*[^)]*)[)]/',
709
-		' EXTRACT(day FROM \1)',
710
-		$res);
708
+    $res = preg_replace('/\bDAYOFMONTH\s*[(]([^()]*([(][^()]*[)][^()]*)*[^)]*)[)]/',
709
+        ' EXTRACT(day FROM \1)',
710
+        $res);
711 711
 
712
-	$res = preg_replace('/\bMONTH\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
713
-		' EXTRACT(month FROM \1)',
714
-		$res);
712
+    $res = preg_replace('/\bMONTH\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
713
+        ' EXTRACT(month FROM \1)',
714
+        $res);
715 715
 
716
-	$res = preg_replace('/\bYEAR\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
717
-		' EXTRACT(year FROM \1)',
718
-		$res);
716
+    $res = preg_replace('/\bYEAR\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
717
+        ' EXTRACT(year FROM \1)',
718
+        $res);
719 719
 
720
-	$res = preg_replace('/TO_DAYS\s*[(]([^()]*([(][^)]*[)][()]*)*)[)]/',
721
-		' EXTRACT(day FROM \1 - \'0001-01-01\')',
722
-		$res);
720
+    $res = preg_replace('/TO_DAYS\s*[(]([^()]*([(][^)]*[)][()]*)*)[)]/',
721
+        ' EXTRACT(day FROM \1 - \'0001-01-01\')',
722
+        $res);
723 723
 
724
-	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)\"([^\"]*)\"/", '\1\'\2\'', $res);
724
+    $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)\"([^\"]*)\"/", '\1\'\2\'', $res);
725 725
 
726
-	$res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m%d\'[)]/', 'to_char(\1, \'YYYYMMDD\')', $res);
726
+    $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m%d\'[)]/', 'to_char(\1, \'YYYYMMDD\')', $res);
727 727
 
728
-	$res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m\'[)]/', 'to_char(\1, \'YYYYMM\')', $res);
728
+    $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m\'[)]/', 'to_char(\1, \'YYYYMM\')', $res);
729 729
 
730
-	$res = preg_replace('/DATE_SUB\s*[(]([^,]*),/', '(\1 -', $res);
731
-	$res = preg_replace('/DATE_ADD\s*[(]([^,]*),/', '(\1 +', $res);
732
-	$res = preg_replace('/INTERVAL\s+(\d+\s+\w+)/', 'INTERVAL \'\1\'', $res);
733
-	$res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\s+\d+:\d+(:\d+)\')/', '\1 timestamp \2', $res);
734
-	$res = preg_replace('/(\'\d+-\d+-\d+\s+\d+:\d+:\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
730
+    $res = preg_replace('/DATE_SUB\s*[(]([^,]*),/', '(\1 -', $res);
731
+    $res = preg_replace('/DATE_ADD\s*[(]([^,]*),/', '(\1 +', $res);
732
+    $res = preg_replace('/INTERVAL\s+(\d+\s+\w+)/', 'INTERVAL \'\1\'', $res);
733
+    $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\s+\d+:\d+(:\d+)\')/', '\1 timestamp \2', $res);
734
+    $res = preg_replace('/(\'\d+-\d+-\d+\s+\d+:\d+:\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
735 735
 
736
-	$res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\')/', '\1 timestamp \2', $res);
737
-	$res = preg_replace('/(\'\d+-\d+-\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
736
+    $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\')/', '\1 timestamp \2', $res);
737
+    $res = preg_replace('/(\'\d+-\d+-\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
738 738
 
739
-	$res = preg_replace('/(timestamp .\d+)-00-/', '\1-01-', $res);
740
-	$res = preg_replace('/(timestamp .\d+-\d+)-00/', '\1-01', $res);
739
+    $res = preg_replace('/(timestamp .\d+)-00-/', '\1-01-', $res);
740
+    $res = preg_replace('/(timestamp .\d+-\d+)-00/', '\1-01', $res);
741 741
 # correct en theorie mais produit des debordements arithmetiques
742 742
 #	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)(timestamp *'[^']*' *[+-] *timestamp *'[^']*') *[)]/", '\2', $res);
743
-	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)('[^']*')/", '\1 timestamp \2', $res);
744
-	$res = preg_replace("/\sLIKE\s+/", ' ILIKE ', $res);
743
+    $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)('[^']*')/", '\1 timestamp \2', $res);
744
+    $res = preg_replace("/\sLIKE\s+/", ' ILIKE ', $res);
745 745
 
746
-	return str_replace('REGEXP', '~', $res);
746
+    return str_replace('REGEXP', '~', $res);
747 747
 }
748 748
 
749 749
 // http://code.spip.net/@spip_pg_fromfield
750 750
 function spip_pg_fromfield($arg) {
751
-	while (preg_match('/^(.*?)FIELD\s*\(([^,]*)((,[^,)]*)*)\)/', $arg, $m)) {
752
-
753
-		preg_match_all('/,([^,]*)/', $m[3], $r, PREG_PATTERN_ORDER);
754
-		$res = '';
755
-		$n = 0;
756
-		$index = $m[2];
757
-		foreach ($r[1] as $v) {
758
-			$n++;
759
-			$res .= "\nwhen $index=$v then $n";
760
-		}
761
-		$arg = $m[1] . "case $res else 0 end "
762
-			. substr($arg, strlen($m[0]));
763
-	}
764
-
765
-	return $arg;
751
+    while (preg_match('/^(.*?)FIELD\s*\(([^,]*)((,[^,)]*)*)\)/', $arg, $m)) {
752
+
753
+        preg_match_all('/,([^,]*)/', $m[3], $r, PREG_PATTERN_ORDER);
754
+        $res = '';
755
+        $n = 0;
756
+        $index = $m[2];
757
+        foreach ($r[1] as $v) {
758
+            $n++;
759
+            $res .= "\nwhen $index=$v then $n";
760
+        }
761
+        $arg = $m[1] . "case $res else 0 end "
762
+            . substr($arg, strlen($m[0]));
763
+    }
764
+
765
+    return $arg;
766 766
 }
767 767
 
768 768
 // http://code.spip.net/@calculer_pg_where
769 769
 function calculer_pg_where($v) {
770
-	if (!is_array($v)) {
771
-		return spip_pg_frommysql($v);
772
-	}
773
-
774
-	$op = str_replace('REGEXP', '~', array_shift($v));
775
-	if (!($n = count($v))) {
776
-		return $op;
777
-	} else {
778
-		$arg = calculer_pg_where(array_shift($v));
779
-		if ($n == 1) {
780
-			return "$op($arg)";
781
-		} else {
782
-			$arg2 = calculer_pg_where(array_shift($v));
783
-			if ($n == 2) {
784
-				return "($arg $op $arg2)";
785
-			} else {
786
-				return "($arg $op ($arg2) : $v[0])";
787
-			}
788
-		}
789
-	}
770
+    if (!is_array($v)) {
771
+        return spip_pg_frommysql($v);
772
+    }
773
+
774
+    $op = str_replace('REGEXP', '~', array_shift($v));
775
+    if (!($n = count($v))) {
776
+        return $op;
777
+    } else {
778
+        $arg = calculer_pg_where(array_shift($v));
779
+        if ($n == 1) {
780
+            return "$op($arg)";
781
+        } else {
782
+            $arg2 = calculer_pg_where(array_shift($v));
783
+            if ($n == 2) {
784
+                return "($arg $op $arg2)";
785
+            } else {
786
+                return "($arg $op ($arg2) : $v[0])";
787
+            }
788
+        }
789
+    }
790 790
 }
791 791
 
792 792
 
793 793
 // http://code.spip.net/@calculer_pg_expression
794 794
 function calculer_pg_expression($expression, $v, $join = 'AND') {
795
-	if (empty($v)) {
796
-		return '';
797
-	}
795
+    if (empty($v)) {
796
+        return '';
797
+    }
798 798
 
799
-	$exp = "\n$expression ";
799
+    $exp = "\n$expression ";
800 800
 
801
-	if (!is_array($v)) {
802
-		$v = array($v);
803
-	}
801
+    if (!is_array($v)) {
802
+        $v = array($v);
803
+    }
804 804
 
805
-	if (strtoupper($join) === 'AND') {
806
-		return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v));
807
-	} else {
808
-		return $exp . join($join, $v);
809
-	}
805
+    if (strtoupper($join) === 'AND') {
806
+        return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v));
807
+    } else {
808
+        return $exp . join($join, $v);
809
+    }
810 810
 }
811 811
 
812 812
 // http://code.spip.net/@spip_pg_select_as
813 813
 function spip_pg_select_as($args) {
814
-	$argsas = "";
815
-	foreach ($args as $k => $v) {
816
-		if (substr($k, -1) == '@') {
817
-			// c'est une jointure qui se refere au from precedent
818
-			// pas de virgule
819
-			$argsas .= '  ' . $v;
820
-		} else {
821
-			$as = '';
822
-			//  spip_log("$k : $v", _LOG_DEBUG);
823
-			if (!is_numeric($k)) {
824
-				if (preg_match('/\.(.*)$/', $k, $r)) {
825
-					$v = $k;
826
-				} elseif ($v != $k) {
827
-					$p = strpos($v, " ");
828
-					if ($p) {
829
-						$v = substr($v, 0, $p) . " AS $k" . substr($v, $p);
830
-					} else {
831
-						$as = " AS $k";
832
-					}
833
-				}
834
-			}
835
-			// spip_log("subs $k : $v avec $as", _LOG_DEBUG);
836
-			// if (strpos($v, 'JOIN') === false)  $argsas .= ', ';
837
-			$argsas .= ', ' . $v . $as;
838
-		}
839
-	}
840
-
841
-	return substr($argsas, 2);
814
+    $argsas = "";
815
+    foreach ($args as $k => $v) {
816
+        if (substr($k, -1) == '@') {
817
+            // c'est une jointure qui se refere au from precedent
818
+            // pas de virgule
819
+            $argsas .= '  ' . $v;
820
+        } else {
821
+            $as = '';
822
+            //  spip_log("$k : $v", _LOG_DEBUG);
823
+            if (!is_numeric($k)) {
824
+                if (preg_match('/\.(.*)$/', $k, $r)) {
825
+                    $v = $k;
826
+                } elseif ($v != $k) {
827
+                    $p = strpos($v, " ");
828
+                    if ($p) {
829
+                        $v = substr($v, 0, $p) . " AS $k" . substr($v, $p);
830
+                    } else {
831
+                        $as = " AS $k";
832
+                    }
833
+                }
834
+            }
835
+            // spip_log("subs $k : $v avec $as", _LOG_DEBUG);
836
+            // if (strpos($v, 'JOIN') === false)  $argsas .= ', ';
837
+            $argsas .= ', ' . $v . $as;
838
+        }
839
+    }
840
+
841
+    return substr($argsas, 2);
842 842
 }
843 843
 
844 844
 // http://code.spip.net/@spip_pg_fetch
845 845
 function spip_pg_fetch($res, $t = '', $serveur = '', $requeter = true) {
846 846
 
847
-	if ($res) {
848
-		$res = pg_fetch_array($res, null, PGSQL_ASSOC);
849
-	}
847
+    if ($res) {
848
+        $res = pg_fetch_array($res, null, PGSQL_ASSOC);
849
+    }
850 850
 
851
-	return $res;
851
+    return $res;
852 852
 }
853 853
 
854 854
 function spip_pg_seek($r, $row_number, $serveur = '', $requeter = true) {
855
-	if ($r) {
856
-		return pg_result_seek($r, $row_number);
857
-	}
855
+    if ($r) {
856
+        return pg_result_seek($r, $row_number);
857
+    }
858 858
 }
859 859
 
860 860
 
861 861
 // http://code.spip.net/@spip_pg_countsel
862 862
 function spip_pg_countsel(
863
-	$from = array(),
864
-	$where = array(),
865
-	$groupby = array(),
866
-	$having = array(),
867
-	$serveur = '',
868
-	$requeter = true
863
+    $from = array(),
864
+    $where = array(),
865
+    $groupby = array(),
866
+    $having = array(),
867
+    $serveur = '',
868
+    $requeter = true
869 869
 ) {
870
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
871
-	$r = spip_pg_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
872
-	if (!$requeter) {
873
-		return $r;
874
-	}
875
-	if (!is_resource($r)) {
876
-		return 0;
877
-	}
878
-	list($c) = pg_fetch_array($r, null, PGSQL_NUM);
879
-
880
-	return $c;
870
+    $c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
871
+    $r = spip_pg_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
872
+    if (!$requeter) {
873
+        return $r;
874
+    }
875
+    if (!is_resource($r)) {
876
+        return 0;
877
+    }
878
+    list($c) = pg_fetch_array($r, null, PGSQL_NUM);
879
+
880
+    return $c;
881 881
 }
882 882
 
883 883
 // http://code.spip.net/@spip_pg_count
884 884
 function spip_pg_count($res, $serveur = '', $requeter = true) {
885
-	return !$res ? 0 : pg_numrows($res);
885
+    return !$res ? 0 : pg_numrows($res);
886 886
 }
887 887
 
888 888
 // http://code.spip.net/@spip_pg_free
889 889
 function spip_pg_free($res, $serveur = '', $requeter = true) {
890
-	// rien a faire en postgres
890
+    // rien a faire en postgres
891 891
 }
892 892
 
893 893
 // http://code.spip.net/@spip_pg_delete
894 894
 function spip_pg_delete($table, $where = '', $serveur = '', $requeter = true) {
895 895
 
896
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
897
-	$table = prefixer_table_spip($table, $connexion['prefixe']);
896
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
897
+    $table = prefixer_table_spip($table, $connexion['prefixe']);
898 898
 
899
-	$query = calculer_pg_expression('DELETE FROM', $table, ',')
900
-		. calculer_pg_expression('WHERE', $where, 'AND');
899
+    $query = calculer_pg_expression('DELETE FROM', $table, ',')
900
+        . calculer_pg_expression('WHERE', $where, 'AND');
901 901
 
902
-	// renvoyer la requete inerte si demandee
903
-	if (!$requeter) {
904
-		return $query;
905
-	}
902
+    // renvoyer la requete inerte si demandee
903
+    if (!$requeter) {
904
+        return $query;
905
+    }
906 906
 
907
-	$res = spip_pg_trace_query($query, $serveur);
908
-	if ($res) {
909
-		return pg_affected_rows($res);
910
-	} else {
911
-		return false;
912
-	}
907
+    $res = spip_pg_trace_query($query, $serveur);
908
+    if ($res) {
909
+        return pg_affected_rows($res);
910
+    } else {
911
+        return false;
912
+    }
913 913
 }
914 914
 
915 915
 // http://code.spip.net/@spip_pg_insert
916 916
 function spip_pg_insert($table, $champs, $valeurs, $desc = array(), $serveur = '', $requeter = true) {
917
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
918
-	$prefixe = $connexion['prefixe'];
919
-	$link = $connexion['link'];
920
-
921
-	if (!$desc) {
922
-		$desc = description_table($table, $serveur);
923
-	}
924
-	$seq = spip_pg_sequence($table, true);
925
-	// si pas de cle primaire dans l'insertion, renvoyer curval
926
-	if (!preg_match(",\b$seq\b,", $champs)) {
927
-		$seq = spip_pg_sequence($table);
928
-		$seq = prefixer_table_spip($seq, $prefixe);
929
-		$seq = "currval('$seq')";
930
-	}
931
-
932
-	$table = prefixer_table_spip($table, $prefixe);
933
-	$ret = !$seq ? '' : (" RETURNING $seq");
934
-	$ins = (strlen($champs) < 3)
935
-		? " DEFAULT VALUES"
936
-		: "$champs VALUES $valeurs";
937
-	$q = "INSERT INTO $table $ins $ret";
938
-	if (!$requeter) {
939
-		return $q;
940
-	}
941
-	$connexion['last'] = $q;
942
-	$r = spip_pg_query_simple($link, $q);
917
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
918
+    $prefixe = $connexion['prefixe'];
919
+    $link = $connexion['link'];
920
+
921
+    if (!$desc) {
922
+        $desc = description_table($table, $serveur);
923
+    }
924
+    $seq = spip_pg_sequence($table, true);
925
+    // si pas de cle primaire dans l'insertion, renvoyer curval
926
+    if (!preg_match(",\b$seq\b,", $champs)) {
927
+        $seq = spip_pg_sequence($table);
928
+        $seq = prefixer_table_spip($seq, $prefixe);
929
+        $seq = "currval('$seq')";
930
+    }
931
+
932
+    $table = prefixer_table_spip($table, $prefixe);
933
+    $ret = !$seq ? '' : (" RETURNING $seq");
934
+    $ins = (strlen($champs) < 3)
935
+        ? " DEFAULT VALUES"
936
+        : "$champs VALUES $valeurs";
937
+    $q = "INSERT INTO $table $ins $ret";
938
+    if (!$requeter) {
939
+        return $q;
940
+    }
941
+    $connexion['last'] = $q;
942
+    $r = spip_pg_query_simple($link, $q);
943 943
 #	spip_log($q,'pg.'._LOG_DEBUG);
944
-	if ($r) {
945
-		if (!$ret) {
946
-			return 0;
947
-		}
948
-		if ($r2 = pg_fetch_array($r, null, PGSQL_NUM)) {
949
-			return $r2[0];
950
-		}
951
-	}
952
-
953
-	return false;
944
+    if ($r) {
945
+        if (!$ret) {
946
+            return 0;
947
+        }
948
+        if ($r2 = pg_fetch_array($r, null, PGSQL_NUM)) {
949
+            return $r2[0];
950
+        }
951
+    }
952
+
953
+    return false;
954 954
 }
955 955
 
956 956
 // http://code.spip.net/@spip_pg_insertq
957 957
 function spip_pg_insertq($table, $couples = array(), $desc = array(), $serveur = '', $requeter = true) {
958 958
 
959
-	if (!$desc) {
960
-		$desc = description_table($table, $serveur);
961
-	}
962
-	if (!$desc) {
963
-		die("$table insertion sans description");
964
-	}
965
-	$fields = $desc['field'];
959
+    if (!$desc) {
960
+        $desc = description_table($table, $serveur);
961
+    }
962
+    if (!$desc) {
963
+        die("$table insertion sans description");
964
+    }
965
+    $fields = $desc['field'];
966 966
 
967
-	foreach ($couples as $champ => $val) {
968
-		$couples[$champ] = spip_pg_cite($val, $fields[$champ]);
969
-	}
967
+    foreach ($couples as $champ => $val) {
968
+        $couples[$champ] = spip_pg_cite($val, $fields[$champ]);
969
+    }
970 970
 
971
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
972
-	$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
971
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
972
+    $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
973 973
 
974
-	return spip_pg_insert($table, "(" . join(',', array_keys($couples)) . ")", "(" . join(',', $couples) . ")", $desc,
975
-		$serveur, $requeter);
974
+    return spip_pg_insert($table, "(" . join(',', array_keys($couples)) . ")", "(" . join(',', $couples) . ")", $desc,
975
+        $serveur, $requeter);
976 976
 }
977 977
 
978 978
 
979 979
 // http://code.spip.net/@spip_pg_insertq_multi
980 980
 function spip_pg_insertq_multi($table, $tab_couples = array(), $desc = array(), $serveur = '', $requeter = true) {
981 981
 
982
-	if (!$desc) {
983
-		$desc = description_table($table, $serveur);
984
-	}
985
-	if (!$desc) {
986
-		die("$table insertion sans description");
987
-	}
988
-	$fields = isset($desc['field']) ? $desc['field'] : array();
989
-
990
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
991
-	// une premiere fois pour ajouter maj dans les cles
992
-	$c = isset($tab_couples[0]) ? $tab_couples[0] : array();
993
-	$les_cles = spip_pg_ajouter_champs_timestamp($table, $c, $desc, $serveur);
994
-
995
-	$cles = "(" . join(',', array_keys($les_cles)) . ')';
996
-	$valeurs = array();
997
-	foreach ($tab_couples as $couples) {
998
-		foreach ($couples as $champ => $val) {
999
-			$couples[$champ] = spip_pg_cite($val, $fields[$champ]);
1000
-		}
1001
-		// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1002
-		$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1003
-
1004
-		$valeurs[] = '(' . join(',', $couples) . ')';
1005
-	}
1006
-	$valeurs = implode(', ', $valeurs);
1007
-
1008
-	return spip_pg_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
982
+    if (!$desc) {
983
+        $desc = description_table($table, $serveur);
984
+    }
985
+    if (!$desc) {
986
+        die("$table insertion sans description");
987
+    }
988
+    $fields = isset($desc['field']) ? $desc['field'] : array();
989
+
990
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
991
+    // une premiere fois pour ajouter maj dans les cles
992
+    $c = isset($tab_couples[0]) ? $tab_couples[0] : array();
993
+    $les_cles = spip_pg_ajouter_champs_timestamp($table, $c, $desc, $serveur);
994
+
995
+    $cles = "(" . join(',', array_keys($les_cles)) . ')';
996
+    $valeurs = array();
997
+    foreach ($tab_couples as $couples) {
998
+        foreach ($couples as $champ => $val) {
999
+            $couples[$champ] = spip_pg_cite($val, $fields[$champ]);
1000
+        }
1001
+        // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1002
+        $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1003
+
1004
+        $valeurs[] = '(' . join(',', $couples) . ')';
1005
+    }
1006
+    $valeurs = implode(', ', $valeurs);
1007
+
1008
+    return spip_pg_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
1009 1009
 }
1010 1010
 
1011 1011
 
1012 1012
 // http://code.spip.net/@spip_pg_update
1013 1013
 function spip_pg_update($table, $couples, $where = '', $desc = '', $serveur = '', $requeter = true) {
1014 1014
 
1015
-	if (!$couples) {
1016
-		return;
1017
-	}
1018
-	$connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1019
-	$table = prefixer_table_spip($table, $connexion['prefixe']);
1015
+    if (!$couples) {
1016
+        return;
1017
+    }
1018
+    $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1019
+    $table = prefixer_table_spip($table, $connexion['prefixe']);
1020 1020
 
1021
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1022
-	$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1021
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1022
+    $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1023 1023
 
1024
-	$set = array();
1025
-	foreach ($couples as $champ => $val) {
1026
-		$set[] = $champ . '=' . $val;
1027
-	}
1024
+    $set = array();
1025
+    foreach ($couples as $champ => $val) {
1026
+        $set[] = $champ . '=' . $val;
1027
+    }
1028 1028
 
1029
-	$query = calculer_pg_expression('UPDATE', $table, ',')
1030
-		. calculer_pg_expression('SET', $set, ',')
1031
-		. calculer_pg_expression('WHERE', $where, 'AND');
1029
+    $query = calculer_pg_expression('UPDATE', $table, ',')
1030
+        . calculer_pg_expression('SET', $set, ',')
1031
+        . calculer_pg_expression('WHERE', $where, 'AND');
1032 1032
 
1033
-	// renvoyer la requete inerte si demandee
1034
-	if (!$requeter) {
1035
-		return $query;
1036
-	}
1033
+    // renvoyer la requete inerte si demandee
1034
+    if (!$requeter) {
1035
+        return $query;
1036
+    }
1037 1037
 
1038
-	return spip_pg_trace_query($query, $serveur);
1038
+    return spip_pg_trace_query($query, $serveur);
1039 1039
 }
1040 1040
 
1041 1041
 // idem, mais les valeurs sont des constantes a mettre entre apostrophes
1042 1042
 // sauf les expressions de date lorsqu'il s'agit de fonctions SQL (NOW etc)
1043 1043
 // http://code.spip.net/@spip_pg_updateq
1044 1044
 function spip_pg_updateq($table, $couples, $where = '', $desc = array(), $serveur = '', $requeter = true) {
1045
-	if (!$couples) {
1046
-		return;
1047
-	}
1048
-	if (!$desc) {
1049
-		$desc = description_table($table, $serveur);
1050
-	}
1051
-	$fields = $desc['field'];
1052
-	foreach ($couples as $k => $val) {
1053
-		$couples[$k] = spip_pg_cite($val, $fields[$k]);
1054
-	}
1055
-
1056
-	return spip_pg_update($table, $couples, $where, $desc, $serveur, $requeter);
1045
+    if (!$couples) {
1046
+        return;
1047
+    }
1048
+    if (!$desc) {
1049
+        $desc = description_table($table, $serveur);
1050
+    }
1051
+    $fields = $desc['field'];
1052
+    foreach ($couples as $k => $val) {
1053
+        $couples[$k] = spip_pg_cite($val, $fields[$k]);
1054
+    }
1055
+
1056
+    return spip_pg_update($table, $couples, $where, $desc, $serveur, $requeter);
1057 1057
 }
1058 1058
 
1059 1059
 
1060 1060
 // http://code.spip.net/@spip_pg_replace
1061 1061
 function spip_pg_replace($table, $values, $desc, $serveur = '', $requeter = true) {
1062
-	if (!$values) {
1063
-		spip_log("replace vide $table", 'pg.' . _LOG_AVERTISSEMENT);
1064
-
1065
-		return 0;
1066
-	}
1067
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1068
-	$prefixe = $connexion['prefixe'];
1069
-	$link = $connexion['link'];
1070
-
1071
-	if (!$desc) {
1072
-		$desc = description_table($table, $serveur);
1073
-	}
1074
-	if (!$desc) {
1075
-		die("$table insertion sans description");
1076
-	}
1077
-	$prim = $desc['key']['PRIMARY KEY'];
1078
-	$ids = preg_split('/,\s*/', $prim);
1079
-	$noprims = $prims = array();
1080
-	foreach ($values as $k => $v) {
1081
-		$values[$k] = $v = spip_pg_cite($v, $desc['field'][$k]);
1082
-
1083
-		if (!in_array($k, $ids)) {
1084
-			$noprims[$k] = "$k=$v";
1085
-		} else {
1086
-			$prims[$k] = "$k=$v";
1087
-		}
1088
-	}
1089
-
1090
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1091
-	$values = spip_pg_ajouter_champs_timestamp($table, $values, $desc, $serveur);
1092
-
1093
-	$where = join(' AND ', $prims);
1094
-	if (!$where) {
1095
-		return spip_pg_insert($table, "(" . join(',', array_keys($values)) . ")", "(" . join(',', $values) . ")", $desc,
1096
-			$serveur);
1097
-	}
1098
-	$couples = join(',', $noprims);
1099
-
1100
-	$seq = spip_pg_sequence($table);
1101
-	$table = prefixer_table_spip($table, $prefixe);
1102
-	$seq = prefixer_table_spip($seq, $prefixe);
1103
-
1104
-	$connexion['last'] = $q = "UPDATE $table SET $couples WHERE $where";
1105
-	if ($couples) {
1106
-		$couples = spip_pg_query_simple($link, $q);
1062
+    if (!$values) {
1063
+        spip_log("replace vide $table", 'pg.' . _LOG_AVERTISSEMENT);
1064
+
1065
+        return 0;
1066
+    }
1067
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1068
+    $prefixe = $connexion['prefixe'];
1069
+    $link = $connexion['link'];
1070
+
1071
+    if (!$desc) {
1072
+        $desc = description_table($table, $serveur);
1073
+    }
1074
+    if (!$desc) {
1075
+        die("$table insertion sans description");
1076
+    }
1077
+    $prim = $desc['key']['PRIMARY KEY'];
1078
+    $ids = preg_split('/,\s*/', $prim);
1079
+    $noprims = $prims = array();
1080
+    foreach ($values as $k => $v) {
1081
+        $values[$k] = $v = spip_pg_cite($v, $desc['field'][$k]);
1082
+
1083
+        if (!in_array($k, $ids)) {
1084
+            $noprims[$k] = "$k=$v";
1085
+        } else {
1086
+            $prims[$k] = "$k=$v";
1087
+        }
1088
+    }
1089
+
1090
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1091
+    $values = spip_pg_ajouter_champs_timestamp($table, $values, $desc, $serveur);
1092
+
1093
+    $where = join(' AND ', $prims);
1094
+    if (!$where) {
1095
+        return spip_pg_insert($table, "(" . join(',', array_keys($values)) . ")", "(" . join(',', $values) . ")", $desc,
1096
+            $serveur);
1097
+    }
1098
+    $couples = join(',', $noprims);
1099
+
1100
+    $seq = spip_pg_sequence($table);
1101
+    $table = prefixer_table_spip($table, $prefixe);
1102
+    $seq = prefixer_table_spip($seq, $prefixe);
1103
+
1104
+    $connexion['last'] = $q = "UPDATE $table SET $couples WHERE $where";
1105
+    if ($couples) {
1106
+        $couples = spip_pg_query_simple($link, $q);
1107 1107
 #	  spip_log($q,'pg.'._LOG_DEBUG);
1108
-		if (!$couples) {
1109
-			return false;
1110
-		}
1111
-		$couples = pg_affected_rows($couples);
1112
-	}
1113
-	if (!$couples) {
1114
-		$ret = !$seq ? '' :
1115
-			(" RETURNING nextval('$seq') < $prim");
1116
-		$connexion['last'] = $q = "INSERT INTO $table (" . join(',', array_keys($values)) . ') VALUES (' . join(',',
1117
-				$values) . ")$ret";
1118
-		$couples = spip_pg_query_simple($link, $q);
1119
-		if (!$couples) {
1120
-			return false;
1121
-		} elseif ($ret) {
1122
-			$r = pg_fetch_array($couples, null, PGSQL_NUM);
1123
-			if ($r[0]) {
1124
-				$connexion['last'] = $q = "SELECT setval('$seq', $prim) from $table";
1125
-				// Le code de SPIP met parfois la sequence a 0 (dans l'import)
1126
-				// MySQL n'en dit rien, on fait pareil pour PG
1127
-				$r = @pg_query($link, $q);
1128
-			}
1129
-		}
1130
-	}
1131
-
1132
-	return $couples;
1108
+        if (!$couples) {
1109
+            return false;
1110
+        }
1111
+        $couples = pg_affected_rows($couples);
1112
+    }
1113
+    if (!$couples) {
1114
+        $ret = !$seq ? '' :
1115
+            (" RETURNING nextval('$seq') < $prim");
1116
+        $connexion['last'] = $q = "INSERT INTO $table (" . join(',', array_keys($values)) . ') VALUES (' . join(',',
1117
+                $values) . ")$ret";
1118
+        $couples = spip_pg_query_simple($link, $q);
1119
+        if (!$couples) {
1120
+            return false;
1121
+        } elseif ($ret) {
1122
+            $r = pg_fetch_array($couples, null, PGSQL_NUM);
1123
+            if ($r[0]) {
1124
+                $connexion['last'] = $q = "SELECT setval('$seq', $prim) from $table";
1125
+                // Le code de SPIP met parfois la sequence a 0 (dans l'import)
1126
+                // MySQL n'en dit rien, on fait pareil pour PG
1127
+                $r = @pg_query($link, $q);
1128
+            }
1129
+        }
1130
+    }
1131
+
1132
+    return $couples;
1133 1133
 }
1134 1134
 
1135 1135
 
1136 1136
 // http://code.spip.net/@spip_pg_replace_multi
1137 1137
 function spip_pg_replace_multi($table, $tab_couples, $desc = array(), $serveur = '', $requeter = true) {
1138
-	// boucler pour traiter chaque requete independemment
1139
-	foreach ($tab_couples as $couples) {
1140
-		$retour = spip_pg_replace($table, $couples, $desc, $serveur, $requeter);
1141
-	}
1138
+    // boucler pour traiter chaque requete independemment
1139
+    foreach ($tab_couples as $couples) {
1140
+        $retour = spip_pg_replace($table, $couples, $desc, $serveur, $requeter);
1141
+    }
1142 1142
 
1143
-	// renvoie le dernier id
1144
-	return $retour;
1143
+    // renvoie le dernier id
1144
+    return $retour;
1145 1145
 }
1146 1146
 
1147 1147
 
@@ -1151,19 +1151,19 @@  discard block
 block discarded – undo
1151 1151
 // http://code.spip.net/@spip_pg_sequence
1152 1152
 function spip_pg_sequence($table, $raw = false) {
1153 1153
 
1154
-	include_spip('base/serial');
1155
-	if (!isset($GLOBALS['tables_principales'][$table])) {
1156
-		return false;
1157
-	}
1158
-	$desc = $GLOBALS['tables_principales'][$table];
1159
-	$prim = @$desc['key']['PRIMARY KEY'];
1160
-	if (!preg_match('/^\w+$/', $prim)
1161
-		or strpos($desc['field'][$prim], 'int') === false
1162
-	) {
1163
-		return '';
1164
-	} else {
1165
-		return $raw ? $prim : $table . '_' . $prim . "_seq";
1166
-	}
1154
+    include_spip('base/serial');
1155
+    if (!isset($GLOBALS['tables_principales'][$table])) {
1156
+        return false;
1157
+    }
1158
+    $desc = $GLOBALS['tables_principales'][$table];
1159
+    $prim = @$desc['key']['PRIMARY KEY'];
1160
+    if (!preg_match('/^\w+$/', $prim)
1161
+        or strpos($desc['field'][$prim], 'int') === false
1162
+    ) {
1163
+        return '';
1164
+    } else {
1165
+        return $raw ? $prim : $table . '_' . $prim . "_seq";
1166
+    }
1167 1167
 }
1168 1168
 
1169 1169
 // Explicite les conversions de Mysql d'une valeur $v de type $t
@@ -1171,65 +1171,65 @@  discard block
 block discarded – undo
1171 1171
 
1172 1172
 // http://code.spip.net/@spip_pg_cite
1173 1173
 function spip_pg_cite($v, $t) {
1174
-	if (is_null($v)) {
1175
-		return 'NULL';
1176
-	} // null php se traduit en NULL SQL
1177
-
1178
-	if (sql_test_date($t)) {
1179
-		if ($v and (strpos("0123456789", $v[0]) === false)) {
1180
-			return spip_pg_frommysql($v);
1181
-		} else {
1182
-			if (strncmp($v, '0000', 4) == 0) {
1183
-				$v = "0001" . substr($v, 4);
1184
-			}
1185
-			if (strpos($v, "-00-00") === 4) {
1186
-				$v = substr($v, 0, 4) . "-01-01" . substr($v, 10);
1187
-			}
1188
-
1189
-			return "timestamp '$v'";
1190
-		}
1191
-	} elseif (!sql_test_int($t)) {
1192
-		return ("'" . pg_escape_string($v) . "'");
1193
-	} elseif (is_numeric($v) or (strpos($v, 'CAST(') === 0)) {
1194
-		return $v;
1195
-	} elseif ($v[0] == '0' and $v[1] !== 'x' and ctype_xdigit(substr($v, 1))) {
1196
-		return substr($v, 1);
1197
-	} else {
1198
-		spip_log("Warning: '$v'  n'est pas de type $t", 'pg.' . _LOG_AVERTISSEMENT);
1199
-
1200
-		return intval($v);
1201
-	}
1174
+    if (is_null($v)) {
1175
+        return 'NULL';
1176
+    } // null php se traduit en NULL SQL
1177
+
1178
+    if (sql_test_date($t)) {
1179
+        if ($v and (strpos("0123456789", $v[0]) === false)) {
1180
+            return spip_pg_frommysql($v);
1181
+        } else {
1182
+            if (strncmp($v, '0000', 4) == 0) {
1183
+                $v = "0001" . substr($v, 4);
1184
+            }
1185
+            if (strpos($v, "-00-00") === 4) {
1186
+                $v = substr($v, 0, 4) . "-01-01" . substr($v, 10);
1187
+            }
1188
+
1189
+            return "timestamp '$v'";
1190
+        }
1191
+    } elseif (!sql_test_int($t)) {
1192
+        return ("'" . pg_escape_string($v) . "'");
1193
+    } elseif (is_numeric($v) or (strpos($v, 'CAST(') === 0)) {
1194
+        return $v;
1195
+    } elseif ($v[0] == '0' and $v[1] !== 'x' and ctype_xdigit(substr($v, 1))) {
1196
+        return substr($v, 1);
1197
+    } else {
1198
+        spip_log("Warning: '$v'  n'est pas de type $t", 'pg.' . _LOG_AVERTISSEMENT);
1199
+
1200
+        return intval($v);
1201
+    }
1202 1202
 }
1203 1203
 
1204 1204
 // http://code.spip.net/@spip_pg_hex
1205 1205
 function spip_pg_hex($v) {
1206
-	return "CAST(x'" . $v . "' as bigint)";
1206
+    return "CAST(x'" . $v . "' as bigint)";
1207 1207
 }
1208 1208
 
1209 1209
 function spip_pg_quote($v, $type = '') {
1210
-	if (!is_array($v)) {
1211
-		return spip_pg_cite($v, $type);
1212
-	}
1213
-	// si c'est un tableau, le parcourir en propageant le type
1214
-	foreach ($v as $k => $r) {
1215
-		$v[$k] = spip_pg_quote($r, $type);
1216
-	}
1217
-
1218
-	return join(",", $v);
1210
+    if (!is_array($v)) {
1211
+        return spip_pg_cite($v, $type);
1212
+    }
1213
+    // si c'est un tableau, le parcourir en propageant le type
1214
+    foreach ($v as $k => $r) {
1215
+        $v[$k] = spip_pg_quote($r, $type);
1216
+    }
1217
+
1218
+    return join(",", $v);
1219 1219
 }
1220 1220
 
1221 1221
 function spip_pg_date_proche($champ, $interval, $unite) {
1222
-	return '('
1223
-	. $champ
1224
-	. (($interval <= 0) ? '>' : '<')
1225
-	. (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1226
-	. '('
1227
-	. sql_quote(date('Y-m-d H:i:s'))
1228
-	. ', INTERVAL '
1229
-	. (($interval > 0) ? $interval : (0 - $interval))
1230
-	. ' '
1231
-	. $unite
1232
-	. '))';
1222
+    return '('
1223
+    . $champ
1224
+    . (($interval <= 0) ? '>' : '<')
1225
+    . (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1226
+    . '('
1227
+    . sql_quote(date('Y-m-d H:i:s'))
1228
+    . ', INTERVAL '
1229
+    . (($interval > 0) ? $interval : (0 - $interval))
1230
+    . ' '
1231
+    . $unite
1232
+    . '))';
1233 1233
 }
1234 1234
 
1235 1235
 // http://code.spip.net/@spip_pg_in
@@ -1237,69 +1237,69 @@  discard block
 block discarded – undo
1237 1237
 //
1238 1238
 // IN (...) souvent limite a 255  elements, d'ou cette fonction assistante
1239 1239
 //
1240
-	// s'il n'y a pas de valeur, eviter de produire un IN vide: PG rale.
1241
-	if (!$valeurs) {
1242
-		return $not ? '0=0' : '0=1';
1243
-	}
1244
-	if (strpos($valeurs, "CAST(x'") !== false) {
1245
-		return "($val=" . join("OR $val=", explode(',', $valeurs)) . ')';
1246
-	}
1247
-	$n = $i = 0;
1248
-	$in_sql = "";
1249
-	while ($n = strpos($valeurs, ',', $n + 1)) {
1250
-		if ((++$i) >= 255) {
1251
-			$in_sql .= "($val $not IN (" .
1252
-				substr($valeurs, 0, $n) .
1253
-				"))\n" .
1254
-				($not ? "AND\t" : "OR\t");
1255
-			$valeurs = substr($valeurs, $n + 1);
1256
-			$i = $n = 0;
1257
-		}
1258
-	}
1259
-	$in_sql .= "($val $not IN ($valeurs))";
1260
-
1261
-	return "($in_sql)";
1240
+    // s'il n'y a pas de valeur, eviter de produire un IN vide: PG rale.
1241
+    if (!$valeurs) {
1242
+        return $not ? '0=0' : '0=1';
1243
+    }
1244
+    if (strpos($valeurs, "CAST(x'") !== false) {
1245
+        return "($val=" . join("OR $val=", explode(',', $valeurs)) . ')';
1246
+    }
1247
+    $n = $i = 0;
1248
+    $in_sql = "";
1249
+    while ($n = strpos($valeurs, ',', $n + 1)) {
1250
+        if ((++$i) >= 255) {
1251
+            $in_sql .= "($val $not IN (" .
1252
+                substr($valeurs, 0, $n) .
1253
+                "))\n" .
1254
+                ($not ? "AND\t" : "OR\t");
1255
+            $valeurs = substr($valeurs, $n + 1);
1256
+            $i = $n = 0;
1257
+        }
1258
+    }
1259
+    $in_sql .= "($val $not IN ($valeurs))";
1260
+
1261
+    return "($in_sql)";
1262 1262
 }
1263 1263
 
1264 1264
 // http://code.spip.net/@spip_pg_error
1265 1265
 function spip_pg_error($query = '', $serveur, $requeter = true) {
1266
-	$link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1267
-	$s = $link ? pg_last_error($link) : pg_last_error();
1268
-	if ($s) {
1269
-		$s = str_replace('ERROR', 'errcode: 1000 ', $s);
1270
-		spip_log("$s - $query", 'pg.' . _LOG_ERREUR);
1271
-	}
1272
-
1273
-	return $s;
1266
+    $link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1267
+    $s = $link ? pg_last_error($link) : pg_last_error();
1268
+    if ($s) {
1269
+        $s = str_replace('ERROR', 'errcode: 1000 ', $s);
1270
+        spip_log("$s - $query", 'pg.' . _LOG_ERREUR);
1271
+    }
1272
+
1273
+    return $s;
1274 1274
 }
1275 1275
 
1276 1276
 // http://code.spip.net/@spip_pg_errno
1277 1277
 function spip_pg_errno($serveur = '') {
1278
-	// il faudrait avoir la derniere ressource retournee et utiliser
1279
-	// http://fr2.php.net/manual/fr/function.pg-result-error.php
1280
-	return 0;
1278
+    // il faudrait avoir la derniere ressource retournee et utiliser
1279
+    // http://fr2.php.net/manual/fr/function.pg-result-error.php
1280
+    return 0;
1281 1281
 }
1282 1282
 
1283 1283
 // http://code.spip.net/@spip_pg_drop_table
1284 1284
 function spip_pg_drop_table($table, $exist = '', $serveur = '', $requeter = true) {
1285
-	if ($exist) {
1286
-		$exist = " IF EXISTS";
1287
-	}
1288
-	if (spip_pg_query("DROP TABLE$exist $table", $serveur, $requeter)) {
1289
-		return true;
1290
-	} else {
1291
-		return false;
1292
-	}
1285
+    if ($exist) {
1286
+        $exist = " IF EXISTS";
1287
+    }
1288
+    if (spip_pg_query("DROP TABLE$exist $table", $serveur, $requeter)) {
1289
+        return true;
1290
+    } else {
1291
+        return false;
1292
+    }
1293 1293
 }
1294 1294
 
1295 1295
 // supprime une vue 
1296 1296
 // http://code.spip.net/@spip_pg_drop_view
1297 1297
 function spip_pg_drop_view($view, $exist = '', $serveur = '', $requeter = true) {
1298
-	if ($exist) {
1299
-		$exist = " IF EXISTS";
1300
-	}
1298
+    if ($exist) {
1299
+        $exist = " IF EXISTS";
1300
+    }
1301 1301
 
1302
-	return spip_pg_query("DROP VIEW$exist $view", $serveur, $requeter);
1302
+    return spip_pg_query("DROP VIEW$exist $view", $serveur, $requeter);
1303 1303
 }
1304 1304
 
1305 1305
 /**
@@ -1316,41 +1316,41 @@  discard block
 block discarded – undo
1316 1316
  *     Ressource à utiliser avec sql_fetch()
1317 1317
  **/
1318 1318
 function spip_pg_showbase($match, $serveur = '', $requeter = true) {
1319
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1320
-	$link = $connexion['link'];
1321
-	$connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE " . _q($match);
1319
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1320
+    $link = $connexion['link'];
1321
+    $connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE " . _q($match);
1322 1322
 
1323
-	return spip_pg_query_simple($link, $q);
1323
+    return spip_pg_query_simple($link, $q);
1324 1324
 }
1325 1325
 
1326 1326
 // http://code.spip.net/@spip_pg_showtable
1327 1327
 function spip_pg_showtable($nom_table, $serveur = '', $requeter = true) {
1328
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1329
-	$link = $connexion['link'];
1330
-	$connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table);
1331
-
1332
-	$res = spip_pg_query_simple($link, $q);
1333
-	if (!$res) {
1334
-		return false;
1335
-	}
1336
-
1337
-	// etrangement, $res peut ne rien contenir, mais arriver ici...
1338
-	// il faut en tenir compte dans le return
1339
-	$fields = array();
1340
-	while ($field = pg_fetch_array($res, null, PGSQL_NUM)) {
1341
-		$fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1]));
1342
-	}
1343
-	$connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table);
1344
-	$res = spip_pg_query_simple($link, $q);
1345
-	$keys = array();
1346
-	while ($index = pg_fetch_array($res, null, PGSQL_NUM)) {
1347
-		if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0], $r)) {
1348
-			$nom = str_replace($nom_table . '_', '', $r[2]);
1349
-			$keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3];
1350
-		}
1351
-	}
1352
-
1353
-	return count($fields) ? array('field' => $fields, 'key' => $keys) : false;
1328
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1329
+    $link = $connexion['link'];
1330
+    $connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table);
1331
+
1332
+    $res = spip_pg_query_simple($link, $q);
1333
+    if (!$res) {
1334
+        return false;
1335
+    }
1336
+
1337
+    // etrangement, $res peut ne rien contenir, mais arriver ici...
1338
+    // il faut en tenir compte dans le return
1339
+    $fields = array();
1340
+    while ($field = pg_fetch_array($res, null, PGSQL_NUM)) {
1341
+        $fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1]));
1342
+    }
1343
+    $connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table);
1344
+    $res = spip_pg_query_simple($link, $q);
1345
+    $keys = array();
1346
+    while ($index = pg_fetch_array($res, null, PGSQL_NUM)) {
1347
+        if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0], $r)) {
1348
+            $nom = str_replace($nom_table . '_', '', $r[2]);
1349
+            $keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3];
1350
+        }
1351
+    }
1352
+
1353
+    return count($fields) ? array('field' => $fields, 'key' => $keys) : false;
1354 1354
 }
1355 1355
 
1356 1356
 // Fonction de creation d'une table SQL nommee $nom
@@ -1362,118 +1362,118 @@  discard block
 block discarded – undo
1362 1362
 // http://code.spip.net/@spip_pg_create
1363 1363
 function spip_pg_create($nom, $champs, $cles, $autoinc = false, $temporary = false, $serveur = '', $requeter = true) {
1364 1364
 
1365
-	$connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1366
-	$link = $connexion['link'];
1367
-	$nom = prefixer_table_spip($nom, $connexion['prefixe']);
1368
-
1369
-	$query = $prim = $prim_name = $v = $s = $p = '';
1370
-	$keys = array();
1371
-
1372
-	// certains plugins declarent les tables  (permet leur inclusion dans le dump)
1373
-	// sans les renseigner (laisse le compilo recuperer la description)
1374
-	if (!is_array($champs) || !is_array($cles)) {
1375
-		return;
1376
-	}
1377
-
1378
-	foreach ($cles as $k => $v) {
1379
-		if (strpos($k, "KEY ") === 0) {
1380
-			$n = str_replace('`', '', $k);
1381
-			$v = str_replace('`', '"', $v);
1382
-			$i = $nom . preg_replace("/KEY +/", '_', $n);
1383
-			if ($k != $n) {
1384
-				$i = "\"$i\"";
1385
-			}
1386
-			$keys[] = "CREATE INDEX $i ON $nom ($v);";
1387
-		} elseif (strpos($k, "UNIQUE ") === 0) {
1388
-			$k = preg_replace("/^UNIQUE +/", '', $k);
1389
-			$prim .= "$s\n\t\tCONSTRAINT " . str_replace('`', '"', $k) . " UNIQUE ($v)";
1390
-		} else {
1391
-			$prim .= "$s\n\t\t" . str_replace('`', '"', $k) . " ($v)";
1392
-		}
1393
-		if ($k == "PRIMARY KEY") {
1394
-			$prim_name = $v;
1395
-		}
1396
-		$s = ",";
1397
-	}
1398
-	$s = '';
1399
-
1400
-	$character_set = "";
1401
-	if (@$GLOBALS['meta']['charset_sql_base']) {
1402
-		$character_set .= " CHARACTER SET " . $GLOBALS['meta']['charset_sql_base'];
1403
-	}
1404
-	if (@$GLOBALS['meta']['charset_collation_sql_base']) {
1405
-		$character_set .= " COLLATE " . $GLOBALS['meta']['charset_collation_sql_base'];
1406
-	}
1407
-
1408
-	foreach ($champs as $k => $v) {
1409
-		$k = str_replace('`', '"', $k);
1410
-		if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
1411
-			if (preg_match(',(char|text),i', $defs[1]) and !preg_match(',binary,i', $defs[1])) {
1412
-				$v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
1413
-			}
1414
-		}
1415
-
1416
-		$query .= "$s\n\t\t$k "
1417
-			. (($autoinc && ($prim_name == $k) && preg_match(',\b(big|small|medium|tiny)?int\b,i', $v))
1418
-				? " bigserial"
1419
-				: mysql2pg_type($v)
1420
-			);
1421
-		$s = ",";
1422
-	}
1423
-	$temporary = $temporary ? 'TEMPORARY' : '';
1424
-
1425
-	// En l'absence de "if not exists" en PG, on neutralise les erreurs
1426
-
1427
-	$q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")" .
1428
-		($character_set ? " DEFAULT $character_set" : "")
1429
-		. "\n";
1430
-
1431
-	if (!$requeter) {
1432
-		return $q;
1433
-	}
1434
-	$connexion['last'] = $q;
1435
-	$r = @pg_query($link, $q);
1436
-
1437
-	if (!$r) {
1438
-		spip_log("Impossible de creer cette table: $q", 'pg.' . _LOG_ERREUR);
1439
-	} else {
1440
-		foreach ($keys as $index) {
1441
-			pg_query($link, $index);
1442
-		}
1443
-	}
1444
-
1445
-	return $r;
1365
+    $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1366
+    $link = $connexion['link'];
1367
+    $nom = prefixer_table_spip($nom, $connexion['prefixe']);
1368
+
1369
+    $query = $prim = $prim_name = $v = $s = $p = '';
1370
+    $keys = array();
1371
+
1372
+    // certains plugins declarent les tables  (permet leur inclusion dans le dump)
1373
+    // sans les renseigner (laisse le compilo recuperer la description)
1374
+    if (!is_array($champs) || !is_array($cles)) {
1375
+        return;
1376
+    }
1377
+
1378
+    foreach ($cles as $k => $v) {
1379
+        if (strpos($k, "KEY ") === 0) {
1380
+            $n = str_replace('`', '', $k);
1381
+            $v = str_replace('`', '"', $v);
1382
+            $i = $nom . preg_replace("/KEY +/", '_', $n);
1383
+            if ($k != $n) {
1384
+                $i = "\"$i\"";
1385
+            }
1386
+            $keys[] = "CREATE INDEX $i ON $nom ($v);";
1387
+        } elseif (strpos($k, "UNIQUE ") === 0) {
1388
+            $k = preg_replace("/^UNIQUE +/", '', $k);
1389
+            $prim .= "$s\n\t\tCONSTRAINT " . str_replace('`', '"', $k) . " UNIQUE ($v)";
1390
+        } else {
1391
+            $prim .= "$s\n\t\t" . str_replace('`', '"', $k) . " ($v)";
1392
+        }
1393
+        if ($k == "PRIMARY KEY") {
1394
+            $prim_name = $v;
1395
+        }
1396
+        $s = ",";
1397
+    }
1398
+    $s = '';
1399
+
1400
+    $character_set = "";
1401
+    if (@$GLOBALS['meta']['charset_sql_base']) {
1402
+        $character_set .= " CHARACTER SET " . $GLOBALS['meta']['charset_sql_base'];
1403
+    }
1404
+    if (@$GLOBALS['meta']['charset_collation_sql_base']) {
1405
+        $character_set .= " COLLATE " . $GLOBALS['meta']['charset_collation_sql_base'];
1406
+    }
1407
+
1408
+    foreach ($champs as $k => $v) {
1409
+        $k = str_replace('`', '"', $k);
1410
+        if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
1411
+            if (preg_match(',(char|text),i', $defs[1]) and !preg_match(',binary,i', $defs[1])) {
1412
+                $v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
1413
+            }
1414
+        }
1415
+
1416
+        $query .= "$s\n\t\t$k "
1417
+            . (($autoinc && ($prim_name == $k) && preg_match(',\b(big|small|medium|tiny)?int\b,i', $v))
1418
+                ? " bigserial"
1419
+                : mysql2pg_type($v)
1420
+            );
1421
+        $s = ",";
1422
+    }
1423
+    $temporary = $temporary ? 'TEMPORARY' : '';
1424
+
1425
+    // En l'absence de "if not exists" en PG, on neutralise les erreurs
1426
+
1427
+    $q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")" .
1428
+        ($character_set ? " DEFAULT $character_set" : "")
1429
+        . "\n";
1430
+
1431
+    if (!$requeter) {
1432
+        return $q;
1433
+    }
1434
+    $connexion['last'] = $q;
1435
+    $r = @pg_query($link, $q);
1436
+
1437
+    if (!$r) {
1438
+        spip_log("Impossible de creer cette table: $q", 'pg.' . _LOG_ERREUR);
1439
+    } else {
1440
+        foreach ($keys as $index) {
1441
+            pg_query($link, $index);
1442
+        }
1443
+    }
1444
+
1445
+    return $r;
1446 1446
 }
1447 1447
 
1448 1448
 
1449 1449
 function spip_pg_create_base($nom, $serveur = '', $requeter = true) {
1450
-	return spip_pg_query("CREATE DATABASE $nom", $serveur, $requeter);
1450
+    return spip_pg_query("CREATE DATABASE $nom", $serveur, $requeter);
1451 1451
 }
1452 1452
 
1453 1453
 // Fonction de creation d'une vue SQL nommee $nom
1454 1454
 // http://code.spip.net/@spip_pg_create_view
1455 1455
 function spip_pg_create_view($nom, $query_select, $serveur = '', $requeter = true) {
1456
-	if (!$query_select) {
1457
-		return false;
1458
-	}
1459
-	// vue deja presente
1460
-	if (sql_showtable($nom, false, $serveur)) {
1461
-		if ($requeter) {
1462
-			spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.' . _LOG_ERREUR);
1463
-		}
1456
+    if (!$query_select) {
1457
+        return false;
1458
+    }
1459
+    // vue deja presente
1460
+    if (sql_showtable($nom, false, $serveur)) {
1461
+        if ($requeter) {
1462
+            spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.' . _LOG_ERREUR);
1463
+        }
1464 1464
 
1465
-		return false;
1466
-	}
1465
+        return false;
1466
+    }
1467 1467
 
1468
-	$query = "CREATE VIEW $nom AS " . $query_select;
1468
+    $query = "CREATE VIEW $nom AS " . $query_select;
1469 1469
 
1470
-	return spip_pg_query($query, $serveur, $requeter);
1470
+    return spip_pg_query($query, $serveur, $requeter);
1471 1471
 }
1472 1472
 
1473 1473
 
1474 1474
 // http://code.spip.net/@spip_pg_set_connect_charset
1475 1475
 function spip_pg_set_connect_charset($charset, $serveur = '', $requeter = true) {
1476
-	spip_log("changement de charset sql a ecrire en PG", 'pg.' . _LOG_ERREUR);
1476
+    spip_log("changement de charset sql a ecrire en PG", 'pg.' . _LOG_ERREUR);
1477 1477
 }
1478 1478
 
1479 1479
 
@@ -1487,7 +1487,7 @@  discard block
 block discarded – undo
1487 1487
  **/
1488 1488
 // http://code.spip.net/@spip_sqlite_optimize
1489 1489
 function spip_pg_optimize($table, $serveur = '', $requeter = true) {
1490
-	return spip_pg_query("VACUUM " . $table, $serveur, $requeter);
1490
+    return spip_pg_query("VACUUM " . $table, $serveur, $requeter);
1491 1491
 }
1492 1492
 
1493 1493
 // Selectionner la sous-chaine dans $objet
@@ -1495,13 +1495,13 @@  discard block
 block discarded – undo
1495 1495
 
1496 1496
 // http://code.spip.net/@spip_pg_multi
1497 1497
 function spip_pg_multi($objet, $lang) {
1498
-	$r = "regexp_replace("
1499
-		. $objet
1500
-		. ",'<multi>.*[[]"
1501
-		. $lang
1502
-		. "[]]([^[]*).*</multi>', E'\\\\1') AS multi";
1498
+    $r = "regexp_replace("
1499
+        . $objet
1500
+        . ",'<multi>.*[[]"
1501
+        . $lang
1502
+        . "[]]([^[]*).*</multi>', E'\\\\1') AS multi";
1503 1503
 
1504
-	return $r;
1504
+    return $r;
1505 1505
 }
1506 1506
 
1507 1507
 // Palanquee d'idiosyncrasies MySQL dans les creations de table
@@ -1509,31 +1509,31 @@  discard block
 block discarded – undo
1509 1509
 
1510 1510
 // http://code.spip.net/@mysql2pg_type
1511 1511
 function mysql2pg_type($v) {
1512
-	$remplace = array(
1513
-		'/auto_increment/i' => '', // non reconnu
1514
-		'/bigint/i' => 'bigint',
1515
-		'/mediumint/i' => 'mediumint',
1516
-		'/smallint/i' => 'smallint',
1517
-		"/tinyint/i" => 'int',
1518
-		'/int\s*[(]\s*\d+\s*[)]/i' => 'int',
1519
-		"/longtext/i" => 'text',
1520
-		"/mediumtext/i" => 'text',
1521
-		"/tinytext/i" => 'text',
1522
-		"/longblob/i" => 'text',
1523
-		"/0000-00-00/" => '0001-01-01',
1524
-		"/datetime/i" => 'timestamp',
1525
-		"/unsigned/i" => '',
1526
-		"/double/i" => 'double precision',
1527
-		'/VARCHAR\((\d+)\)\s+BINARY/i' => 'varchar(\1)',
1528
-		"/ENUM *[(][^)]*[)]/i" => "varchar(255)",
1529
-		'/(timestamp .* )ON .*$/is' => '\\1',
1530
-	);
1531
-
1532
-	return preg_replace(array_keys($remplace), array_values($remplace), $v);
1512
+    $remplace = array(
1513
+        '/auto_increment/i' => '', // non reconnu
1514
+        '/bigint/i' => 'bigint',
1515
+        '/mediumint/i' => 'mediumint',
1516
+        '/smallint/i' => 'smallint',
1517
+        "/tinyint/i" => 'int',
1518
+        '/int\s*[(]\s*\d+\s*[)]/i' => 'int',
1519
+        "/longtext/i" => 'text',
1520
+        "/mediumtext/i" => 'text',
1521
+        "/tinytext/i" => 'text',
1522
+        "/longblob/i" => 'text',
1523
+        "/0000-00-00/" => '0001-01-01',
1524
+        "/datetime/i" => 'timestamp',
1525
+        "/unsigned/i" => '',
1526
+        "/double/i" => 'double precision',
1527
+        '/VARCHAR\((\d+)\)\s+BINARY/i' => 'varchar(\1)',
1528
+        "/ENUM *[(][^)]*[)]/i" => "varchar(255)",
1529
+        '/(timestamp .* )ON .*$/is' => '\\1',
1530
+    );
1531
+
1532
+    return preg_replace(array_keys($remplace), array_values($remplace), $v);
1533 1533
 }
1534 1534
 
1535 1535
 // Renvoie false si on n'a pas les fonctions pg (pour l'install)
1536 1536
 // http://code.spip.net/@spip_versions_pg
1537 1537
 function spip_versions_pg() {
1538
-	return function_exists('pg_connect');
1538
+    return function_exists('pg_connect');
1539 1539
 }
Please login to merge, or discard this patch.
ecrire/xml/analyser_dtd.php 3 patches
Doc Comments   +24 added lines patch added patch discarded remove patch
@@ -167,6 +167,9 @@  discard block
 block discarded – undo
167 167
 }
168 168
 
169 169
 // http://code.spip.net/@analyser_dtd_comment
170
+/**
171
+ * @param string $dtd
172
+ */
170 173
 function analyser_dtd_comment($dtd, &$dtc, $grammaire) {
171 174
 	// ejecter les commentaires, surtout quand ils contiennent du code.
172 175
 	// Option /s car sur plusieurs lignes parfois
@@ -179,6 +182,9 @@  discard block
 block discarded – undo
179 182
 }
180 183
 
181 184
 // http://code.spip.net/@analyser_dtd_pi
185
+/**
186
+ * @param string $dtd
187
+ */
182 188
 function analyser_dtd_pi($dtd, &$dtc, $grammaire) {
183 189
 	if (!preg_match('/^<\?.*?>\s*(.*)$/s', $dtd, $m)) {
184 190
 		return -10;
@@ -188,6 +194,9 @@  discard block
 block discarded – undo
188 194
 }
189 195
 
190 196
 // http://code.spip.net/@analyser_dtd_lexeme
197
+/**
198
+ * @param string $dtd
199
+ */
191 200
 function analyser_dtd_lexeme($dtd, &$dtc, $grammaire) {
192 201
 
193 202
 	if (!preg_match(_REGEXP_ENTITY_DEF, $dtd, $m)) {
@@ -215,6 +224,9 @@  discard block
 block discarded – undo
215 224
 // ca ne depasse pas 3 ici.
216 225
 
217 226
 // http://code.spip.net/@analyser_dtd_data
227
+/**
228
+ * @param string $dtd
229
+ */
218 230
 function analyser_dtd_data($dtd, &$dtc, $grammaire) {
219 231
 
220 232
 	if (!preg_match(_REGEXP_INCLUDE_USE, $dtd, $m)) {
@@ -236,6 +248,9 @@  discard block
 block discarded – undo
236 248
 }
237 249
 
238 250
 // http://code.spip.net/@analyser_dtd_notation
251
+/**
252
+ * @param string $dtd
253
+ */
239 254
 function analyser_dtd_notation($dtd, &$dtc, $grammaire) {
240 255
 	if (!preg_match('/^<!NOTATION.*?>\s*(.*)$/s', $dtd, $m)) {
241 256
 		return -8;
@@ -246,6 +261,9 @@  discard block
 block discarded – undo
246 261
 }
247 262
 
248 263
 // http://code.spip.net/@analyser_dtd_entity
264
+/**
265
+ * @param string $dtd
266
+ */
249 267
 function analyser_dtd_entity($dtd, &$dtc, $grammaire) {
250 268
 	if (!preg_match(_REGEXP_ENTITY_DECL, $dtd, $m)) {
251 269
 		return -2;
@@ -303,6 +321,9 @@  discard block
 block discarded – undo
303 321
 // Fin du controle en finElement
304 322
 
305 323
 // http://code.spip.net/@analyser_dtd_element
324
+/**
325
+ * @param string $dtd
326
+ */
306 327
 function analyser_dtd_element($dtd, &$dtc, $grammaire) {
307 328
 	if (!preg_match('/^<!ELEMENT\s+([^>\s]+)([^>]*)>\s*(.*)$/s', $dtd, $m)) {
308 329
 		return -3;
@@ -351,6 +372,9 @@  discard block
 block discarded – undo
351 372
 
352 373
 
353 374
 // http://code.spip.net/@analyser_dtd_attlist
375
+/**
376
+ * @param string $dtd
377
+ */
354 378
 function analyser_dtd_attlist($dtd, &$dtc, $grammaire) {
355 379
 	if (!preg_match('/^<!ATTLIST\s+(\S+)\s+([^>]*)>\s*(.*)/s', $dtd, $m)) {
356 380
 		return -5;
Please login to merge, or discard this patch.
Indentation   +311 added lines, -311 removed lines patch added patch discarded remove patch
@@ -11,59 +11,59 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('xml/interfaces');
18 18
 
19 19
 // http://code.spip.net/@charger_dtd
20 20
 function charger_dtd($grammaire, $avail, $rotlvl) {
21
-	static $dtd = array(); # cache bien utile pour le validateur en boucle
22
-
23
-	if (isset($dtd[$grammaire])) {
24
-		return $dtd[$grammaire];
25
-	}
26
-
27
-	if ($avail == 'SYSTEM') {
28
-		$grammaire = find_in_path($grammaire);
29
-	}
30
-
31
-	$file = _DIR_CACHE_XML . preg_replace('/[^\w.]/', '_', $rotlvl) . '.gz';
32
-
33
-	if (lire_fichier($file, $r)) {
34
-		if (!$grammaire) {
35
-			return array();
36
-		}
37
-		if (($avail == 'SYSTEM') and filemtime($file) < filemtime($grammaire)) {
38
-			$r = false;
39
-		}
40
-	}
41
-
42
-	if ($r) {
43
-		$dtc = unserialize($r);
44
-	} else {
45
-		spip_timer('dtd');
46
-		$dtc = new DTC;
47
-		// L'analyseur retourne un booleen de reussite et modifie $dtc.
48
-		// Retourner vide en cas d'echec
49
-		if (!analyser_dtd($grammaire, $avail, $dtc)) {
50
-			$dtc = array();
51
-		} else {
52
-			// tri final pour presenter les suggestions de corrections
53
-			foreach ($dtc->peres as $k => $v) {
54
-				asort($v);
55
-				$dtc->peres[$k] = $v;
56
-			}
57
-
58
-			spip_log("Analyser DTD $avail $grammaire (" . spip_timer('dtd') . ") " . count($dtc->macros) . ' macros, ' . count($dtc->elements) . ' elements, ' . count($dtc->attributs) . " listes d'attributs, " . count($dtc->entites) . " entites");
59
-			#	$r = $dtc->regles; ksort($r);foreach($r as $l => $v) {$t=array_keys($dtc->attributs[$l]);echo "<b>$l</b> '$v' ", count($t), " attributs: ", join (', ',$t);$t=$dtc->peres[$l];echo "<br />",count($t), " peres: ", @join (', ',$t), "<br />\n";}exit;
60
-			ecrire_fichier($file, serialize($dtc), true);
61
-		}
62
-
63
-	}
64
-	$dtd[$grammaire] = $dtc;
65
-
66
-	return $dtc;
21
+    static $dtd = array(); # cache bien utile pour le validateur en boucle
22
+
23
+    if (isset($dtd[$grammaire])) {
24
+        return $dtd[$grammaire];
25
+    }
26
+
27
+    if ($avail == 'SYSTEM') {
28
+        $grammaire = find_in_path($grammaire);
29
+    }
30
+
31
+    $file = _DIR_CACHE_XML . preg_replace('/[^\w.]/', '_', $rotlvl) . '.gz';
32
+
33
+    if (lire_fichier($file, $r)) {
34
+        if (!$grammaire) {
35
+            return array();
36
+        }
37
+        if (($avail == 'SYSTEM') and filemtime($file) < filemtime($grammaire)) {
38
+            $r = false;
39
+        }
40
+    }
41
+
42
+    if ($r) {
43
+        $dtc = unserialize($r);
44
+    } else {
45
+        spip_timer('dtd');
46
+        $dtc = new DTC;
47
+        // L'analyseur retourne un booleen de reussite et modifie $dtc.
48
+        // Retourner vide en cas d'echec
49
+        if (!analyser_dtd($grammaire, $avail, $dtc)) {
50
+            $dtc = array();
51
+        } else {
52
+            // tri final pour presenter les suggestions de corrections
53
+            foreach ($dtc->peres as $k => $v) {
54
+                asort($v);
55
+                $dtc->peres[$k] = $v;
56
+            }
57
+
58
+            spip_log("Analyser DTD $avail $grammaire (" . spip_timer('dtd') . ") " . count($dtc->macros) . ' macros, ' . count($dtc->elements) . ' elements, ' . count($dtc->attributs) . " listes d'attributs, " . count($dtc->entites) . " entites");
59
+            #	$r = $dtc->regles; ksort($r);foreach($r as $l => $v) {$t=array_keys($dtc->attributs[$l]);echo "<b>$l</b> '$v' ", count($t), " attributs: ", join (', ',$t);$t=$dtc->peres[$l];echo "<br />",count($t), " peres: ", @join (', ',$t), "<br />\n";}exit;
60
+            ecrire_fichier($file, serialize($dtc), true);
61
+        }
62
+
63
+    }
64
+    $dtd[$grammaire] = $dtc;
65
+
66
+    return $dtc;
67 67
 }
68 68
 
69 69
 // Compiler une regle de production en une Regexp qu'on appliquera sur la
@@ -76,139 +76,139 @@  discard block
 block discarded – undo
76 76
 
77 77
 // http://code.spip.net/@compilerRegle
78 78
 function compilerRegle($val) {
79
-	$x = str_replace('()', '',
80
-		preg_replace('/\s*,\s*/', '',
81
-			preg_replace('/(\w+)\s*/', '(?:\1 )',
82
-				preg_replace('/\s*\)/', ')',
83
-					preg_replace('/\s*([(+*|?])\s*/', '\1',
84
-						preg_replace('/\s*#\w+\s*[,|]?\s*/', '', $val))))));
85
-
86
-	return $x;
79
+    $x = str_replace('()', '',
80
+        preg_replace('/\s*,\s*/', '',
81
+            preg_replace('/(\w+)\s*/', '(?:\1 )',
82
+                preg_replace('/\s*\)/', ')',
83
+                    preg_replace('/\s*([(+*|?])\s*/', '\1',
84
+                        preg_replace('/\s*#\w+\s*[,|]?\s*/', '', $val))))));
85
+
86
+    return $x;
87 87
 }
88 88
 
89 89
 
90 90
 // http://code.spip.net/@analyser_dtd
91 91
 function analyser_dtd($loc, $avail, &$dtc) {
92
-	// creer le repertoire de cache si ce n'est fait
93
-	// (utile aussi pour le resultat de la compil)
94
-	$file = sous_repertoire(_DIR_CACHE_XML);
95
-	// si DTD locale, ignorer ce repertoire pour le moment
96
-	if ($avail == 'SYSTEM') {
97
-		$file = $loc;
98
-		if (_DIR_RACINE and strncmp($file, _DIR_RACINE, strlen(_DIR_RACINE)) == 0) {
99
-			$file = substr($file, strlen(_DIR_RACINE));
100
-		}
101
-		$file = find_in_path($file);
102
-	} else {
103
-		$file .= preg_replace('/[^\w.]/', '_', $loc);
104
-	}
105
-
106
-	$dtd = '';
107
-	if (@is_readable($file)) {
108
-		lire_fichier($file, $dtd);
109
-	} else {
110
-		if ($avail == 'PUBLIC') {
111
-			include_spip('inc/distant');
112
-			if ($dtd = trim(recuperer_page($loc))) {
113
-				ecrire_fichier($file, $dtd, true);
114
-			}
115
-		}
116
-	}
117
-
118
-	$dtd = ltrim($dtd);
119
-	if (!$dtd) {
120
-		spip_log("DTD '$loc' ($file) inaccessible");
121
-
122
-		return false;
123
-	} else {
124
-		spip_log("analyse de la DTD $loc ");
125
-	}
126
-
127
-	while ($dtd) {
128
-		if ($dtd[0] != '<') {
129
-			$r = analyser_dtd_lexeme($dtd, $dtc, $loc);
130
-		} elseif ($dtd[1] != '!') {
131
-			$r = analyser_dtd_pi($dtd, $dtc, $loc);
132
-		} elseif ($dtd[2] == '[') {
133
-			$r = analyser_dtd_data($dtd, $dtc, $loc);
134
-		} else {
135
-			switch ($dtd[3]) {
136
-				case '%' :
137
-					$r = analyser_dtd_data($dtd, $dtc, $loc);
138
-					break;
139
-				case 'T' :
140
-					$r = analyser_dtd_attlist($dtd, $dtc, $loc);
141
-					break;
142
-				case 'L' :
143
-					$r = analyser_dtd_element($dtd, $dtc, $loc);
144
-					break;
145
-				case 'N' :
146
-					$r = analyser_dtd_entity($dtd, $dtc, $loc);
147
-					break;
148
-				case 'O' :
149
-					$r = analyser_dtd_notation($dtd, $dtc, $loc);
150
-					break;
151
-				case '-' :
152
-					$r = analyser_dtd_comment($dtd, $dtc, $loc);
153
-					break;
154
-				default:
155
-					$r = -1;
156
-			}
157
-		}
158
-		if (!is_string($r)) {
159
-			spip_log("erreur $r dans la DTD  " . substr($dtd, 0, 80) . ".....");
160
-
161
-			return false;
162
-		}
163
-		$dtd = $r;
164
-	}
165
-
166
-	return true;
92
+    // creer le repertoire de cache si ce n'est fait
93
+    // (utile aussi pour le resultat de la compil)
94
+    $file = sous_repertoire(_DIR_CACHE_XML);
95
+    // si DTD locale, ignorer ce repertoire pour le moment
96
+    if ($avail == 'SYSTEM') {
97
+        $file = $loc;
98
+        if (_DIR_RACINE and strncmp($file, _DIR_RACINE, strlen(_DIR_RACINE)) == 0) {
99
+            $file = substr($file, strlen(_DIR_RACINE));
100
+        }
101
+        $file = find_in_path($file);
102
+    } else {
103
+        $file .= preg_replace('/[^\w.]/', '_', $loc);
104
+    }
105
+
106
+    $dtd = '';
107
+    if (@is_readable($file)) {
108
+        lire_fichier($file, $dtd);
109
+    } else {
110
+        if ($avail == 'PUBLIC') {
111
+            include_spip('inc/distant');
112
+            if ($dtd = trim(recuperer_page($loc))) {
113
+                ecrire_fichier($file, $dtd, true);
114
+            }
115
+        }
116
+    }
117
+
118
+    $dtd = ltrim($dtd);
119
+    if (!$dtd) {
120
+        spip_log("DTD '$loc' ($file) inaccessible");
121
+
122
+        return false;
123
+    } else {
124
+        spip_log("analyse de la DTD $loc ");
125
+    }
126
+
127
+    while ($dtd) {
128
+        if ($dtd[0] != '<') {
129
+            $r = analyser_dtd_lexeme($dtd, $dtc, $loc);
130
+        } elseif ($dtd[1] != '!') {
131
+            $r = analyser_dtd_pi($dtd, $dtc, $loc);
132
+        } elseif ($dtd[2] == '[') {
133
+            $r = analyser_dtd_data($dtd, $dtc, $loc);
134
+        } else {
135
+            switch ($dtd[3]) {
136
+                case '%' :
137
+                    $r = analyser_dtd_data($dtd, $dtc, $loc);
138
+                    break;
139
+                case 'T' :
140
+                    $r = analyser_dtd_attlist($dtd, $dtc, $loc);
141
+                    break;
142
+                case 'L' :
143
+                    $r = analyser_dtd_element($dtd, $dtc, $loc);
144
+                    break;
145
+                case 'N' :
146
+                    $r = analyser_dtd_entity($dtd, $dtc, $loc);
147
+                    break;
148
+                case 'O' :
149
+                    $r = analyser_dtd_notation($dtd, $dtc, $loc);
150
+                    break;
151
+                case '-' :
152
+                    $r = analyser_dtd_comment($dtd, $dtc, $loc);
153
+                    break;
154
+                default:
155
+                    $r = -1;
156
+            }
157
+        }
158
+        if (!is_string($r)) {
159
+            spip_log("erreur $r dans la DTD  " . substr($dtd, 0, 80) . ".....");
160
+
161
+            return false;
162
+        }
163
+        $dtd = $r;
164
+    }
165
+
166
+    return true;
167 167
 }
168 168
 
169 169
 // http://code.spip.net/@analyser_dtd_comment
170 170
 function analyser_dtd_comment($dtd, &$dtc, $grammaire) {
171
-	// ejecter les commentaires, surtout quand ils contiennent du code.
172
-	// Option /s car sur plusieurs lignes parfois
171
+    // ejecter les commentaires, surtout quand ils contiennent du code.
172
+    // Option /s car sur plusieurs lignes parfois
173 173
 
174
-	if (!preg_match('/^<!--.*?-->\s*(.*)$/s', $dtd, $m)) {
175
-		return -6;
176
-	}
174
+    if (!preg_match('/^<!--.*?-->\s*(.*)$/s', $dtd, $m)) {
175
+        return -6;
176
+    }
177 177
 
178
-	return $m[1];
178
+    return $m[1];
179 179
 }
180 180
 
181 181
 // http://code.spip.net/@analyser_dtd_pi
182 182
 function analyser_dtd_pi($dtd, &$dtc, $grammaire) {
183
-	if (!preg_match('/^<\?.*?>\s*(.*)$/s', $dtd, $m)) {
184
-		return -10;
185
-	}
183
+    if (!preg_match('/^<\?.*?>\s*(.*)$/s', $dtd, $m)) {
184
+        return -10;
185
+    }
186 186
 
187
-	return $m[1];
187
+    return $m[1];
188 188
 }
189 189
 
190 190
 // http://code.spip.net/@analyser_dtd_lexeme
191 191
 function analyser_dtd_lexeme($dtd, &$dtc, $grammaire) {
192 192
 
193
-	if (!preg_match(_REGEXP_ENTITY_DEF, $dtd, $m)) {
194
-		return -9;
195
-	}
196
-
197
-	list(, $s) = $m;
198
-	$n = $dtc->macros[$s];
199
-
200
-	if (is_array($n)) {
201
-		// en cas d'inclusion, l'espace de nom est le meme
202
-		// mais gaffe aux DTD dont l'URL est relative a l'engloblante
203
-		if (($n[0] == 'PUBLIC')
204
-			and !tester_url_absolue($n[1])
205
-		) {
206
-			$n[1] = substr($grammaire, 0, strrpos($grammaire, '/') + 1) . $n[1];
207
-		}
208
-		analyser_dtd($n[1], $n[0], $dtc);
209
-	}
210
-
211
-	return ltrim(substr($dtd, strlen($m[0])));
193
+    if (!preg_match(_REGEXP_ENTITY_DEF, $dtd, $m)) {
194
+        return -9;
195
+    }
196
+
197
+    list(, $s) = $m;
198
+    $n = $dtc->macros[$s];
199
+
200
+    if (is_array($n)) {
201
+        // en cas d'inclusion, l'espace de nom est le meme
202
+        // mais gaffe aux DTD dont l'URL est relative a l'engloblante
203
+        if (($n[0] == 'PUBLIC')
204
+            and !tester_url_absolue($n[1])
205
+        ) {
206
+            $n[1] = substr($grammaire, 0, strrpos($grammaire, '/') + 1) . $n[1];
207
+        }
208
+        analyser_dtd($n[1], $n[0], $dtc);
209
+    }
210
+
211
+    return ltrim(substr($dtd, strlen($m[0])));
212 212
 }
213 213
 
214 214
 // il faudrait gerer plus proprement les niveaux d'inclusion:
@@ -217,80 +217,80 @@  discard block
 block discarded – undo
217 217
 // http://code.spip.net/@analyser_dtd_data
218 218
 function analyser_dtd_data($dtd, &$dtc, $grammaire) {
219 219
 
220
-	if (!preg_match(_REGEXP_INCLUDE_USE, $dtd, $m)) {
221
-		return -11;
222
-	}
223
-	if (!preg_match('/^((\s*<!(\[\s*%\s*[^;]*;\s*\[([^]<]*<[^>]*>)*[^]<]*\]\]>)|([^]>]*>))*[^]<]*)\]\]>\s*/s', $m[2],
224
-		$r)
225
-	) {
226
-		return -12;
227
-	}
228
-
229
-	if ($dtc->macros[$m[1]] == 'INCLUDE') {
230
-		$retour = $r[1] . substr($m[2], strlen($r[0]));
231
-	} else {
232
-		$retour = substr($m[2], strlen($r[0]));
233
-	}
234
-
235
-	return $retour;
220
+    if (!preg_match(_REGEXP_INCLUDE_USE, $dtd, $m)) {
221
+        return -11;
222
+    }
223
+    if (!preg_match('/^((\s*<!(\[\s*%\s*[^;]*;\s*\[([^]<]*<[^>]*>)*[^]<]*\]\]>)|([^]>]*>))*[^]<]*)\]\]>\s*/s', $m[2],
224
+        $r)
225
+    ) {
226
+        return -12;
227
+    }
228
+
229
+    if ($dtc->macros[$m[1]] == 'INCLUDE') {
230
+        $retour = $r[1] . substr($m[2], strlen($r[0]));
231
+    } else {
232
+        $retour = substr($m[2], strlen($r[0]));
233
+    }
234
+
235
+    return $retour;
236 236
 }
237 237
 
238 238
 // http://code.spip.net/@analyser_dtd_notation
239 239
 function analyser_dtd_notation($dtd, &$dtc, $grammaire) {
240
-	if (!preg_match('/^<!NOTATION.*?>\s*(.*)$/s', $dtd, $m)) {
241
-		return -8;
242
-	}
243
-	spip_log("analyser_dtd_notation a ecrire");
240
+    if (!preg_match('/^<!NOTATION.*?>\s*(.*)$/s', $dtd, $m)) {
241
+        return -8;
242
+    }
243
+    spip_log("analyser_dtd_notation a ecrire");
244 244
 
245
-	return $m[1];
245
+    return $m[1];
246 246
 }
247 247
 
248 248
 // http://code.spip.net/@analyser_dtd_entity
249 249
 function analyser_dtd_entity($dtd, &$dtc, $grammaire) {
250
-	if (!preg_match(_REGEXP_ENTITY_DECL, $dtd, $m)) {
251
-		return -2;
252
-	}
253
-
254
-	list($t, $term, $nom, $type, $k1, $k2, $k3, $k4, $k5, $k6, $c, $q, $alt, $dtd) = $m;
255
-
256
-	if (isset($dtc->macros[$nom]) and $dtc->macros[$nom]) {
257
-		return $dtd;
258
-	}
259
-	if (isset($dtc->entites[$nom])) {
260
-		spip_log("redefinition de l'entite $nom");
261
-	}
262
-	if ($k6) {
263
-		return $k6 . $dtd;
264
-	} // cas du synonyme complet
265
-	$val = expanserEntite(($k2 ? $k3 : ($k4 ? $k5 : $k6)), $dtc->macros);
266
-
267
-	// cas particulier double evaluation: 'PUBLIC "..." "...."' 
268
-	if (preg_match('/(PUBLIC|SYSTEM)\s+"([^"]*)"\s*("([^"]*)")?\s*$/s', $val, $r)) {
269
-		list($t, $type, $val, $q, $alt) = $r;
270
-	}
271
-
272
-	if (!$term) {
273
-		$dtc->entites[$nom] = $val;
274
-	} elseif (!$type) {
275
-		$dtc->macros[$nom] = $val;
276
-	} else {
277
-		if (($type == 'SYSTEM') and !$alt) {
278
-			$alt = $val;
279
-		}
280
-		if (!$alt) {
281
-			$dtc->macros[$nom] = $val;
282
-		} else {
283
-			if (($type == 'PUBLIC')
284
-				and (strpos($alt, '/') === false)
285
-			) {
286
-				$alt = preg_replace(',/[^/]+$,', '/', $grammaire)
287
-					. $alt;
288
-			}
289
-			$dtc->macros[$nom] = array($type, $alt);
290
-		}
291
-	}
292
-
293
-	return $dtd;
250
+    if (!preg_match(_REGEXP_ENTITY_DECL, $dtd, $m)) {
251
+        return -2;
252
+    }
253
+
254
+    list($t, $term, $nom, $type, $k1, $k2, $k3, $k4, $k5, $k6, $c, $q, $alt, $dtd) = $m;
255
+
256
+    if (isset($dtc->macros[$nom]) and $dtc->macros[$nom]) {
257
+        return $dtd;
258
+    }
259
+    if (isset($dtc->entites[$nom])) {
260
+        spip_log("redefinition de l'entite $nom");
261
+    }
262
+    if ($k6) {
263
+        return $k6 . $dtd;
264
+    } // cas du synonyme complet
265
+    $val = expanserEntite(($k2 ? $k3 : ($k4 ? $k5 : $k6)), $dtc->macros);
266
+
267
+    // cas particulier double evaluation: 'PUBLIC "..." "...."' 
268
+    if (preg_match('/(PUBLIC|SYSTEM)\s+"([^"]*)"\s*("([^"]*)")?\s*$/s', $val, $r)) {
269
+        list($t, $type, $val, $q, $alt) = $r;
270
+    }
271
+
272
+    if (!$term) {
273
+        $dtc->entites[$nom] = $val;
274
+    } elseif (!$type) {
275
+        $dtc->macros[$nom] = $val;
276
+    } else {
277
+        if (($type == 'SYSTEM') and !$alt) {
278
+            $alt = $val;
279
+        }
280
+        if (!$alt) {
281
+            $dtc->macros[$nom] = $val;
282
+        } else {
283
+            if (($type == 'PUBLIC')
284
+                and (strpos($alt, '/') === false)
285
+            ) {
286
+                $alt = preg_replace(',/[^/]+$,', '/', $grammaire)
287
+                    . $alt;
288
+            }
289
+            $dtc->macros[$nom] = array($type, $alt);
290
+        }
291
+    }
292
+
293
+    return $dtd;
294 294
 }
295 295
 
296 296
 // Dresser le tableau des filles potentielles de l'element
@@ -304,76 +304,76 @@  discard block
 block discarded – undo
304 304
 
305 305
 // http://code.spip.net/@analyser_dtd_element
306 306
 function analyser_dtd_element($dtd, &$dtc, $grammaire) {
307
-	if (!preg_match('/^<!ELEMENT\s+([^>\s]+)([^>]*)>\s*(.*)$/s', $dtd, $m)) {
308
-		return -3;
309
-	}
310
-
311
-	list(, $nom, $contenu, $dtd) = $m;
312
-	$nom = expanserEntite($nom, $dtc->macros);
313
-
314
-	if (isset($dtc->elements[$nom])) {
315
-		spip_log("redefinition de l'element $nom dans la DTD");
316
-
317
-		return -4;
318
-	}
319
-	$filles = array();
320
-	$contenu = expanserEntite($contenu, $dtc->macros);
321
-	$val = $contenu ? compilerRegle($contenu) : '(?:EMPTY )';
322
-	if ($val == '(?:EMPTY )') {
323
-		$dtc->regles[$nom] = 'EMPTY';
324
-	} elseif ($val == '(?:ANY )') {
325
-		$dtc->regles[$nom] = 'ANY';
326
-	} else {
327
-		$last = substr($val, -1);
328
-		if (preg_match('/ \w/', $val)
329
-			or (!empty($last) and strpos('*+?', $last) === false)
330
-		) {
331
-			$dtc->regles[$nom] = "/^$val$/";
332
-		} else {
333
-			$dtc->regles[$nom] = $last;
334
-		}
335
-		$filles = array_values(preg_split('/\W+/', $val, -1, PREG_SPLIT_NO_EMPTY));
336
-
337
-		foreach ($filles as $k) {
338
-			if (!isset($dtc->peres[$k])) {
339
-				$dtc->peres[$k] = array();
340
-			}
341
-			if (!in_array($nom, $dtc->peres[$k])) {
342
-				$dtc->peres[$k][] = $nom;
343
-			}
344
-		}
345
-	}
346
-	$dtc->pcdata[$nom] = (strpos($contenu, '#PCDATA') === false);
347
-	$dtc->elements[$nom] = $filles;
348
-
349
-	return $dtd;
307
+    if (!preg_match('/^<!ELEMENT\s+([^>\s]+)([^>]*)>\s*(.*)$/s', $dtd, $m)) {
308
+        return -3;
309
+    }
310
+
311
+    list(, $nom, $contenu, $dtd) = $m;
312
+    $nom = expanserEntite($nom, $dtc->macros);
313
+
314
+    if (isset($dtc->elements[$nom])) {
315
+        spip_log("redefinition de l'element $nom dans la DTD");
316
+
317
+        return -4;
318
+    }
319
+    $filles = array();
320
+    $contenu = expanserEntite($contenu, $dtc->macros);
321
+    $val = $contenu ? compilerRegle($contenu) : '(?:EMPTY )';
322
+    if ($val == '(?:EMPTY )') {
323
+        $dtc->regles[$nom] = 'EMPTY';
324
+    } elseif ($val == '(?:ANY )') {
325
+        $dtc->regles[$nom] = 'ANY';
326
+    } else {
327
+        $last = substr($val, -1);
328
+        if (preg_match('/ \w/', $val)
329
+            or (!empty($last) and strpos('*+?', $last) === false)
330
+        ) {
331
+            $dtc->regles[$nom] = "/^$val$/";
332
+        } else {
333
+            $dtc->regles[$nom] = $last;
334
+        }
335
+        $filles = array_values(preg_split('/\W+/', $val, -1, PREG_SPLIT_NO_EMPTY));
336
+
337
+        foreach ($filles as $k) {
338
+            if (!isset($dtc->peres[$k])) {
339
+                $dtc->peres[$k] = array();
340
+            }
341
+            if (!in_array($nom, $dtc->peres[$k])) {
342
+                $dtc->peres[$k][] = $nom;
343
+            }
344
+        }
345
+    }
346
+    $dtc->pcdata[$nom] = (strpos($contenu, '#PCDATA') === false);
347
+    $dtc->elements[$nom] = $filles;
348
+
349
+    return $dtd;
350 350
 }
351 351
 
352 352
 
353 353
 // http://code.spip.net/@analyser_dtd_attlist
354 354
 function analyser_dtd_attlist($dtd, &$dtc, $grammaire) {
355
-	if (!preg_match('/^<!ATTLIST\s+(\S+)\s+([^>]*)>\s*(.*)/s', $dtd, $m)) {
356
-		return -5;
357
-	}
358
-
359
-	list(, $nom, $val, $dtd) = $m;
360
-	$nom = expanserEntite($nom, $dtc->macros);
361
-	$val = expanserEntite($val, $dtc->macros);
362
-	if (!isset($dtc->attributs[$nom])) {
363
-		$dtc->attributs[$nom] = array();
364
-	}
365
-
366
-	if (preg_match_all("/\s*(\S+)\s+(([(][^)]*[)])|(\S+))\s+([^\s']*)(\s*'[^']*')?/", $val, $r2, PREG_SET_ORDER)) {
367
-		foreach ($r2 as $m2) {
368
-			$v = preg_match('/^\w+$/', $m2[2]) ? $m2[2]
369
-				: ('/^' . preg_replace('/\s+/', '', $m2[2]) . '$/');
370
-			$m21 = expanserEntite($m2[1], $dtc->macros);
371
-			$m25 = expanserEntite($m2[5], $dtc->macros);
372
-			$dtc->attributs[$nom][$m21] = array($v, $m25);
373
-		}
374
-	}
375
-
376
-	return $dtd;
355
+    if (!preg_match('/^<!ATTLIST\s+(\S+)\s+([^>]*)>\s*(.*)/s', $dtd, $m)) {
356
+        return -5;
357
+    }
358
+
359
+    list(, $nom, $val, $dtd) = $m;
360
+    $nom = expanserEntite($nom, $dtc->macros);
361
+    $val = expanserEntite($val, $dtc->macros);
362
+    if (!isset($dtc->attributs[$nom])) {
363
+        $dtc->attributs[$nom] = array();
364
+    }
365
+
366
+    if (preg_match_all("/\s*(\S+)\s+(([(][^)]*[)])|(\S+))\s+([^\s']*)(\s*'[^']*')?/", $val, $r2, PREG_SET_ORDER)) {
367
+        foreach ($r2 as $m2) {
368
+            $v = preg_match('/^\w+$/', $m2[2]) ? $m2[2]
369
+                : ('/^' . preg_replace('/\s+/', '', $m2[2]) . '$/');
370
+            $m21 = expanserEntite($m2[1], $dtc->macros);
371
+            $m25 = expanserEntite($m2[5], $dtc->macros);
372
+            $dtc->attributs[$nom][$m21] = array($v, $m25);
373
+        }
374
+    }
375
+
376
+    return $dtd;
377 377
 }
378 378
 
379 379
 
@@ -389,26 +389,26 @@  discard block
 block discarded – undo
389 389
  * @return string|array
390 390
  **/
391 391
 function expanserEntite($val, $macros = array()) {
392
-	static $vu = array();
393
-	if (!is_string($val)) {
394
-		return $vu;
395
-	}
396
-
397
-	if (preg_match_all(_REGEXP_ENTITY_USE, $val, $r, PREG_SET_ORDER)) {
398
-		foreach ($r as $m) {
399
-			$ent = $m[1];
400
-			// il peut valoir ""
401
-			if (!isset($macros[$ent])) {
402
-				spip_log("Entite $ent inconnu");
403
-			} else {
404
-				if (!isset($vu[$ent])) {
405
-					$vu[$ent] = 0;
406
-				}
407
-				++$vu[$ent];
408
-				$val = str_replace($m[0], $macros[$ent], $val);
409
-			}
410
-		}
411
-	}
412
-
413
-	return trim(preg_replace('/\s+/', ' ', $val));
392
+    static $vu = array();
393
+    if (!is_string($val)) {
394
+        return $vu;
395
+    }
396
+
397
+    if (preg_match_all(_REGEXP_ENTITY_USE, $val, $r, PREG_SET_ORDER)) {
398
+        foreach ($r as $m) {
399
+            $ent = $m[1];
400
+            // il peut valoir ""
401
+            if (!isset($macros[$ent])) {
402
+                spip_log("Entite $ent inconnu");
403
+            } else {
404
+                if (!isset($vu[$ent])) {
405
+                    $vu[$ent] = 0;
406
+                }
407
+                ++$vu[$ent];
408
+                $val = str_replace($m[0], $macros[$ent], $val);
409
+            }
410
+        }
411
+    }
412
+
413
+    return trim(preg_replace('/\s+/', ' ', $val));
414 414
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 		$grammaire = find_in_path($grammaire);
29 29
 	}
30 30
 
31
-	$file = _DIR_CACHE_XML . preg_replace('/[^\w.]/', '_', $rotlvl) . '.gz';
31
+	$file = _DIR_CACHE_XML.preg_replace('/[^\w.]/', '_', $rotlvl).'.gz';
32 32
 
33 33
 	if (lire_fichier($file, $r)) {
34 34
 		if (!$grammaire) {
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 				$dtc->peres[$k] = $v;
56 56
 			}
57 57
 
58
-			spip_log("Analyser DTD $avail $grammaire (" . spip_timer('dtd') . ") " . count($dtc->macros) . ' macros, ' . count($dtc->elements) . ' elements, ' . count($dtc->attributs) . " listes d'attributs, " . count($dtc->entites) . " entites");
58
+			spip_log("Analyser DTD $avail $grammaire (".spip_timer('dtd').") ".count($dtc->macros).' macros, '.count($dtc->elements).' elements, '.count($dtc->attributs)." listes d'attributs, ".count($dtc->entites)." entites");
59 59
 			#	$r = $dtc->regles; ksort($r);foreach($r as $l => $v) {$t=array_keys($dtc->attributs[$l]);echo "<b>$l</b> '$v' ", count($t), " attributs: ", join (', ',$t);$t=$dtc->peres[$l];echo "<br />",count($t), " peres: ", @join (', ',$t), "<br />\n";}exit;
60 60
 			ecrire_fichier($file, serialize($dtc), true);
61 61
 		}
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 			}
157 157
 		}
158 158
 		if (!is_string($r)) {
159
-			spip_log("erreur $r dans la DTD  " . substr($dtd, 0, 80) . ".....");
159
+			spip_log("erreur $r dans la DTD  ".substr($dtd, 0, 80).".....");
160 160
 
161 161
 			return false;
162 162
 		}
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 		if (($n[0] == 'PUBLIC')
204 204
 			and !tester_url_absolue($n[1])
205 205
 		) {
206
-			$n[1] = substr($grammaire, 0, strrpos($grammaire, '/') + 1) . $n[1];
206
+			$n[1] = substr($grammaire, 0, strrpos($grammaire, '/') + 1).$n[1];
207 207
 		}
208 208
 		analyser_dtd($n[1], $n[0], $dtc);
209 209
 	}
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 	}
228 228
 
229 229
 	if ($dtc->macros[$m[1]] == 'INCLUDE') {
230
-		$retour = $r[1] . substr($m[2], strlen($r[0]));
230
+		$retour = $r[1].substr($m[2], strlen($r[0]));
231 231
 	} else {
232 232
 		$retour = substr($m[2], strlen($r[0]));
233 233
 	}
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 		spip_log("redefinition de l'entite $nom");
261 261
 	}
262 262
 	if ($k6) {
263
-		return $k6 . $dtd;
263
+		return $k6.$dtd;
264 264
 	} // cas du synonyme complet
265 265
 	$val = expanserEntite(($k2 ? $k3 : ($k4 ? $k5 : $k6)), $dtc->macros);
266 266
 
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 	if (preg_match_all("/\s*(\S+)\s+(([(][^)]*[)])|(\S+))\s+([^\s']*)(\s*'[^']*')?/", $val, $r2, PREG_SET_ORDER)) {
367 367
 		foreach ($r2 as $m2) {
368 368
 			$v = preg_match('/^\w+$/', $m2[2]) ? $m2[2]
369
-				: ('/^' . preg_replace('/\s+/', '', $m2[2]) . '$/');
369
+				: ('/^'.preg_replace('/\s+/', '', $m2[2]).'$/');
370 370
 			$m21 = expanserEntite($m2[1], $dtc->macros);
371 371
 			$m25 = expanserEntite($m2[5], $dtc->macros);
372 372
 			$dtc->attributs[$nom][$m21] = array($v, $m25);
Please login to merge, or discard this patch.
ecrire/xml/sax.php 3 patches
Doc Comments   +9 added lines patch added patch discarded remove patch
@@ -102,6 +102,9 @@  discard block
 block discarded – undo
102 102
 		: xml_entites_html($data);
103 103
 }
104 104
 
105
+/**
106
+ * @param IndenteurXML $phraseur
107
+ */
105 108
 function xml_piElement($phraseur, $target, $data) {
106 109
 	$depth = $phraseur->depth;
107 110
 
@@ -118,6 +121,9 @@  discard block
 block discarded – undo
118 121
 
119 122
 
120 123
 // http://code.spip.net/@xml_defautElement
124
+/**
125
+ * @param IndenteurXML $phraseur
126
+ */
121 127
 function xml_defaultElement($phraseur, $data) {
122 128
 	$depth = $phraseur->depth;
123 129
 
@@ -149,6 +155,9 @@  discard block
 block discarded – undo
149 155
 }
150 156
 
151 157
 // http://code.spip.net/@coordonnees_erreur
158
+/**
159
+ * @param string $msg
160
+ */
152 161
 function coordonnees_erreur($phraseur, $msg) {
153 162
 	$entete_length = substr_count($phraseur->entete, "\n");
154 163
 	$phraseur->err[] = array(
Please login to merge, or discard this patch.
Indentation   +246 added lines, -246 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('inc/charsets');
@@ -24,218 +24,218 @@  discard block
 block discarded – undo
24 24
  * @return string
25 25
  */
26 26
 function xml_entites_html($texte) {
27
-	if (!is_string($texte) or !$texte
28
-		or strpbrk($texte, "&\"'<>") == false
29
-	) {
30
-		return $texte;
31
-	}
32
-
33
-	if (!function_exists('spip_htmlspecialchars')) {
34
-		include_spip("inc/filtres_mini");
35
-	}
36
-	$texte = spip_htmlspecialchars($texte, ENT_QUOTES);
37
-
38
-	return $texte;
27
+    if (!is_string($texte) or !$texte
28
+        or strpbrk($texte, "&\"'<>") == false
29
+    ) {
30
+        return $texte;
31
+    }
32
+
33
+    if (!function_exists('spip_htmlspecialchars')) {
34
+        include_spip("inc/filtres_mini");
35
+    }
36
+    $texte = spip_htmlspecialchars($texte, ENT_QUOTES);
37
+
38
+    return $texte;
39 39
 }
40 40
 
41 41
 // http://code.spip.net/@xml_debutElement
42 42
 function xml_debutElement($phraseur, $name, $attrs) {
43
-	$depth = $phraseur->depth;
44
-
45
-	$t = isset($phraseur->ouvrant[$depth]) ? $phraseur->ouvrant[$depth] : ' ';
46
-	// espace initial signifie: deja integree au resultat
47
-	if ($t[0] != ' ') {
48
-		$phraseur->res .= '<' . $t . '>';
49
-		$phraseur->ouvrant[$depth] = ' ' . $t;
50
-	}
51
-	$t = $phraseur->contenu[$depth];
52
-	// n'indenter que s'il y a un separateur avant
53
-	$phraseur->res .= preg_replace("/[\n\t ]+$/", "\n$depth", $t);
54
-	$phraseur->contenu[$depth] = "";
55
-	$att = '';
56
-	$sep = ' ';
57
-	foreach ($attrs as $k => $v) {
58
-		$delim = strpos($v, "'") === false ? "'" : '"';
59
-		$val = xml_entites_html($v);
60
-		$att .= $sep . $k . "=" . $delim
61
-			. ($delim !== '"' ? str_replace('&quot;', '"', $val) : $val)
62
-			. $delim;
63
-		$sep = "\n $depth";
64
-	}
65
-	$phraseur->depth .= '  ';
66
-	$phraseur->contenu[$phraseur->depth] = "";
67
-	$phraseur->ouvrant[$phraseur->depth] = $name . $att;
68
-	$phraseur->reperes[$phraseur->depth] = xml_get_current_line_number($phraseur->sax);
43
+    $depth = $phraseur->depth;
44
+
45
+    $t = isset($phraseur->ouvrant[$depth]) ? $phraseur->ouvrant[$depth] : ' ';
46
+    // espace initial signifie: deja integree au resultat
47
+    if ($t[0] != ' ') {
48
+        $phraseur->res .= '<' . $t . '>';
49
+        $phraseur->ouvrant[$depth] = ' ' . $t;
50
+    }
51
+    $t = $phraseur->contenu[$depth];
52
+    // n'indenter que s'il y a un separateur avant
53
+    $phraseur->res .= preg_replace("/[\n\t ]+$/", "\n$depth", $t);
54
+    $phraseur->contenu[$depth] = "";
55
+    $att = '';
56
+    $sep = ' ';
57
+    foreach ($attrs as $k => $v) {
58
+        $delim = strpos($v, "'") === false ? "'" : '"';
59
+        $val = xml_entites_html($v);
60
+        $att .= $sep . $k . "=" . $delim
61
+            . ($delim !== '"' ? str_replace('&quot;', '"', $val) : $val)
62
+            . $delim;
63
+        $sep = "\n $depth";
64
+    }
65
+    $phraseur->depth .= '  ';
66
+    $phraseur->contenu[$phraseur->depth] = "";
67
+    $phraseur->ouvrant[$phraseur->depth] = $name . $att;
68
+    $phraseur->reperes[$phraseur->depth] = xml_get_current_line_number($phraseur->sax);
69 69
 }
70 70
 
71 71
 // http://code.spip.net/@xml_finElement
72 72
 function xml_finElement($phraseur, $name, $fusion_bal = false) {
73
-	$ouv = $phraseur->ouvrant[$phraseur->depth];
74
-
75
-	if ($ouv[0] != ' ') {
76
-		$phraseur->ouvrant[$phraseur->depth] = ' ' . $ouv;
77
-	} else {
78
-		$ouv = "";
79
-	}
80
-	$t = $phraseur->contenu[$phraseur->depth];
81
-	$phraseur->depth = substr($phraseur->depth, 2);
82
-	$t = preg_replace("/[\n\t ]+$/", "\n" . $phraseur->depth, $t);
83
-
84
-	// fusion <balise></balise> en <balise />.
85
-	// ATTENTION,  certains clients http croient que fusion ==> pas d'atttributs
86
-	// en particulier pour les balises Script et A.
87
-	// en presence d'attributs ne le faire que si la DTD est dispo et d'accord
88
-	// (param fusion_bal)
89
-
90
-	if ($t || (($ouv != $name) and !$fusion_bal)) {
91
-		$phraseur->res .= ($ouv ? ('<' . $ouv . '>') : '') . $t . "</" . $name . ">";
92
-	} else {
93
-		$phraseur->res .= ($ouv ? ('<' . $ouv . ' />') : ("</" . $name . ">"));
94
-	}
73
+    $ouv = $phraseur->ouvrant[$phraseur->depth];
74
+
75
+    if ($ouv[0] != ' ') {
76
+        $phraseur->ouvrant[$phraseur->depth] = ' ' . $ouv;
77
+    } else {
78
+        $ouv = "";
79
+    }
80
+    $t = $phraseur->contenu[$phraseur->depth];
81
+    $phraseur->depth = substr($phraseur->depth, 2);
82
+    $t = preg_replace("/[\n\t ]+$/", "\n" . $phraseur->depth, $t);
83
+
84
+    // fusion <balise></balise> en <balise />.
85
+    // ATTENTION,  certains clients http croient que fusion ==> pas d'atttributs
86
+    // en particulier pour les balises Script et A.
87
+    // en presence d'attributs ne le faire que si la DTD est dispo et d'accord
88
+    // (param fusion_bal)
89
+
90
+    if ($t || (($ouv != $name) and !$fusion_bal)) {
91
+        $phraseur->res .= ($ouv ? ('<' . $ouv . '>') : '') . $t . "</" . $name . ">";
92
+    } else {
93
+        $phraseur->res .= ($ouv ? ('<' . $ouv . ' />') : ("</" . $name . ">"));
94
+    }
95 95
 }
96 96
 
97 97
 // http://code.spip.net/@xml_textElement
98 98
 function xml_textElement($phraseur, $data) {
99
-	$depth = $phraseur->depth;
100
-	$phraseur->contenu[$depth] .= preg_match('/^script/', $phraseur->ouvrant[$depth])
101
-		? $data
102
-		: xml_entites_html($data);
99
+    $depth = $phraseur->depth;
100
+    $phraseur->contenu[$depth] .= preg_match('/^script/', $phraseur->ouvrant[$depth])
101
+        ? $data
102
+        : xml_entites_html($data);
103 103
 }
104 104
 
105 105
 function xml_piElement($phraseur, $target, $data) {
106
-	$depth = $phraseur->depth;
107
-
108
-	if (strtolower($target) != "php") {
109
-		$phraseur->contenu[$depth] .= $data;
110
-	} else {
111
-		ob_start();
112
-		eval($data);
113
-		$data = ob_get_contents();
114
-		ob_end_clean();
115
-		$phraseur->contenu[$depth] .= $data;
116
-	}
106
+    $depth = $phraseur->depth;
107
+
108
+    if (strtolower($target) != "php") {
109
+        $phraseur->contenu[$depth] .= $data;
110
+    } else {
111
+        ob_start();
112
+        eval($data);
113
+        $data = ob_get_contents();
114
+        ob_end_clean();
115
+        $phraseur->contenu[$depth] .= $data;
116
+    }
117 117
 }
118 118
 
119 119
 
120 120
 // http://code.spip.net/@xml_defautElement
121 121
 function xml_defaultElement($phraseur, $data) {
122
-	$depth = $phraseur->depth;
122
+    $depth = $phraseur->depth;
123 123
 
124
-	if (!isset($phraseur->contenu[$depth])) {
125
-		$phraseur->contenu[$depth] = '';
126
-	}
127
-	$phraseur->contenu[$depth] .= $data;
124
+    if (!isset($phraseur->contenu[$depth])) {
125
+        $phraseur->contenu[$depth] = '';
126
+    }
127
+    $phraseur->contenu[$depth] .= $data;
128 128
 }
129 129
 
130 130
 // http://code.spip.net/@xml_parsestring
131 131
 function xml_parsestring($phraseur, $data) {
132
-	$phraseur->contenu[$phraseur->depth] = '';
133
-
134
-	if (!xml_parse($phraseur->sax, $data, true)) {
135
-		coordonnees_erreur($phraseur,
136
-			xml_error_string(xml_get_error_code($phraseur->sax))
137
-			. "<br />\n" .
138
-			(!$phraseur->depth ? '' :
139
-				('(' .
140
-					_T('erreur_balise_non_fermee') .
141
-					" <tt>" .
142
-					$phraseur->ouvrant[$phraseur->depth] .
143
-					"</tt> " .
144
-					_T('ligne') .
145
-					" " .
146
-					$phraseur->reperes[$phraseur->depth] .
147
-					") <br />\n")));
148
-	}
132
+    $phraseur->contenu[$phraseur->depth] = '';
133
+
134
+    if (!xml_parse($phraseur->sax, $data, true)) {
135
+        coordonnees_erreur($phraseur,
136
+            xml_error_string(xml_get_error_code($phraseur->sax))
137
+            . "<br />\n" .
138
+            (!$phraseur->depth ? '' :
139
+                ('(' .
140
+                    _T('erreur_balise_non_fermee') .
141
+                    " <tt>" .
142
+                    $phraseur->ouvrant[$phraseur->depth] .
143
+                    "</tt> " .
144
+                    _T('ligne') .
145
+                    " " .
146
+                    $phraseur->reperes[$phraseur->depth] .
147
+                    ") <br />\n")));
148
+    }
149 149
 }
150 150
 
151 151
 // http://code.spip.net/@coordonnees_erreur
152 152
 function coordonnees_erreur($phraseur, $msg) {
153
-	$entete_length = substr_count($phraseur->entete, "\n");
154
-	$phraseur->err[] = array(
155
-		$msg,
156
-		xml_get_current_line_number($phraseur->sax) + $entete_length,
157
-		xml_get_current_column_number($phraseur->sax)
158
-	);
153
+    $entete_length = substr_count($phraseur->entete, "\n");
154
+    $phraseur->err[] = array(
155
+        $msg,
156
+        xml_get_current_line_number($phraseur->sax) + $entete_length,
157
+        xml_get_current_column_number($phraseur->sax)
158
+    );
159 159
 }
160 160
 
161 161
 // http://code.spip.net/@xml_sax_dist
162 162
 function xml_sax_dist($page, $apply = false, $phraseur = null, $doctype = '', $charset = null) {
163
-	if (is_null($charset)) {
164
-		$charset = $GLOBALS['meta']['charset'];
165
-	}
166
-	if ($apply) {
167
-		ob_start();
168
-		if (is_array($apply)) {
169
-			$r = call_user_func_array($page, $apply);
170
-		} else {
171
-			$r = $page();
172
-		}
173
-		$page = ob_get_contents();
174
-		ob_end_clean();
175
-		// fonction sans aucun "echo", ca doit etre le resultat
176
-		if (!$page) {
177
-			$page = $r;
178
-		}
179
-	}
180
-
181
-	if (!$page) {
182
-		return '';
183
-	}
184
-	// charger la DTD et transcoder les entites,
185
-	// et escamoter le doctype que sax mange en php5 mais pas en  php4
186
-	if (!$doctype) {
187
-		if (!$r = analyser_doctype($page)) {
188
-			$page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE
189
-				. preg_replace(_REGEXP_DOCTYPE, '', $page);
190
-			$r = analyser_doctype($page);
191
-		}
192
-		list($entete, $avail, $grammaire, $rotlvl) = array_pad($r, 4, null);
193
-		$page = substr($page, strlen($entete));
194
-	} else {
195
-		$avail = 'SYSTEM';
196
-		$grammaire = $doctype;
197
-		$rotlvl = basename($grammaire);
198
-	}
199
-
200
-	include_spip('xml/analyser_dtd');
201
-	$dtc = charger_dtd($grammaire, $avail, $rotlvl);
202
-	$page = sax_bug($page, $dtc, $charset);
203
-
204
-	// compatibilite Tidy espace public
205
-	if (!$phraseur) {
206
-		$indenter_xml = charger_fonction('indenter', 'xml');
207
-
208
-		return $indenter_xml($page, $apply);
209
-	}
210
-
211
-	$xml_parser = xml_parser_create($charset);
212
-
213
-	xml_set_element_handler($xml_parser,
214
-		array($phraseur, "debutElement"),
215
-		array($phraseur, "finElement"));
216
-
217
-	xml_set_character_data_handler($xml_parser,
218
-		array($phraseur, "textElement"));
219
-
220
-	xml_set_processing_instruction_handler($xml_parser,
221
-		array($phraseur, 'piElement'));
222
-
223
-	xml_set_default_handler($xml_parser,
224
-		array($phraseur, "defaultElement"));
225
-
226
-	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
227
-
228
-	$phraseur->sax = $xml_parser;
229
-	if (isset($entete)) {
230
-		$phraseur->entete = $entete;
231
-	}
232
-	$phraseur->page = $page;
233
-	$phraseur->dtc = $dtc;
234
-	$phraseur->phraserTout($xml_parser, $page);
235
-	xml_parser_free($xml_parser);
236
-	$phraseur->sax = '';
237
-
238
-	return $phraseur;
163
+    if (is_null($charset)) {
164
+        $charset = $GLOBALS['meta']['charset'];
165
+    }
166
+    if ($apply) {
167
+        ob_start();
168
+        if (is_array($apply)) {
169
+            $r = call_user_func_array($page, $apply);
170
+        } else {
171
+            $r = $page();
172
+        }
173
+        $page = ob_get_contents();
174
+        ob_end_clean();
175
+        // fonction sans aucun "echo", ca doit etre le resultat
176
+        if (!$page) {
177
+            $page = $r;
178
+        }
179
+    }
180
+
181
+    if (!$page) {
182
+        return '';
183
+    }
184
+    // charger la DTD et transcoder les entites,
185
+    // et escamoter le doctype que sax mange en php5 mais pas en  php4
186
+    if (!$doctype) {
187
+        if (!$r = analyser_doctype($page)) {
188
+            $page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE
189
+                . preg_replace(_REGEXP_DOCTYPE, '', $page);
190
+            $r = analyser_doctype($page);
191
+        }
192
+        list($entete, $avail, $grammaire, $rotlvl) = array_pad($r, 4, null);
193
+        $page = substr($page, strlen($entete));
194
+    } else {
195
+        $avail = 'SYSTEM';
196
+        $grammaire = $doctype;
197
+        $rotlvl = basename($grammaire);
198
+    }
199
+
200
+    include_spip('xml/analyser_dtd');
201
+    $dtc = charger_dtd($grammaire, $avail, $rotlvl);
202
+    $page = sax_bug($page, $dtc, $charset);
203
+
204
+    // compatibilite Tidy espace public
205
+    if (!$phraseur) {
206
+        $indenter_xml = charger_fonction('indenter', 'xml');
207
+
208
+        return $indenter_xml($page, $apply);
209
+    }
210
+
211
+    $xml_parser = xml_parser_create($charset);
212
+
213
+    xml_set_element_handler($xml_parser,
214
+        array($phraseur, "debutElement"),
215
+        array($phraseur, "finElement"));
216
+
217
+    xml_set_character_data_handler($xml_parser,
218
+        array($phraseur, "textElement"));
219
+
220
+    xml_set_processing_instruction_handler($xml_parser,
221
+        array($phraseur, 'piElement'));
222
+
223
+    xml_set_default_handler($xml_parser,
224
+        array($phraseur, "defaultElement"));
225
+
226
+    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
227
+
228
+    $phraseur->sax = $xml_parser;
229
+    if (isset($entete)) {
230
+        $phraseur->entete = $entete;
231
+    }
232
+    $phraseur->page = $page;
233
+    $phraseur->dtc = $dtc;
234
+    $phraseur->phraserTout($xml_parser, $page);
235
+    xml_parser_free($xml_parser);
236
+    $phraseur->sax = '';
237
+
238
+    return $phraseur;
239 239
 }
240 240
 
241 241
 // SAX ne dit pas si une Entite est dans un attribut ou non.
@@ -247,24 +247,24 @@  discard block
 block discarded – undo
247 247
 
248 248
 // http://code.spip.net/@sax_bug
249 249
 function sax_bug($data, $dtc, $charset = null) {
250
-	if (is_null($charset)) {
251
-		$charset = $GLOBALS['meta']['charset'];
252
-	}
253
-
254
-	if ($dtc) {
255
-		$trans = array();
256
-
257
-		foreach ($dtc->entites as $k => $v) {
258
-			if (!strpos(" amp lt gt quot ", $k)) {
259
-				$trans["&$k;"] = $v;
260
-			}
261
-		}
262
-		$data = strtr($data, $trans);
263
-	} else {
264
-		$data = html2unicode($data, true);
265
-	}
266
-
267
-	return unicode2charset($data, $charset);
250
+    if (is_null($charset)) {
251
+        $charset = $GLOBALS['meta']['charset'];
252
+    }
253
+
254
+    if ($dtc) {
255
+        $trans = array();
256
+
257
+        foreach ($dtc->entites as $k => $v) {
258
+            if (!strpos(" amp lt gt quot ", $k)) {
259
+                $trans["&$k;"] = $v;
260
+            }
261
+        }
262
+        $data = strtr($data, $trans);
263
+    } else {
264
+        $data = html2unicode($data, true);
265
+    }
266
+
267
+    return unicode2charset($data, $charset);
268 268
 }
269 269
 
270 270
 // Retirer < ? xml... ? > et autre PI, ainsi que les commentaires en debut
@@ -275,52 +275,52 @@  discard block
 block discarded – undo
275 275
 // mais un XML Schema que SPIP ne fait pas encore lire.
276 276
 // http://code.spip.net/@analyser_doctype
277 277
 function analyser_doctype($data) {
278
-	if (!preg_match(_REGEXP_DOCTYPE, $data, $page)) {
279
-		if (preg_match(_REGEXP_XML, $data, $page)) {
280
-			list(, $entete, $topelement) = $page;
281
-			if ($topelement == 'rss') {
282
-				return array(
283
-					$entete,
284
-					'PUBLIC',
285
-					_DOCTYPE_RSS,
286
-					'rss-0.91.dtd'
287
-				);
288
-			} else {
289
-				$dtd = $topelement . '.dtd';
290
-				$f = find_in_path($dtd);
291
-				if (file_exists($f)) {
292
-					return array($entete, 'SYSTEM', $f, $dtd);
293
-				}
294
-			}
295
-		}
296
-		spip_log("Dtd pas vu pour " . substr($data, 0, 100));
297
-
298
-		return array();
299
-	}
300
-	list($entete, , $topelement, $avail, $suite) = $page;
301
-
302
-	if (!preg_match('/^"([^"]*)"\s*(.*)$/', $suite, $r)) {
303
-		if (!preg_match("/^'([^']*)'\s*(.*)$/", $suite, $r)) {
304
-			return array();
305
-		}
306
-	}
307
-	list(, $rotlvl, $suite) = $r;
308
-
309
-	if (!$suite) {
310
-		if ($avail != 'SYSTEM') {
311
-			return array();
312
-		}
313
-		$grammaire = $rotlvl;
314
-		$rotlvl = '';
315
-	} else {
316
-		if (!preg_match('/^"([^"]*)"\s*$/', $suite, $r)) {
317
-			if (!preg_match("/^'([^']*)'\s*$/", $suite, $r)) {
318
-				return array();
319
-			}
320
-		}
321
-
322
-		$grammaire = $r[1];
323
-	}
324
-
325
-	return array($entete, $avail, $grammaire, $rotlvl);
278
+    if (!preg_match(_REGEXP_DOCTYPE, $data, $page)) {
279
+        if (preg_match(_REGEXP_XML, $data, $page)) {
280
+            list(, $entete, $topelement) = $page;
281
+            if ($topelement == 'rss') {
282
+                return array(
283
+                    $entete,
284
+                    'PUBLIC',
285
+                    _DOCTYPE_RSS,
286
+                    'rss-0.91.dtd'
287
+                );
288
+            } else {
289
+                $dtd = $topelement . '.dtd';
290
+                $f = find_in_path($dtd);
291
+                if (file_exists($f)) {
292
+                    return array($entete, 'SYSTEM', $f, $dtd);
293
+                }
294
+            }
295
+        }
296
+        spip_log("Dtd pas vu pour " . substr($data, 0, 100));
297
+
298
+        return array();
299
+    }
300
+    list($entete, , $topelement, $avail, $suite) = $page;
301
+
302
+    if (!preg_match('/^"([^"]*)"\s*(.*)$/', $suite, $r)) {
303
+        if (!preg_match("/^'([^']*)'\s*(.*)$/", $suite, $r)) {
304
+            return array();
305
+        }
306
+    }
307
+    list(, $rotlvl, $suite) = $r;
308
+
309
+    if (!$suite) {
310
+        if ($avail != 'SYSTEM') {
311
+            return array();
312
+        }
313
+        $grammaire = $rotlvl;
314
+        $rotlvl = '';
315
+    } else {
316
+        if (!preg_match('/^"([^"]*)"\s*$/', $suite, $r)) {
317
+            if (!preg_match("/^'([^']*)'\s*$/", $suite, $r)) {
318
+                return array();
319
+            }
320
+        }
321
+
322
+        $grammaire = $r[1];
323
+    }
324
+
325
+    return array($entete, $avail, $grammaire, $rotlvl);
326 326
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -22 removed lines patch added patch discarded remove patch
@@ -45,8 +45,8 @@  discard block
 block discarded – undo
45 45
 	$t = isset($phraseur->ouvrant[$depth]) ? $phraseur->ouvrant[$depth] : ' ';
46 46
 	// espace initial signifie: deja integree au resultat
47 47
 	if ($t[0] != ' ') {
48
-		$phraseur->res .= '<' . $t . '>';
49
-		$phraseur->ouvrant[$depth] = ' ' . $t;
48
+		$phraseur->res .= '<'.$t.'>';
49
+		$phraseur->ouvrant[$depth] = ' '.$t;
50 50
 	}
51 51
 	$t = $phraseur->contenu[$depth];
52 52
 	// n'indenter que s'il y a un separateur avant
@@ -57,14 +57,14 @@  discard block
 block discarded – undo
57 57
 	foreach ($attrs as $k => $v) {
58 58
 		$delim = strpos($v, "'") === false ? "'" : '"';
59 59
 		$val = xml_entites_html($v);
60
-		$att .= $sep . $k . "=" . $delim
60
+		$att .= $sep.$k."=".$delim
61 61
 			. ($delim !== '"' ? str_replace('&quot;', '"', $val) : $val)
62 62
 			. $delim;
63 63
 		$sep = "\n $depth";
64 64
 	}
65 65
 	$phraseur->depth .= '  ';
66 66
 	$phraseur->contenu[$phraseur->depth] = "";
67
-	$phraseur->ouvrant[$phraseur->depth] = $name . $att;
67
+	$phraseur->ouvrant[$phraseur->depth] = $name.$att;
68 68
 	$phraseur->reperes[$phraseur->depth] = xml_get_current_line_number($phraseur->sax);
69 69
 }
70 70
 
@@ -73,13 +73,13 @@  discard block
 block discarded – undo
73 73
 	$ouv = $phraseur->ouvrant[$phraseur->depth];
74 74
 
75 75
 	if ($ouv[0] != ' ') {
76
-		$phraseur->ouvrant[$phraseur->depth] = ' ' . $ouv;
76
+		$phraseur->ouvrant[$phraseur->depth] = ' '.$ouv;
77 77
 	} else {
78 78
 		$ouv = "";
79 79
 	}
80 80
 	$t = $phraseur->contenu[$phraseur->depth];
81 81
 	$phraseur->depth = substr($phraseur->depth, 2);
82
-	$t = preg_replace("/[\n\t ]+$/", "\n" . $phraseur->depth, $t);
82
+	$t = preg_replace("/[\n\t ]+$/", "\n".$phraseur->depth, $t);
83 83
 
84 84
 	// fusion <balise></balise> en <balise />.
85 85
 	// ATTENTION,  certains clients http croient que fusion ==> pas d'atttributs
@@ -88,9 +88,9 @@  discard block
 block discarded – undo
88 88
 	// (param fusion_bal)
89 89
 
90 90
 	if ($t || (($ouv != $name) and !$fusion_bal)) {
91
-		$phraseur->res .= ($ouv ? ('<' . $ouv . '>') : '') . $t . "</" . $name . ">";
91
+		$phraseur->res .= ($ouv ? ('<'.$ouv.'>') : '').$t."</".$name.">";
92 92
 	} else {
93
-		$phraseur->res .= ($ouv ? ('<' . $ouv . ' />') : ("</" . $name . ">"));
93
+		$phraseur->res .= ($ouv ? ('<'.$ouv.' />') : ("</".$name.">"));
94 94
 	}
95 95
 }
96 96
 
@@ -134,16 +134,15 @@  discard block
 block discarded – undo
134 134
 	if (!xml_parse($phraseur->sax, $data, true)) {
135 135
 		coordonnees_erreur($phraseur,
136 136
 			xml_error_string(xml_get_error_code($phraseur->sax))
137
-			. "<br />\n" .
138
-			(!$phraseur->depth ? '' :
139
-				('(' .
140
-					_T('erreur_balise_non_fermee') .
141
-					" <tt>" .
142
-					$phraseur->ouvrant[$phraseur->depth] .
143
-					"</tt> " .
144
-					_T('ligne') .
145
-					" " .
146
-					$phraseur->reperes[$phraseur->depth] .
137
+			. "<br />\n".
138
+			(!$phraseur->depth ? '' : ('('.
139
+					_T('erreur_balise_non_fermee').
140
+					" <tt>".
141
+					$phraseur->ouvrant[$phraseur->depth].
142
+					"</tt> ".
143
+					_T('ligne').
144
+					" ".
145
+					$phraseur->reperes[$phraseur->depth].
147 146
 					") <br />\n")));
148 147
 	}
149 148
 }
@@ -185,7 +184,7 @@  discard block
 block discarded – undo
185 184
 	// et escamoter le doctype que sax mange en php5 mais pas en  php4
186 185
 	if (!$doctype) {
187 186
 		if (!$r = analyser_doctype($page)) {
188
-			$page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE
187
+			$page = _MESSAGE_DOCTYPE._DOCTYPE_ECRIRE
189 188
 				. preg_replace(_REGEXP_DOCTYPE, '', $page);
190 189
 			$r = analyser_doctype($page);
191 190
 		}
@@ -286,18 +285,18 @@  discard block
 block discarded – undo
286 285
 					'rss-0.91.dtd'
287 286
 				);
288 287
 			} else {
289
-				$dtd = $topelement . '.dtd';
288
+				$dtd = $topelement.'.dtd';
290 289
 				$f = find_in_path($dtd);
291 290
 				if (file_exists($f)) {
292 291
 					return array($entete, 'SYSTEM', $f, $dtd);
293 292
 				}
294 293
 			}
295 294
 		}
296
-		spip_log("Dtd pas vu pour " . substr($data, 0, 100));
295
+		spip_log("Dtd pas vu pour ".substr($data, 0, 100));
297 296
 
298 297
 		return array();
299 298
 	}
300
-	list($entete, , $topelement, $avail, $suite) = $page;
299
+	list($entete,, $topelement, $avail, $suite) = $page;
301 300
 
302 301
 	if (!preg_match('/^"([^"]*)"\s*(.*)$/', $suite, $r)) {
303 302
 		if (!preg_match("/^'([^']*)'\s*(.*)$/", $suite, $r)) {
Please login to merge, or discard this patch.
ecrire/inc/securiser_action.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -304,6 +304,7 @@
 block discarded – undo
304 304
  * @param string $url Url à autoriser en prévisu
305 305
  * @param int|null id_auteur qui génère le token de prévisu. Null utilisera auteur courant.
306 306
  * @param string $alea Nom de l’alea à utiliser
307
+ * @param integer $id_auteur
307 308
  * @return string Token, de la forme "{id}*{hash}"
308 309
  */
309 310
 function calculer_token_previsu($url, $id_auteur = null, $alea = 'alea_ephemere') {
Please login to merge, or discard this patch.
Indentation   +175 added lines, -175 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
 /**
@@ -50,19 +50,19 @@  discard block
 block discarded – undo
50 50
  * @return array|string
51 51
  */
52 52
 function inc_securiser_action_dist($action = '', $arg = '', $redirect = "", $mode = false, $att = '', $public = false) {
53
-	if ($action) {
54
-		return securiser_action_auteur($action, $arg, $redirect, $mode, $att, $public);
55
-	} else {
56
-		$arg = _request('arg');
57
-		$hash = _request('hash');
58
-		$action = _request('action') ? _request('action') : _request('formulaire_action');
59
-		if ($a = verifier_action_auteur("$action-$arg", $hash)) {
60
-			return $arg;
61
-		}
62
-		include_spip('inc/minipres');
63
-		echo minipres();
64
-		exit;
65
-	}
53
+    if ($action) {
54
+        return securiser_action_auteur($action, $arg, $redirect, $mode, $att, $public);
55
+    } else {
56
+        $arg = _request('arg');
57
+        $hash = _request('hash');
58
+        $action = _request('action') ? _request('action') : _request('formulaire_action');
59
+        if ($a = verifier_action_auteur("$action-$arg", $hash)) {
60
+            return $arg;
61
+        }
62
+        include_spip('inc/minipres');
63
+        echo minipres();
64
+        exit;
65
+    }
66 66
 }
67 67
 
68 68
 /**
@@ -94,30 +94,30 @@  discard block
 block discarded – undo
94 94
  */
95 95
 function securiser_action_auteur($action, $arg, $redirect = "", $mode = false, $att = '', $public = false) {
96 96
 
97
-	// mode URL ou array
98
-	if (!is_string($mode)) {
99
-		$hash = calculer_action_auteur("$action-$arg", is_numeric($att) ? $att : null);
100
-
101
-		$r = rawurlencode($redirect);
102
-		if ($mode === -1) {
103
-			return array('action' => $action, 'arg' => $arg, 'hash' => $hash);
104
-		} else {
105
-			return generer_url_action($action, "arg=" . rawurlencode($arg) . "&hash=$hash" . (!$r ? '' : "&redirect=$r"),
106
-				$mode, $public);
107
-		}
108
-	}
109
-
110
-	// mode formulaire
111
-	$hash = calculer_action_auteur("$action-$arg");
112
-	$att .= " style='margin: 0px; border: 0px'";
113
-	if ($redirect) {
114
-		$redirect = "\n\t\t<input name='redirect' type='hidden' value='" . str_replace("'", '&#39;', $redirect) . "' />";
115
-	}
116
-	$mode .= $redirect . "
97
+    // mode URL ou array
98
+    if (!is_string($mode)) {
99
+        $hash = calculer_action_auteur("$action-$arg", is_numeric($att) ? $att : null);
100
+
101
+        $r = rawurlencode($redirect);
102
+        if ($mode === -1) {
103
+            return array('action' => $action, 'arg' => $arg, 'hash' => $hash);
104
+        } else {
105
+            return generer_url_action($action, "arg=" . rawurlencode($arg) . "&hash=$hash" . (!$r ? '' : "&redirect=$r"),
106
+                $mode, $public);
107
+        }
108
+    }
109
+
110
+    // mode formulaire
111
+    $hash = calculer_action_auteur("$action-$arg");
112
+    $att .= " style='margin: 0px; border: 0px'";
113
+    if ($redirect) {
114
+        $redirect = "\n\t\t<input name='redirect' type='hidden' value='" . str_replace("'", '&#39;', $redirect) . "' />";
115
+    }
116
+    $mode .= $redirect . "
117 117
 <input name='hash' type='hidden' value='$hash' />
118 118
 <input name='arg' type='hidden' value='$arg' />";
119 119
 
120
-	return generer_form_action($action, $mode, $att, $public);
120
+    return generer_form_action($action, $mode, $att, $public);
121 121
 }
122 122
 
123 123
 /**
@@ -127,47 +127,47 @@  discard block
 block discarded – undo
127 127
  * @return array
128 128
  */
129 129
 function caracteriser_auteur($id_auteur = null) {
130
-	static $caracterisation = array();
131
-
132
-	if (is_null($id_auteur) and !isset($GLOBALS['visiteur_session']['id_auteur'])) {
133
-		// si l'auteur courant n'est pas connu alors qu'il peut demander une action
134
-		// c'est une connexion par php_auth ou 1 instal, on se rabat sur le cookie.
135
-		// S'il n'avait pas le droit de realiser cette action, le hash sera faux.
136
-		if (isset($_COOKIE['spip_session'])
137
-			and (preg_match('/^(\d+)/', $_COOKIE['spip_session'], $r))
138
-		) {
139
-			return array($r[1], '');
140
-			// Necessaire aux forums anonymes.
141
-			// Pour le reste, ca echouera.
142
-		} else {
143
-			return array('0', '');
144
-		}
145
-	}
146
-	// Eviter l'acces SQL si le pass est connu de PHP
147
-	if (is_null($id_auteur)) {
148
-		$id_auteur = isset($GLOBALS['visiteur_session']['id_auteur']) ? $GLOBALS['visiteur_session']['id_auteur'] : 0;
149
-		if (isset($GLOBALS['visiteur_session']['pass']) and $GLOBALS['visiteur_session']['pass']) {
150
-			return $caracterisation[$id_auteur] = array($id_auteur, $GLOBALS['visiteur_session']['pass']);
151
-		}
152
-	}
153
-
154
-	if (isset($caracterisation[$id_auteur])) {
155
-		return $caracterisation[$id_auteur];
156
-	}
157
-
158
-	if ($id_auteur) {
159
-		include_spip('base/abstract_sql');
160
-		$t = sql_fetsel("id_auteur, pass", "spip_auteurs", "id_auteur=$id_auteur");
161
-		if ($t) {
162
-			return $caracterisation[$id_auteur] = array($t['id_auteur'], $t['pass']);
163
-		}
164
-		include_spip('inc/minipres');
165
-		echo minipres();
166
-		exit;
167
-	} // Visiteur anonyme, pour ls forums par exemple
168
-	else {
169
-		return array('0', '');
170
-	}
130
+    static $caracterisation = array();
131
+
132
+    if (is_null($id_auteur) and !isset($GLOBALS['visiteur_session']['id_auteur'])) {
133
+        // si l'auteur courant n'est pas connu alors qu'il peut demander une action
134
+        // c'est une connexion par php_auth ou 1 instal, on se rabat sur le cookie.
135
+        // S'il n'avait pas le droit de realiser cette action, le hash sera faux.
136
+        if (isset($_COOKIE['spip_session'])
137
+            and (preg_match('/^(\d+)/', $_COOKIE['spip_session'], $r))
138
+        ) {
139
+            return array($r[1], '');
140
+            // Necessaire aux forums anonymes.
141
+            // Pour le reste, ca echouera.
142
+        } else {
143
+            return array('0', '');
144
+        }
145
+    }
146
+    // Eviter l'acces SQL si le pass est connu de PHP
147
+    if (is_null($id_auteur)) {
148
+        $id_auteur = isset($GLOBALS['visiteur_session']['id_auteur']) ? $GLOBALS['visiteur_session']['id_auteur'] : 0;
149
+        if (isset($GLOBALS['visiteur_session']['pass']) and $GLOBALS['visiteur_session']['pass']) {
150
+            return $caracterisation[$id_auteur] = array($id_auteur, $GLOBALS['visiteur_session']['pass']);
151
+        }
152
+    }
153
+
154
+    if (isset($caracterisation[$id_auteur])) {
155
+        return $caracterisation[$id_auteur];
156
+    }
157
+
158
+    if ($id_auteur) {
159
+        include_spip('base/abstract_sql');
160
+        $t = sql_fetsel("id_auteur, pass", "spip_auteurs", "id_auteur=$id_auteur");
161
+        if ($t) {
162
+            return $caracterisation[$id_auteur] = array($t['id_auteur'], $t['pass']);
163
+        }
164
+        include_spip('inc/minipres');
165
+        echo minipres();
166
+        exit;
167
+    } // Visiteur anonyme, pour ls forums par exemple
168
+    else {
169
+        return array('0', '');
170
+    }
171 171
 }
172 172
 
173 173
 /**
@@ -182,26 +182,26 @@  discard block
 block discarded – undo
182 182
  * @return string
183 183
  */
184 184
 function _action_auteur($action, $id_auteur, $pass, $alea) {
185
-	static $sha = array();
186
-	if (!isset($sha[$id_auteur . $pass . $alea])) {
187
-		if (!isset($GLOBALS['meta'][$alea]) and _request('exec') !== 'install') {
188
-			include_spip('inc/acces');
189
-			charger_aleas();
190
-			if (empty($GLOBALS['meta'][$alea])) {
191
-				include_spip('inc/minipres');
192
-				echo minipres();
193
-				spip_log("$alea indisponible");
194
-				exit;
195
-			}
196
-		}
197
-		include_spip('auth/sha256.inc');
198
-		$sha[$id_auteur . $pass . $alea] = _nano_sha256($id_auteur . $pass . @$GLOBALS['meta'][$alea]);
199
-	}
200
-	if (function_exists('sha1')) {
201
-		return sha1($action . $sha[$id_auteur . $pass . $alea]);
202
-	} else {
203
-		return md5($action . $sha[$id_auteur . $pass . $alea]);
204
-	}
185
+    static $sha = array();
186
+    if (!isset($sha[$id_auteur . $pass . $alea])) {
187
+        if (!isset($GLOBALS['meta'][$alea]) and _request('exec') !== 'install') {
188
+            include_spip('inc/acces');
189
+            charger_aleas();
190
+            if (empty($GLOBALS['meta'][$alea])) {
191
+                include_spip('inc/minipres');
192
+                echo minipres();
193
+                spip_log("$alea indisponible");
194
+                exit;
195
+            }
196
+        }
197
+        include_spip('auth/sha256.inc');
198
+        $sha[$id_auteur . $pass . $alea] = _nano_sha256($id_auteur . $pass . @$GLOBALS['meta'][$alea]);
199
+    }
200
+    if (function_exists('sha1')) {
201
+        return sha1($action . $sha[$id_auteur . $pass . $alea]);
202
+    } else {
203
+        return md5($action . $sha[$id_auteur . $pass . $alea]);
204
+    }
205 205
 }
206 206
 
207 207
 /**
@@ -212,9 +212,9 @@  discard block
 block discarded – undo
212 212
  * @return string
213 213
  */
214 214
 function calculer_action_auteur($action, $id_auteur = null) {
215
-	list($id_auteur, $pass) = caracteriser_auteur($id_auteur);
215
+    list($id_auteur, $pass) = caracteriser_auteur($id_auteur);
216 216
 
217
-	return _action_auteur($action, $id_auteur, $pass, 'alea_ephemere');
217
+    return _action_auteur($action, $id_auteur, $pass, 'alea_ephemere');
218 218
 }
219 219
 
220 220
 
@@ -227,15 +227,15 @@  discard block
 block discarded – undo
227 227
  * @return bool
228 228
  */
229 229
 function verifier_action_auteur($action, $hash) {
230
-	list($id_auteur, $pass) = caracteriser_auteur();
231
-	if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere')) {
232
-		return true;
233
-	}
234
-	if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere_ancien')) {
235
-		return true;
236
-	}
237
-
238
-	return false;
230
+    list($id_auteur, $pass) = caracteriser_auteur();
231
+    if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere')) {
232
+        return true;
233
+    }
234
+    if ($hash == _action_auteur($action, $id_auteur, $pass, 'alea_ephemere_ancien')) {
235
+        return true;
236
+    }
237
+
238
+    return false;
239 239
 }
240 240
 
241 241
 //
@@ -251,21 +251,21 @@  discard block
 block discarded – undo
251 251
  * @return string
252 252
  */
253 253
 function secret_du_site() {
254
-	if (!isset($GLOBALS['meta']['secret_du_site'])) {
255
-		include_spip('base/abstract_sql');
256
-		$GLOBALS['meta']['secret_du_site'] = sql_getfetsel('valeur', 'spip_meta', "nom='secret_du_site'");
257
-	}
258
-	if (!isset($GLOBALS['meta']['secret_du_site'])
259
-		or (strlen($GLOBALS['meta']['secret_du_site']) < 64)
260
-	) {
261
-		include_spip('inc/acces');
262
-		include_spip('auth/sha256.inc');
263
-		ecrire_meta('secret_du_site',
264
-			_nano_sha256($_SERVER["DOCUMENT_ROOT"] . $_SERVER["SERVER_SIGNATURE"] . creer_uniqid()), 'non');
265
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
266
-	}
267
-
268
-	return $GLOBALS['meta']['secret_du_site'];
254
+    if (!isset($GLOBALS['meta']['secret_du_site'])) {
255
+        include_spip('base/abstract_sql');
256
+        $GLOBALS['meta']['secret_du_site'] = sql_getfetsel('valeur', 'spip_meta', "nom='secret_du_site'");
257
+    }
258
+    if (!isset($GLOBALS['meta']['secret_du_site'])
259
+        or (strlen($GLOBALS['meta']['secret_du_site']) < 64)
260
+    ) {
261
+        include_spip('inc/acces');
262
+        include_spip('auth/sha256.inc');
263
+        ecrire_meta('secret_du_site',
264
+            _nano_sha256($_SERVER["DOCUMENT_ROOT"] . $_SERVER["SERVER_SIGNATURE"] . creer_uniqid()), 'non');
265
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
266
+    }
267
+
268
+    return $GLOBALS['meta']['secret_du_site'];
269 269
 }
270 270
 
271 271
 /**
@@ -275,11 +275,11 @@  discard block
 block discarded – undo
275 275
  * @return string
276 276
  */
277 277
 function calculer_cle_action($action) {
278
-	if (function_exists('sha1')) {
279
-		return sha1($action . secret_du_site());
280
-	} else {
281
-		return md5($action . secret_du_site());
282
-	}
278
+    if (function_exists('sha1')) {
279
+        return sha1($action . secret_du_site());
280
+    } else {
281
+        return md5($action . secret_du_site());
282
+    }
283 283
 }
284 284
 
285 285
 /**
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
  * @return bool
291 291
  */
292 292
 function verifier_cle_action($action, $cle) {
293
-	return ($cle == calculer_cle_action($action));
293
+    return ($cle == calculer_cle_action($action));
294 294
 }
295 295
 
296 296
 
@@ -307,19 +307,19 @@  discard block
 block discarded – undo
307 307
  * @return string Token, de la forme "{id}*{hash}"
308 308
  */
309 309
 function calculer_token_previsu($url, $id_auteur = null, $alea = 'alea_ephemere') {
310
-	if (is_null($id_auteur)) {
311
-		if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
312
-			$id_auteur = $GLOBALS['visiteur_session']['id_auteur'];
313
-		}
314
-	}
315
-	if (!$id_auteur = intval($id_auteur)) {
316
-		return "";
317
-	}
318
-	// On nettoie l’URL de tous les var_.
319
-	$url = nettoyer_uri_var($url);
320
-
321
-	$token = _action_auteur('previsualiser-' . $url, $id_auteur, null, $alea);
322
-	return "$id_auteur-$token";
310
+    if (is_null($id_auteur)) {
311
+        if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
312
+            $id_auteur = $GLOBALS['visiteur_session']['id_auteur'];
313
+        }
314
+    }
315
+    if (!$id_auteur = intval($id_auteur)) {
316
+        return "";
317
+    }
318
+    // On nettoie l’URL de tous les var_.
319
+    $url = nettoyer_uri_var($url);
320
+
321
+    $token = _action_auteur('previsualiser-' . $url, $id_auteur, null, $alea);
322
+    return "$id_auteur-$token";
323 323
 }
324 324
 
325 325
 
@@ -337,31 +337,31 @@  discard block
 block discarded – undo
337 337
  *     + Tableau (id auteur, type d’objet, id_objet) sinon.
338 338
  */
339 339
 function verifier_token_previsu($token) {
340
-	// retrouver auteur / hash
341
-	$e = explode('-', $token, 2);
342
-	if (count($e) == 2 and is_numeric(reset($e))) {
343
-		$id_auteur = intval(reset($e));
344
-	} else {
345
-		return false;
346
-	}
347
-
348
-	// calculer le type et id de l’url actuelle
349
-	include_spip('inc/urls');
350
-	include_spip('inc/filtres_mini');
351
-	$url = url_absolue(self());
352
-
353
-	// verifier le token
354
-	$_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere');
355
-	if (!$_token or $token !== $_token) {
356
-		$_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere_ancien');
357
-		if (!$_token or $token !== $_token) {
358
-			return false;
359
-		}
360
-	}
361
-
362
-	return array(
363
-		'id_auteur' => $id_auteur,
364
-	);
340
+    // retrouver auteur / hash
341
+    $e = explode('-', $token, 2);
342
+    if (count($e) == 2 and is_numeric(reset($e))) {
343
+        $id_auteur = intval(reset($e));
344
+    } else {
345
+        return false;
346
+    }
347
+
348
+    // calculer le type et id de l’url actuelle
349
+    include_spip('inc/urls');
350
+    include_spip('inc/filtres_mini');
351
+    $url = url_absolue(self());
352
+
353
+    // verifier le token
354
+    $_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere');
355
+    if (!$_token or $token !== $_token) {
356
+        $_token = calculer_token_previsu($url, $id_auteur, 'alea_ephemere_ancien');
357
+        if (!$_token or $token !== $_token) {
358
+            return false;
359
+        }
360
+    }
361
+
362
+    return array(
363
+        'id_auteur' => $id_auteur,
364
+    );
365 365
 }
366 366
 
367 367
 /**
@@ -370,13 +370,13 @@  discard block
 block discarded – undo
370 370
  * @return bool|array
371 371
  */
372 372
 function decrire_token_previsu() {
373
-	static $desc = null;
374
-	if (is_null($desc)) {
375
-		if ($token = _request('var_previewtoken')) {
376
-			$desc = verifier_token_previsu($token);
377
-		} else {
378
-			$desc = false;
379
-		}
380
-	}
381
-	return $desc;
373
+    static $desc = null;
374
+    if (is_null($desc)) {
375
+        if ($token = _request('var_previewtoken')) {
376
+            $desc = verifier_token_previsu($token);
377
+        } else {
378
+            $desc = false;
379
+        }
380
+    }
381
+    return $desc;
382 382
 }
383 383
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		if ($mode === -1) {
103 103
 			return array('action' => $action, 'arg' => $arg, 'hash' => $hash);
104 104
 		} else {
105
-			return generer_url_action($action, "arg=" . rawurlencode($arg) . "&hash=$hash" . (!$r ? '' : "&redirect=$r"),
105
+			return generer_url_action($action, "arg=".rawurlencode($arg)."&hash=$hash".(!$r ? '' : "&redirect=$r"),
106 106
 				$mode, $public);
107 107
 		}
108 108
 	}
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 	$hash = calculer_action_auteur("$action-$arg");
112 112
 	$att .= " style='margin: 0px; border: 0px'";
113 113
 	if ($redirect) {
114
-		$redirect = "\n\t\t<input name='redirect' type='hidden' value='" . str_replace("'", '&#39;', $redirect) . "' />";
114
+		$redirect = "\n\t\t<input name='redirect' type='hidden' value='".str_replace("'", '&#39;', $redirect)."' />";
115 115
 	}
116
-	$mode .= $redirect . "
116
+	$mode .= $redirect."
117 117
 <input name='hash' type='hidden' value='$hash' />
118 118
 <input name='arg' type='hidden' value='$arg' />";
119 119
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
  */
184 184
 function _action_auteur($action, $id_auteur, $pass, $alea) {
185 185
 	static $sha = array();
186
-	if (!isset($sha[$id_auteur . $pass . $alea])) {
186
+	if (!isset($sha[$id_auteur.$pass.$alea])) {
187 187
 		if (!isset($GLOBALS['meta'][$alea]) and _request('exec') !== 'install') {
188 188
 			include_spip('inc/acces');
189 189
 			charger_aleas();
@@ -195,12 +195,12 @@  discard block
 block discarded – undo
195 195
 			}
196 196
 		}
197 197
 		include_spip('auth/sha256.inc');
198
-		$sha[$id_auteur . $pass . $alea] = _nano_sha256($id_auteur . $pass . @$GLOBALS['meta'][$alea]);
198
+		$sha[$id_auteur.$pass.$alea] = _nano_sha256($id_auteur.$pass.@$GLOBALS['meta'][$alea]);
199 199
 	}
200 200
 	if (function_exists('sha1')) {
201
-		return sha1($action . $sha[$id_auteur . $pass . $alea]);
201
+		return sha1($action.$sha[$id_auteur.$pass.$alea]);
202 202
 	} else {
203
-		return md5($action . $sha[$id_auteur . $pass . $alea]);
203
+		return md5($action.$sha[$id_auteur.$pass.$alea]);
204 204
 	}
205 205
 }
206 206
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 		include_spip('inc/acces');
262 262
 		include_spip('auth/sha256.inc');
263 263
 		ecrire_meta('secret_du_site',
264
-			_nano_sha256($_SERVER["DOCUMENT_ROOT"] . $_SERVER["SERVER_SIGNATURE"] . creer_uniqid()), 'non');
264
+			_nano_sha256($_SERVER["DOCUMENT_ROOT"].$_SERVER["SERVER_SIGNATURE"].creer_uniqid()), 'non');
265 265
 		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
266 266
 	}
267 267
 
@@ -276,9 +276,9 @@  discard block
 block discarded – undo
276 276
  */
277 277
 function calculer_cle_action($action) {
278 278
 	if (function_exists('sha1')) {
279
-		return sha1($action . secret_du_site());
279
+		return sha1($action.secret_du_site());
280 280
 	} else {
281
-		return md5($action . secret_du_site());
281
+		return md5($action.secret_du_site());
282 282
 	}
283 283
 }
284 284
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 	// On nettoie l’URL de tous les var_.
319 319
 	$url = nettoyer_uri_var($url);
320 320
 
321
-	$token = _action_auteur('previsualiser-' . $url, $id_auteur, null, $alea);
321
+	$token = _action_auteur('previsualiser-'.$url, $id_auteur, null, $alea);
322 322
 	return "$id_auteur-$token";
323 323
 }
324 324
 
Please login to merge, or discard this patch.
ecrire/public/quete.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -28,9 +28,9 @@  discard block
 block discarded – undo
28 28
 /**
29 29
  * Retourne l'URL de redirection d'un article virtuel, seulement si il est publié
30 30
  *
31
- * @param $id_article
32
- * @param $connect
33
- * @return array|bool|null
31
+ * @param integer $id_article
32
+ * @param string $connect
33
+ * @return string
34 34
  */
35 35
 function quete_virtuel($id_article, $connect) {
36 36
 	return sql_getfetsel(
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
  * @uses quete_parent_lang()
123 123
  *
124 124
  * @param int $id_article
125
- * @param $serveur
125
+ * @param string $serveur
126 126
  * @return int
127 127
  */
128 128
 function quete_rubrique($id_article, $serveur) {
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
  *
294 294
  * @param int $id_document
295 295
  * @param string $serveur
296
- * @return array|bool|null
296
+ * @return string
297 297
  */
298 298
 function quete_fichier($id_document, $serveur = '') {
299 299
 	return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
Please login to merge, or discard this patch.
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
  **/
20 20
 
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	return;
22
+    return;
23 23
 }
24 24
 
25 25
 
@@ -33,16 +33,16 @@  discard block
 block discarded – undo
33 33
  * @return array|bool|null
34 34
  */
35 35
 function quete_virtuel($id_article, $connect) {
36
-	return sql_getfetsel(
37
-		'virtuel',
38
-		'spip_articles',
39
-		array('id_article=' . intval($id_article), "statut='publie'"),
40
-		'',
41
-		'',
42
-		'',
43
-		'',
44
-		$connect
45
-	);
36
+    return sql_getfetsel(
37
+        'virtuel',
38
+        'spip_articles',
39
+        array('id_article=' . intval($id_article), "statut='publie'"),
40
+        '',
41
+        '',
42
+        '',
43
+        '',
44
+        $connect
45
+    );
46 46
 }
47 47
 
48 48
 /**
@@ -57,38 +57,38 @@  discard block
 block discarded – undo
57 57
  * @return array
58 58
  */
59 59
 function quete_parent_lang($table, $id, $connect = '') {
60
-	static $cache_quete = array();
61
-
62
-	if (!isset($cache_quete[$connect][$table][$id])) {
63
-		if (!isset($cache_quete[$connect][$table]['_select'])) {
64
-			$trouver_table = charger_fonction('trouver_table', 'base');
65
-			if (!$desc = $trouver_table($table,
66
-					$connect) or !isset($desc['field']['id_rubrique'])
67
-			) {
68
-				// pas de parent rubrique, on passe
69
-				$cache_quete[$connect][$table]['_select'] = false;
70
-			} else {
71
-				$select = ($table == 'spip_rubriques' ? 'id_parent' : 'id_rubrique');
72
-				$select .= isset($desc['field']['lang']) ? ', lang' : '';
73
-				$cache_quete[$connect][$table]['_select'] = $select;
74
-				$cache_quete[$connect][$table]['_id'] = id_table_objet(objet_type($table));
75
-			}
76
-		}
77
-		if ($cache_quete[$connect][$table]['_select']) {
78
-			$cache_quete[$connect][$table][$id] = sql_fetsel(
79
-				$cache_quete[$connect][$table]['_select'],
80
-				$table,
81
-				$cache_quete[$connect][$table]['_id'] . '=' . intval($id),
82
-				'',
83
-				'',
84
-				'',
85
-				'',
86
-				$connect
87
-			);
88
-		}
89
-	}
90
-
91
-	return isset($cache_quete[$connect][$table][$id]) ? $cache_quete[$connect][$table][$id] : null;
60
+    static $cache_quete = array();
61
+
62
+    if (!isset($cache_quete[$connect][$table][$id])) {
63
+        if (!isset($cache_quete[$connect][$table]['_select'])) {
64
+            $trouver_table = charger_fonction('trouver_table', 'base');
65
+            if (!$desc = $trouver_table($table,
66
+                    $connect) or !isset($desc['field']['id_rubrique'])
67
+            ) {
68
+                // pas de parent rubrique, on passe
69
+                $cache_quete[$connect][$table]['_select'] = false;
70
+            } else {
71
+                $select = ($table == 'spip_rubriques' ? 'id_parent' : 'id_rubrique');
72
+                $select .= isset($desc['field']['lang']) ? ', lang' : '';
73
+                $cache_quete[$connect][$table]['_select'] = $select;
74
+                $cache_quete[$connect][$table]['_id'] = id_table_objet(objet_type($table));
75
+            }
76
+        }
77
+        if ($cache_quete[$connect][$table]['_select']) {
78
+            $cache_quete[$connect][$table][$id] = sql_fetsel(
79
+                $cache_quete[$connect][$table]['_select'],
80
+                $table,
81
+                $cache_quete[$connect][$table]['_id'] . '=' . intval($id),
82
+                '',
83
+                '',
84
+                '',
85
+                '',
86
+                $connect
87
+            );
88
+        }
89
+    }
90
+
91
+    return isset($cache_quete[$connect][$table][$id]) ? $cache_quete[$connect][$table][$id] : null;
92 92
 }
93 93
 
94 94
 
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
  * @return int
106 106
  */
107 107
 function quete_parent($id_rubrique, $connect = '') {
108
-	if (!$id_rubrique = intval($id_rubrique)) {
109
-		return 0;
110
-	}
111
-	$id_parent = quete_parent_lang('spip_rubriques', $id_rubrique, $connect);
108
+    if (!$id_rubrique = intval($id_rubrique)) {
109
+        return 0;
110
+    }
111
+    $id_parent = quete_parent_lang('spip_rubriques', $id_rubrique, $connect);
112 112
 
113
-	return $id_parent['id_parent'];
113
+    return $id_parent['id_parent'];
114 114
 }
115 115
 
116 116
 /**
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
  * @return int
127 127
  */
128 128
 function quete_rubrique($id_article, $serveur) {
129
-	$id_parent = quete_parent_lang('spip_articles', $id_article, $serveur);
129
+    $id_parent = quete_parent_lang('spip_articles', $id_article, $serveur);
130 130
 
131
-	return $id_parent['id_rubrique'];
131
+    return $id_parent['id_rubrique'];
132 132
 }
133 133
 
134 134
 
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
  * @return int
143 143
  */
144 144
 function quete_profondeur($id, $connect = '') {
145
-	$n = 0;
146
-	while ($id) {
147
-		$n++;
148
-		$id = quete_parent($id, $connect);
149
-	}
145
+    $n = 0;
146
+    while ($id) {
147
+        $n++;
148
+        $id = quete_parent($id, $connect);
149
+    }
150 150
 
151
-	return $n;
151
+    return $n;
152 152
 }
153 153
 
154 154
 
@@ -164,15 +164,15 @@  discard block
 block discarded – undo
164 164
  *     Morceau de la requête SQL testant la date
165 165
  */
166 166
 function quete_condition_postdates($champ_date, $serveur = '', $ignore_previsu = false) {
167
-	if (defined('_VAR_PREVIEW') and _VAR_PREVIEW and !$ignore_previsu) {
168
-		return '1=1';
169
-	}
170
-
171
-	return
172
-		(isset($GLOBALS['meta']['date_prochain_postdate'])
173
-			and $GLOBALS['meta']['date_prochain_postdate'] > time())
174
-			? "$champ_date<" . sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
175
-			: '1=1';
167
+    if (defined('_VAR_PREVIEW') and _VAR_PREVIEW and !$ignore_previsu) {
168
+        return '1=1';
169
+    }
170
+
171
+    return
172
+        (isset($GLOBALS['meta']['date_prochain_postdate'])
173
+            and $GLOBALS['meta']['date_prochain_postdate'] > time())
174
+            ? "$champ_date<" . sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
175
+            : '1=1';
176 176
 }
177 177
 
178 178
 
@@ -192,100 +192,100 @@  discard block
 block discarded – undo
192 192
  * @return array|string
193 193
  */
194 194
 function quete_condition_statut($mstatut, $previsu, $publie, $serveur = '', $ignore_previsu = false) {
195
-	static $cond = array();
196
-	$key = func_get_args();
197
-	$key = implode('-', $key);
198
-	if (isset($cond[$key])) {
199
-		return $cond[$key];
200
-	}
201
-
202
-	$liste_statuts = $publie;
203
-	if (defined('_VAR_PREVIEW') and _VAR_PREVIEW and !$ignore_previsu) {
204
-		$liste_statuts = $previsu;
205
-	}
206
-	$not = false;
207
-	if (strncmp($liste_statuts, '!', 1) == 0) {
208
-		$not = true;
209
-		$liste_statuts = substr($liste_statuts, 1);
210
-	}
211
-	// '' => ne rien afficher, '!'=> ne rien filtrer
212
-	if (!strlen($liste_statuts)) {
213
-		return $cond[$key] = ($not ? '1=1' : '0=1');
214
-	}
215
-
216
-	$liste_statuts = explode(',', $liste_statuts);
217
-	$where = array();
218
-	foreach ($liste_statuts as $k => $v) {
219
-		// filtrage /auteur pour limiter les objets d'un statut (prepa en general)
220
-		// a ceux de l'auteur identifie
221
-		if (strpos($v, '/') !== false) {
222
-			$v = explode('/', $v);
223
-			$filtre = end($v);
224
-			$v = reset($v);
225
-			$v = preg_replace(',\W,', '', $v);
226
-			if ($filtre == 'auteur'
227
-				and (strpos($mstatut, '.') !== false)
228
-				and $objet = explode('.', $mstatut)
229
-				and $id_table = reset($objet)
230
-				and $objet = objet_type($id_table)
231
-			) {
232
-				$w = "$mstatut<>" . sql_quote($v);
233
-
234
-				// retrouver l’id_auteur qui a filé un lien de prévisu éventuellement,
235
-				// sinon l’auteur en session
236
-				include_spip('inc/securiser_action');
237
-				if ($desc = decrire_token_previsu()) {
238
-					$id_auteur = $desc['id_auteur'];
239
-				} elseif (isset($GLOBALS['visiteur_session']['id_auteur'])) {
240
-					$id_auteur = intval($GLOBALS['visiteur_session']['id_auteur']);
241
-				} else {
242
-					$id_auteur = null;
243
-				}
244
-
245
-				// dans ce cas (admin en general), pas de filtrage sur ce statut
246
-				if (!autoriser('previsualiser' . $v, $objet, '', $id_auteur)) {
247
-					// si pas d'auteur identifie pas de sous-requete car pas d'article qui matche
248
-					if (!$id_auteur) {
249
-						$where[] = $w;
250
-					} else {
251
-						$primary = id_table_objet($objet);
252
-						$where[] = "($w OR $id_table.$primary IN (" . sql_get_select(
253
-								'ssss.id_objet',
254
-								'spip_auteurs_liens AS ssss',
255
-								'ssss.objet=' . sql_quote($objet) . ' AND ssss.id_auteur=' . intval($id_auteur),
256
-								'',
257
-								'',
258
-								'',
259
-								'',
260
-								$serveur
261
-							) . '))';
262
-					}
263
-				}
264
-			} // ignorer ce statut si on ne sait pas comment le filtrer
265
-			else {
266
-				$v = '';
267
-			}
268
-		}
269
-		// securite
270
-		$liste_statuts[$k] = preg_replace(',\W,', '', $v);
271
-	}
272
-	$liste_statuts = array_filter($liste_statuts);
273
-	if (count($liste_statuts) == 1) {
274
-		$where[] = array('=', $mstatut, sql_quote(reset($liste_statuts), $serveur));
275
-	} else {
276
-		$where[] = sql_in($mstatut, $liste_statuts, $not, $serveur);
277
-	}
278
-
279
-	while (count($where) > 1) {
280
-		$and = array('AND', array_pop($where), array_pop($where));
281
-		$where[] = $and;
282
-	}
283
-	$cond[$key] = reset($where);
284
-	if ($not) {
285
-		$cond[$key] = array('NOT', $cond[$key]);
286
-	}
287
-
288
-	return $cond[$key];
195
+    static $cond = array();
196
+    $key = func_get_args();
197
+    $key = implode('-', $key);
198
+    if (isset($cond[$key])) {
199
+        return $cond[$key];
200
+    }
201
+
202
+    $liste_statuts = $publie;
203
+    if (defined('_VAR_PREVIEW') and _VAR_PREVIEW and !$ignore_previsu) {
204
+        $liste_statuts = $previsu;
205
+    }
206
+    $not = false;
207
+    if (strncmp($liste_statuts, '!', 1) == 0) {
208
+        $not = true;
209
+        $liste_statuts = substr($liste_statuts, 1);
210
+    }
211
+    // '' => ne rien afficher, '!'=> ne rien filtrer
212
+    if (!strlen($liste_statuts)) {
213
+        return $cond[$key] = ($not ? '1=1' : '0=1');
214
+    }
215
+
216
+    $liste_statuts = explode(',', $liste_statuts);
217
+    $where = array();
218
+    foreach ($liste_statuts as $k => $v) {
219
+        // filtrage /auteur pour limiter les objets d'un statut (prepa en general)
220
+        // a ceux de l'auteur identifie
221
+        if (strpos($v, '/') !== false) {
222
+            $v = explode('/', $v);
223
+            $filtre = end($v);
224
+            $v = reset($v);
225
+            $v = preg_replace(',\W,', '', $v);
226
+            if ($filtre == 'auteur'
227
+                and (strpos($mstatut, '.') !== false)
228
+                and $objet = explode('.', $mstatut)
229
+                and $id_table = reset($objet)
230
+                and $objet = objet_type($id_table)
231
+            ) {
232
+                $w = "$mstatut<>" . sql_quote($v);
233
+
234
+                // retrouver l’id_auteur qui a filé un lien de prévisu éventuellement,
235
+                // sinon l’auteur en session
236
+                include_spip('inc/securiser_action');
237
+                if ($desc = decrire_token_previsu()) {
238
+                    $id_auteur = $desc['id_auteur'];
239
+                } elseif (isset($GLOBALS['visiteur_session']['id_auteur'])) {
240
+                    $id_auteur = intval($GLOBALS['visiteur_session']['id_auteur']);
241
+                } else {
242
+                    $id_auteur = null;
243
+                }
244
+
245
+                // dans ce cas (admin en general), pas de filtrage sur ce statut
246
+                if (!autoriser('previsualiser' . $v, $objet, '', $id_auteur)) {
247
+                    // si pas d'auteur identifie pas de sous-requete car pas d'article qui matche
248
+                    if (!$id_auteur) {
249
+                        $where[] = $w;
250
+                    } else {
251
+                        $primary = id_table_objet($objet);
252
+                        $where[] = "($w OR $id_table.$primary IN (" . sql_get_select(
253
+                                'ssss.id_objet',
254
+                                'spip_auteurs_liens AS ssss',
255
+                                'ssss.objet=' . sql_quote($objet) . ' AND ssss.id_auteur=' . intval($id_auteur),
256
+                                '',
257
+                                '',
258
+                                '',
259
+                                '',
260
+                                $serveur
261
+                            ) . '))';
262
+                    }
263
+                }
264
+            } // ignorer ce statut si on ne sait pas comment le filtrer
265
+            else {
266
+                $v = '';
267
+            }
268
+        }
269
+        // securite
270
+        $liste_statuts[$k] = preg_replace(',\W,', '', $v);
271
+    }
272
+    $liste_statuts = array_filter($liste_statuts);
273
+    if (count($liste_statuts) == 1) {
274
+        $where[] = array('=', $mstatut, sql_quote(reset($liste_statuts), $serveur));
275
+    } else {
276
+        $where[] = sql_in($mstatut, $liste_statuts, $not, $serveur);
277
+    }
278
+
279
+    while (count($where) > 1) {
280
+        $and = array('AND', array_pop($where), array_pop($where));
281
+        $where[] = $and;
282
+    }
283
+    $cond[$key] = reset($where);
284
+    if ($not) {
285
+        $cond[$key] = array('NOT', $cond[$key]);
286
+    }
287
+
288
+    return $cond[$key];
289 289
 }
290 290
 
291 291
 /**
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
  * @return array|bool|null
297 297
  */
298 298
 function quete_fichier($id_document, $serveur = '') {
299
-	return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
299
+    return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
300 300
 }
301 301
 
302 302
 /**
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
  * @return array|bool
308 308
  */
309 309
 function quete_document($id_document, $serveur = '') {
310
-	return sql_fetsel('*', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
310
+    return sql_fetsel('*', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
311 311
 }
312 312
 
313 313
 /**
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
  * @return array|bool|null
319 319
  */
320 320
 function quete_meta($nom, $serveur) {
321
-	return sql_getfetsel('valeur', 'spip_meta', 'nom=' . sql_quote($nom), '', '', '', '', $serveur);
321
+    return sql_getfetsel('valeur', 'spip_meta', 'nom=' . sql_quote($nom), '', '', '', '', $serveur);
322 322
 }
323 323
 
324 324
 /**
@@ -344,64 +344,64 @@  discard block
 block discarded – undo
344 344
  *     Retourne soit un tableau, soit le chemin du fichier.
345 345
  */
346 346
 function quete_logo($cle_objet, $onoff, $id, $id_rubrique, $flag) {
347
-	include_spip('base/objets');
348
-	$nom = strtolower($onoff);
349
-
350
-	while (1) {
351
-		$objet = objet_type($cle_objet);
352
-
353
-		$on = quete_logo_objet($id, $objet, $nom);
354
-
355
-		if ($on) {
356
-			if ($flag) {
357
-				return basename($on['chemin']);
358
-			} else {
359
-				$taille = @getimagesize($on['chemin']);
360
-
361
-				// Si on a déjà demandé un survol directement ($onoff = off)
362
-				// ou qu'on a demandé uniquement le normal ($onoff = on)
363
-				// alors on ne cherche pas du tout le survol ici
364
-				if ($onoff != 'ON') {
365
-					$off = '';
366
-				} else {
367
-					// Sinon, c'est qu'on demande normal ET survol à la fois, donc on cherche maintenant le survol
368
-					$off = quete_logo_objet($id, $objet, 'off');
369
-				}
370
-
371
-				// on retourne une url du type IMG/artonXX?timestamp
372
-				// qui permet de distinguer le changement de logo
373
-				// et placer un expire sur le dossier IMG/
374
-				$res = array(
375
-					$on['chemin'] . ($on['timestamp'] ? "?{$on['timestamp']}" : ''),
376
-					($off ? $off['chemin'] . ($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
377
-					(!$taille ? '' : (' ' . $taille[3]))
378
-				);
379
-				$res['src'] = $res[0];
380
-				$res['logo_on'] = $res[0];
381
-				$res['logo_off'] = $res[1];
382
-				$res['width'] = ($taille ? $taille[0] : '');
383
-				$res['height'] = ($taille ? $taille[1] : '');
384
-
385
-				return $res;
386
-			}
387
-		} else {
388
-			if (defined('_LOGO_RUBRIQUE_DESACTIVER_HERITAGE')) {
389
-				return '';
390
-			} else {
391
-				if ($id_rubrique) {
392
-					$cle_objet = 'id_rubrique';
393
-					$id = $id_rubrique;
394
-					$id_rubrique = 0;
395
-				} else {
396
-					if ($id and $cle_objet == 'id_rubrique') {
397
-						$id = quete_parent($id);
398
-					} else {
399
-						return '';
400
-					}
401
-				}
402
-			}
403
-		}
404
-	}
347
+    include_spip('base/objets');
348
+    $nom = strtolower($onoff);
349
+
350
+    while (1) {
351
+        $objet = objet_type($cle_objet);
352
+
353
+        $on = quete_logo_objet($id, $objet, $nom);
354
+
355
+        if ($on) {
356
+            if ($flag) {
357
+                return basename($on['chemin']);
358
+            } else {
359
+                $taille = @getimagesize($on['chemin']);
360
+
361
+                // Si on a déjà demandé un survol directement ($onoff = off)
362
+                // ou qu'on a demandé uniquement le normal ($onoff = on)
363
+                // alors on ne cherche pas du tout le survol ici
364
+                if ($onoff != 'ON') {
365
+                    $off = '';
366
+                } else {
367
+                    // Sinon, c'est qu'on demande normal ET survol à la fois, donc on cherche maintenant le survol
368
+                    $off = quete_logo_objet($id, $objet, 'off');
369
+                }
370
+
371
+                // on retourne une url du type IMG/artonXX?timestamp
372
+                // qui permet de distinguer le changement de logo
373
+                // et placer un expire sur le dossier IMG/
374
+                $res = array(
375
+                    $on['chemin'] . ($on['timestamp'] ? "?{$on['timestamp']}" : ''),
376
+                    ($off ? $off['chemin'] . ($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
377
+                    (!$taille ? '' : (' ' . $taille[3]))
378
+                );
379
+                $res['src'] = $res[0];
380
+                $res['logo_on'] = $res[0];
381
+                $res['logo_off'] = $res[1];
382
+                $res['width'] = ($taille ? $taille[0] : '');
383
+                $res['height'] = ($taille ? $taille[1] : '');
384
+
385
+                return $res;
386
+            }
387
+        } else {
388
+            if (defined('_LOGO_RUBRIQUE_DESACTIVER_HERITAGE')) {
389
+                return '';
390
+            } else {
391
+                if ($id_rubrique) {
392
+                    $cle_objet = 'id_rubrique';
393
+                    $id = $id_rubrique;
394
+                    $id_rubrique = 0;
395
+                } else {
396
+                    if ($id and $cle_objet == 'id_rubrique') {
397
+                        $id = quete_parent($id);
398
+                    } else {
399
+                        return '';
400
+                    }
401
+                }
402
+            }
403
+        }
404
+    }
405 405
 }
406 406
 
407 407
 /**
@@ -415,37 +415,37 @@  discard block
 block discarded – undo
415 415
  * 		"on" ou "off" suivant le logo normal ou survol
416 416
  **/
417 417
 function quete_logo_objet($id_objet, $objet, $mode) {
418
-	static $chercher_logo;
419
-	if (is_null($chercher_logo)) {
420
-		$chercher_logo = charger_fonction('chercher_logo', 'inc');
421
-	}
422
-	$cle_objet = id_table_objet($objet);
423
-
424
-	// On cherche pas la méthode classique
425
-	$infos_logo = $chercher_logo($id_objet, $cle_objet, $mode);
426
-	// Si la méthode classique a trouvé quelque chose, on utilise le nouveau format
427
-	if (!empty($infos_logo)) {
428
-		$infos_logo = array(
429
-			'chemin' => $infos_logo[0],
430
-			'timestamp' => $infos_logo[4],
431
-		);
432
-	}
433
-
434
-	// On passe cette recherche de logo dans un pipeline
435
-	$infos_logo = pipeline(
436
-		'quete_logo_objet',
437
-		array(
438
-			'args' => array(
439
-				'id_objet' => $id_objet,
440
-				'objet' => $objet,
441
-				'cle_objet' => $cle_objet,
442
-				'mode' => $mode,
443
-			),
444
-			'data' => $infos_logo,
445
-		)
446
-	);
447
-
448
-	return $infos_logo;
418
+    static $chercher_logo;
419
+    if (is_null($chercher_logo)) {
420
+        $chercher_logo = charger_fonction('chercher_logo', 'inc');
421
+    }
422
+    $cle_objet = id_table_objet($objet);
423
+
424
+    // On cherche pas la méthode classique
425
+    $infos_logo = $chercher_logo($id_objet, $cle_objet, $mode);
426
+    // Si la méthode classique a trouvé quelque chose, on utilise le nouveau format
427
+    if (!empty($infos_logo)) {
428
+        $infos_logo = array(
429
+            'chemin' => $infos_logo[0],
430
+            'timestamp' => $infos_logo[4],
431
+        );
432
+    }
433
+
434
+    // On passe cette recherche de logo dans un pipeline
435
+    $infos_logo = pipeline(
436
+        'quete_logo_objet',
437
+        array(
438
+            'args' => array(
439
+                'id_objet' => $id_objet,
440
+                'objet' => $objet,
441
+                'cle_objet' => $cle_objet,
442
+                'mode' => $mode,
443
+            ),
444
+            'data' => $infos_logo,
445
+        )
446
+    );
447
+
448
+    return $infos_logo;
449 449
 }
450 450
 
451 451
 /**
@@ -458,24 +458,24 @@  discard block
 block discarded – undo
458 458
  * @return bool|string
459 459
  */
460 460
 function quete_logo_file($row, $connect = null) {
461
-	include_spip('inc/documents');
462
-	$logo = vignette_logo_document($row, $connect);
463
-	if (!$logo) {
464
-		$logo = image_du_document($row, $connect);
465
-	}
466
-	if (!$logo) {
467
-		$f = charger_fonction('vignette', 'inc');
468
-		$logo = $f($row['extension'], false);
469
-	}
470
-	// si c'est une vignette type doc, la renvoyer direct
471
-	if (strcmp($logo, _DIR_PLUGINS) == 0
472
-		or strcmp($logo, _DIR_PLUGINS_DIST) == 0
473
-		or strcmp($logo, _DIR_RACINE . 'prive/') == 0
474
-	) {
475
-		return $logo;
476
-	}
477
-
478
-	return get_spip_doc($logo);
461
+    include_spip('inc/documents');
462
+    $logo = vignette_logo_document($row, $connect);
463
+    if (!$logo) {
464
+        $logo = image_du_document($row, $connect);
465
+    }
466
+    if (!$logo) {
467
+        $f = charger_fonction('vignette', 'inc');
468
+        $logo = $f($row['extension'], false);
469
+    }
470
+    // si c'est une vignette type doc, la renvoyer direct
471
+    if (strcmp($logo, _DIR_PLUGINS) == 0
472
+        or strcmp($logo, _DIR_PLUGINS_DIST) == 0
473
+        or strcmp($logo, _DIR_RACINE . 'prive/') == 0
474
+    ) {
475
+        return $logo;
476
+    }
477
+
478
+    return get_spip_doc($logo);
479 479
 }
480 480
 
481 481
 /**
@@ -503,20 +503,20 @@  discard block
 block discarded – undo
503 503
  */
504 504
 function quete_logo_document($row, $lien, $align, $mode_logo, $x, $y, $connect = null) {
505 505
 
506
-	include_spip('inc/documents');
507
-	$logo = '';
508
-	if (!in_array($mode_logo, array('icone', 'apercu'))) {
509
-		$logo = vignette_logo_document($row, $connect);
510
-	}
511
-	// si on veut explicitement la vignette, ne rien renvoyer si il n'y en a pas
512
-	if ($mode_logo == 'vignette' and !$logo) {
513
-		return '';
514
-	}
515
-	if ($mode_logo == 'icone') {
516
-		$row['fichier'] = '';
517
-	}
518
-
519
-	return vignette_automatique($logo, $row, $lien, $x, $y, $align, null, $connect);
506
+    include_spip('inc/documents');
507
+    $logo = '';
508
+    if (!in_array($mode_logo, array('icone', 'apercu'))) {
509
+        $logo = vignette_logo_document($row, $connect);
510
+    }
511
+    // si on veut explicitement la vignette, ne rien renvoyer si il n'y en a pas
512
+    if ($mode_logo == 'vignette' and !$logo) {
513
+        return '';
514
+    }
515
+    if ($mode_logo == 'icone') {
516
+        $row['fichier'] = '';
517
+    }
518
+
519
+    return vignette_automatique($logo, $row, $lien, $x, $y, $align, null, $connect);
520 520
 }
521 521
 
522 522
 /**
@@ -530,14 +530,14 @@  discard block
 block discarded – undo
530 530
  * @return string|false
531 531
  */
532 532
 function document_spip_externe($fichier, $connect) {
533
-	if ($connect) {
534
-		$site = quete_meta('adresse_site', $connect);
535
-		if ($site) {
536
-			$dir = quete_meta('dir_img', $connect);
537
-			return "$site/$dir$fichier";
538
-		}
539
-	}
540
-	return false;
533
+    if ($connect) {
534
+        $site = quete_meta('adresse_site', $connect);
535
+        if ($site) {
536
+            $dir = quete_meta('dir_img', $connect);
537
+            return "$site/$dir$fichier";
538
+        }
539
+    }
540
+    return false;
541 541
 }
542 542
 
543 543
 /**
@@ -550,23 +550,23 @@  discard block
 block discarded – undo
550 550
  * @return string
551 551
  */
552 552
 function vignette_logo_document($row, $connect = '') {
553
-	if (!$row['id_vignette']) {
554
-		return '';
555
-	}
556
-	$fichier = quete_fichier($row['id_vignette'], $connect);
557
-	if ($url = document_spip_externe($fichier, $connect)) {
558
-		return $url;
559
-	}
560
-
561
-	$f = get_spip_doc($fichier);
562
-	if ($f and @file_exists($f)) {
563
-		return $f;
564
-	}
565
-	if ($row['mode'] !== 'vignette') {
566
-		return '';
567
-	}
568
-
569
-	return generer_url_entite($row['id_document'], 'document', '', '', $connect);
553
+    if (!$row['id_vignette']) {
554
+        return '';
555
+    }
556
+    $fichier = quete_fichier($row['id_vignette'], $connect);
557
+    if ($url = document_spip_externe($fichier, $connect)) {
558
+        return $url;
559
+    }
560
+
561
+    $f = get_spip_doc($fichier);
562
+    if ($f and @file_exists($f)) {
563
+        return $f;
564
+    }
565
+    if ($row['mode'] !== 'vignette') {
566
+        return '';
567
+    }
568
+
569
+    return generer_url_entite($row['id_document'], 'document', '', '', $connect);
570 570
 }
571 571
 
572 572
 /**
@@ -582,68 +582,68 @@  discard block
 block discarded – undo
582 582
  * @return bool|string
583 583
  */
584 584
 function calcul_exposer($id, $prim, $reference, $parent, $type, $connect = '') {
585
-	static $exposer = array();
586
-
587
-	// Que faut-il exposer ? Tous les elements de $reference
588
-	// ainsi que leur hierarchie ; on ne fait donc ce calcul
589
-	// qu'une fois (par squelette) et on conserve le resultat
590
-	// en static.
591
-	if (!isset($exposer[$m = md5(serialize($reference))][$prim])) {
592
-		$principal = isset($reference[$type]) ? $reference[$type] :
593
-			// cas de la pagination indecte @xx qui positionne la page avec l'id xx
594
-			// et donne la reference dynamique @type=xx dans le contexte
595
-			(isset($reference["@$type"]) ? $reference["@$type"] : '');
596
-		// le parent fournit en argument est le parent de $id, pas celui de $principal
597
-		// il n'est donc pas utile
598
-		$parent = 0;
599
-		if (!$principal) { // regarder si un enfant est dans le contexte, auquel cas il expose peut etre le parent courant
600
-			$enfants = array('id_rubrique' => array('id_article'), 'id_groupe' => array('id_mot'));
601
-			if (isset($enfants[$type])) {
602
-				foreach ($enfants[$type] as $t) {
603
-					if (isset($reference[$t])
604
-						// cas de la reference donnee dynamiquement par la pagination
605
-						or isset($reference["@$t"])
606
-					) {
607
-						$type = $t;
608
-						$principal = isset($reference[$type]) ? $reference[$type] : $reference["@$type"];
609
-						continue;
610
-					}
611
-				}
612
-			}
613
-		}
614
-		$exposer[$m][$type] = array();
615
-		if ($principal) {
616
-			$principaux = is_array($principal) ? $principal : array($principal);
617
-			foreach ($principaux as $principal) {
618
-				$exposer[$m][$type][$principal] = true;
619
-				if ($type == 'id_mot') {
620
-					if (!$parent) {
621
-						$parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot=' . intval($principal), '', '', '', '', $connect);
622
-					}
623
-					if ($parent) {
624
-						$exposer[$m]['id_groupe'][$parent] = true;
625
-					}
626
-				} else {
627
-					if ($type != 'id_groupe') {
628
-						if (!$parent) {
629
-							if ($type == 'id_rubrique') {
630
-								$parent = $principal;
631
-							}
632
-							if ($type == 'id_article') {
633
-								$parent = quete_rubrique($principal, $connect);
634
-							}
635
-						}
636
-						do {
637
-							$exposer[$m]['id_rubrique'][$parent] = true;
638
-						} while ($parent = quete_parent($parent, $connect));
639
-					}
640
-				}
641
-			}
642
-		}
643
-	}
644
-
645
-	// And the winner is...
646
-	return isset($exposer[$m][$prim]) ? isset($exposer[$m][$prim][$id]) : '';
585
+    static $exposer = array();
586
+
587
+    // Que faut-il exposer ? Tous les elements de $reference
588
+    // ainsi que leur hierarchie ; on ne fait donc ce calcul
589
+    // qu'une fois (par squelette) et on conserve le resultat
590
+    // en static.
591
+    if (!isset($exposer[$m = md5(serialize($reference))][$prim])) {
592
+        $principal = isset($reference[$type]) ? $reference[$type] :
593
+            // cas de la pagination indecte @xx qui positionne la page avec l'id xx
594
+            // et donne la reference dynamique @type=xx dans le contexte
595
+            (isset($reference["@$type"]) ? $reference["@$type"] : '');
596
+        // le parent fournit en argument est le parent de $id, pas celui de $principal
597
+        // il n'est donc pas utile
598
+        $parent = 0;
599
+        if (!$principal) { // regarder si un enfant est dans le contexte, auquel cas il expose peut etre le parent courant
600
+            $enfants = array('id_rubrique' => array('id_article'), 'id_groupe' => array('id_mot'));
601
+            if (isset($enfants[$type])) {
602
+                foreach ($enfants[$type] as $t) {
603
+                    if (isset($reference[$t])
604
+                        // cas de la reference donnee dynamiquement par la pagination
605
+                        or isset($reference["@$t"])
606
+                    ) {
607
+                        $type = $t;
608
+                        $principal = isset($reference[$type]) ? $reference[$type] : $reference["@$type"];
609
+                        continue;
610
+                    }
611
+                }
612
+            }
613
+        }
614
+        $exposer[$m][$type] = array();
615
+        if ($principal) {
616
+            $principaux = is_array($principal) ? $principal : array($principal);
617
+            foreach ($principaux as $principal) {
618
+                $exposer[$m][$type][$principal] = true;
619
+                if ($type == 'id_mot') {
620
+                    if (!$parent) {
621
+                        $parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot=' . intval($principal), '', '', '', '', $connect);
622
+                    }
623
+                    if ($parent) {
624
+                        $exposer[$m]['id_groupe'][$parent] = true;
625
+                    }
626
+                } else {
627
+                    if ($type != 'id_groupe') {
628
+                        if (!$parent) {
629
+                            if ($type == 'id_rubrique') {
630
+                                $parent = $principal;
631
+                            }
632
+                            if ($type == 'id_article') {
633
+                                $parent = quete_rubrique($principal, $connect);
634
+                            }
635
+                        }
636
+                        do {
637
+                            $exposer[$m]['id_rubrique'][$parent] = true;
638
+                        } while ($parent = quete_parent($parent, $connect));
639
+                    }
640
+                }
641
+            }
642
+        }
643
+    }
644
+
645
+    // And the winner is...
646
+    return isset($exposer[$m][$prim]) ? isset($exposer[$m][$prim][$id]) : '';
647 647
 }
648 648
 
649 649
 /**
@@ -658,21 +658,21 @@  discard block
 block discarded – undo
658 658
  * @return int
659 659
  */
660 660
 function quete_debut_pagination($primary, $valeur, $pas, $iter) {
661
-	// on ne devrait pas arriver ici si la cle primaire est inexistante
662
-	// ou composee, mais verifions
663
-	if (!$primary or preg_match('/[,\s]/', $primary)) {
664
-		return 0;
665
-	}
666
-
667
-	$pos = 0;
668
-	while ($row = $iter->fetch() and $row[$primary] != $valeur) {
669
-		$pos++;
670
-	}
671
-	// si on a pas trouve
672
-	if ($row[$primary] != $valeur) {
673
-		return 0;
674
-	}
675
-
676
-	// sinon, calculer le bon numero de page
677
-	return floor($pos / $pas) * $pas;
661
+    // on ne devrait pas arriver ici si la cle primaire est inexistante
662
+    // ou composee, mais verifions
663
+    if (!$primary or preg_match('/[,\s]/', $primary)) {
664
+        return 0;
665
+    }
666
+
667
+    $pos = 0;
668
+    while ($row = $iter->fetch() and $row[$primary] != $valeur) {
669
+        $pos++;
670
+    }
671
+    // si on a pas trouve
672
+    if ($row[$primary] != $valeur) {
673
+        return 0;
674
+    }
675
+
676
+    // sinon, calculer le bon numero de page
677
+    return floor($pos / $pas) * $pas;
678 678
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -18 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	return sql_getfetsel(
37 37
 		'virtuel',
38 38
 		'spip_articles',
39
-		array('id_article=' . intval($id_article), "statut='publie'"),
39
+		array('id_article='.intval($id_article), "statut='publie'"),
40 40
 		'',
41 41
 		'',
42 42
 		'',
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 			$cache_quete[$connect][$table][$id] = sql_fetsel(
79 79
 				$cache_quete[$connect][$table]['_select'],
80 80
 				$table,
81
-				$cache_quete[$connect][$table]['_id'] . '=' . intval($id),
81
+				$cache_quete[$connect][$table]['_id'].'='.intval($id),
82 82
 				'',
83 83
 				'',
84 84
 				'',
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 	return
172 172
 		(isset($GLOBALS['meta']['date_prochain_postdate'])
173 173
 			and $GLOBALS['meta']['date_prochain_postdate'] > time())
174
-			? "$champ_date<" . sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
174
+			? "$champ_date<".sql_quote(date('Y-m-d H:i:s', $GLOBALS['meta']['date_prochain_postdate']), $serveur)
175 175
 			: '1=1';
176 176
 }
177 177
 
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 				and $id_table = reset($objet)
230 230
 				and $objet = objet_type($id_table)
231 231
 			) {
232
-				$w = "$mstatut<>" . sql_quote($v);
232
+				$w = "$mstatut<>".sql_quote($v);
233 233
 
234 234
 				// retrouver l’id_auteur qui a filé un lien de prévisu éventuellement,
235 235
 				// sinon l’auteur en session
@@ -243,22 +243,22 @@  discard block
 block discarded – undo
243 243
 				}
244 244
 
245 245
 				// dans ce cas (admin en general), pas de filtrage sur ce statut
246
-				if (!autoriser('previsualiser' . $v, $objet, '', $id_auteur)) {
246
+				if (!autoriser('previsualiser'.$v, $objet, '', $id_auteur)) {
247 247
 					// si pas d'auteur identifie pas de sous-requete car pas d'article qui matche
248 248
 					if (!$id_auteur) {
249 249
 						$where[] = $w;
250 250
 					} else {
251 251
 						$primary = id_table_objet($objet);
252
-						$where[] = "($w OR $id_table.$primary IN (" . sql_get_select(
252
+						$where[] = "($w OR $id_table.$primary IN (".sql_get_select(
253 253
 								'ssss.id_objet',
254 254
 								'spip_auteurs_liens AS ssss',
255
-								'ssss.objet=' . sql_quote($objet) . ' AND ssss.id_auteur=' . intval($id_auteur),
255
+								'ssss.objet='.sql_quote($objet).' AND ssss.id_auteur='.intval($id_auteur),
256 256
 								'',
257 257
 								'',
258 258
 								'',
259 259
 								'',
260 260
 								$serveur
261
-							) . '))';
261
+							).'))';
262 262
 					}
263 263
 				}
264 264
 			} // ignorer ce statut si on ne sait pas comment le filtrer
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
  * @return array|bool|null
297 297
  */
298 298
 function quete_fichier($id_document, $serveur = '') {
299
-	return sql_getfetsel('fichier', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
299
+	return sql_getfetsel('fichier', 'spip_documents', ('id_document='.intval($id_document)), '', array(), '', '', $serveur);
300 300
 }
301 301
 
302 302
 /**
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
  * @return array|bool
308 308
  */
309 309
 function quete_document($id_document, $serveur = '') {
310
-	return sql_fetsel('*', 'spip_documents', ('id_document=' . intval($id_document)), '', array(), '', '', $serveur);
310
+	return sql_fetsel('*', 'spip_documents', ('id_document='.intval($id_document)), '', array(), '', '', $serveur);
311 311
 }
312 312
 
313 313
 /**
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
  * @return array|bool|null
319 319
  */
320 320
 function quete_meta($nom, $serveur) {
321
-	return sql_getfetsel('valeur', 'spip_meta', 'nom=' . sql_quote($nom), '', '', '', '', $serveur);
321
+	return sql_getfetsel('valeur', 'spip_meta', 'nom='.sql_quote($nom), '', '', '', '', $serveur);
322 322
 }
323 323
 
324 324
 /**
@@ -372,9 +372,9 @@  discard block
 block discarded – undo
372 372
 				// qui permet de distinguer le changement de logo
373 373
 				// et placer un expire sur le dossier IMG/
374 374
 				$res = array(
375
-					$on['chemin'] . ($on['timestamp'] ? "?{$on['timestamp']}" : ''),
376
-					($off ? $off['chemin'] . ($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
377
-					(!$taille ? '' : (' ' . $taille[3]))
375
+					$on['chemin'].($on['timestamp'] ? "?{$on['timestamp']}" : ''),
376
+					($off ? $off['chemin'].($off['timestamp'] ? "?{$off['timestamp']}" : '') : ''),
377
+					(!$taille ? '' : (' '.$taille[3]))
378 378
 				);
379 379
 				$res['src'] = $res[0];
380 380
 				$res['logo_on'] = $res[0];
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 	// si c'est une vignette type doc, la renvoyer direct
471 471
 	if (strcmp($logo, _DIR_PLUGINS) == 0
472 472
 		or strcmp($logo, _DIR_PLUGINS_DIST) == 0
473
-		or strcmp($logo, _DIR_RACINE . 'prive/') == 0
473
+		or strcmp($logo, _DIR_RACINE.'prive/') == 0
474 474
 	) {
475 475
 		return $logo;
476 476
 	}
@@ -589,8 +589,7 @@  discard block
 block discarded – undo
589 589
 	// qu'une fois (par squelette) et on conserve le resultat
590 590
 	// en static.
591 591
 	if (!isset($exposer[$m = md5(serialize($reference))][$prim])) {
592
-		$principal = isset($reference[$type]) ? $reference[$type] :
593
-			// cas de la pagination indecte @xx qui positionne la page avec l'id xx
592
+		$principal = isset($reference[$type]) ? $reference[$type] : // cas de la pagination indecte @xx qui positionne la page avec l'id xx
594 593
 			// et donne la reference dynamique @type=xx dans le contexte
595 594
 			(isset($reference["@$type"]) ? $reference["@$type"] : '');
596 595
 		// le parent fournit en argument est le parent de $id, pas celui de $principal
@@ -618,7 +617,7 @@  discard block
 block discarded – undo
618 617
 				$exposer[$m][$type][$principal] = true;
619 618
 				if ($type == 'id_mot') {
620 619
 					if (!$parent) {
621
-						$parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot=' . intval($principal), '', '', '', '', $connect);
620
+						$parent = sql_getfetsel('id_groupe', 'spip_mots', 'id_mot='.intval($principal), '', '', '', '', $connect);
622 621
 					}
623 622
 					if ($parent) {
624 623
 						$exposer[$m]['id_groupe'][$parent] = true;
Please login to merge, or discard this patch.
config/ecran_securite.php 3 patches
Braces   +80 added lines, -46 removed lines patch added patch discarded remove patch
@@ -14,8 +14,9 @@  discard block
 block discarded – undo
14 14
 /*
15 15
  * Test utilisateur
16 16
  */
17
-if (isset($_GET['test_ecran_securite']))
17
+if (isset($_GET['test_ecran_securite'])) {
18 18
 	$ecran_securite_raison = 'test '._ECRAN_SECURITE;
19
+}
19 20
 
20 21
 /*
21 22
  * Monitoring
@@ -60,18 +61,21 @@  discard block
 block discarded – undo
60 61
  * (sauf pour id_table, qui n'est pas numérique jusqu'à [5743])
61 62
  * (id_base est une variable de la config des widgets de WordPress)
62 63
  */
63
-foreach ($_GET as $var => $val)
64
+foreach ($_GET as $var => $val) {
64 65
 	if ($_GET[$var] and strncmp($var, "id_", 3) == 0
65 66
 	and !in_array($var, array('id_table', 'id_base')))
66 67
 		$_GET[$var] = is_array($_GET[$var])?@array_map('intval', $_GET[$var]):intval($_GET[$var]);
67
-foreach ($_POST as $var => $val)
68
+}
69
+foreach ($_POST as $var => $val) {
68 70
 	if ($_POST[$var] and strncmp($var, "id_", 3) == 0
69 71
 	and !in_array($var, array('id_table', 'id_base')))
70 72
 		$_POST[$var] = is_array($_POST[$var])?@array_map('intval', $_POST[$var]):intval($_POST[$var]);
71
-foreach ($GLOBALS as $var => $val)
73
+}
74
+foreach ($GLOBALS as $var => $val) {
72 75
 	if ($GLOBALS[$var] and strncmp($var, "id_", 3) == 0
73 76
 	and !in_array($var, array('id_table', 'id_base')))
74 77
 		$GLOBALS[$var] = is_array($GLOBALS[$var])?@array_map('intval', $GLOBALS[$var]):intval($GLOBALS[$var]);
78
+}
75 79
 
76 80
 /*
77 81
  * Interdit la variable $cjpeg_command, qui était utilisée sans
@@ -83,11 +87,13 @@  discard block
 block discarded – undo
83 87
  * Contrôle de quelques variables (XSS)
84 88
  */
85 89
 foreach(array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
86
-	if (isset($_GET[$var]))
87
-		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
88
-	if (isset($_POST[$var]))
89
-		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
90
-}
90
+	if (isset($_GET[$var])) {
91
+			$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
92
+	}
93
+	if (isset($_POST[$var])) {
94
+			$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
95
+	}
96
+	}
91 97
 
92 98
 /*
93 99
  * Filtre l'accès à spip_acces_doc (injection SQL en 1.8.2x)
@@ -101,41 +107,49 @@  discard block
 block discarded – undo
101 107
  */
102 108
 if (isset($_REQUEST['mode']) and isset($_REQUEST['page'])
103 109
 and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
104
-and $_REQUEST['page'] == "identifiants")
110
+and $_REQUEST['page'] == "identifiants") {
105 111
 	$ecran_securite_raison = "identifiants";
112
+}
106 113
 
107 114
 /*
108 115
  * Agenda joue à l'injection php
109 116
  */
110 117
 if (isset($_REQUEST['partie_cal'])
111
-and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal']))
118
+and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal'])) {
112 119
 	$ecran_securite_raison = "partie_cal";
120
+}
113 121
 if (isset($_REQUEST['echelle'])
114
-and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle']))
122
+and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle'])) {
115 123
 	$ecran_securite_raison = "echelle";
124
+}
116 125
 
117 126
 /*
118 127
  * Espace privé
119 128
  */
120 129
 if (isset($_REQUEST['exec'])
121
-and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec']))
130
+and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec'])) {
122 131
 	$ecran_securite_raison = "exec";
132
+}
123 133
 if (isset($_REQUEST['cherche_auteur'])
124
-and preg_match(',[<],', (string)$_REQUEST['cherche_auteur']))
134
+and preg_match(',[<],', (string)$_REQUEST['cherche_auteur'])) {
125 135
 	$ecran_securite_raison = "cherche_auteur";
136
+}
126 137
 if (isset($_REQUEST['exec'])
127 138
 and $_REQUEST['exec'] == 'auteurs'
128
-and preg_match(',[<],', (string)$_REQUEST['recherche']))
139
+and preg_match(',[<],', (string)$_REQUEST['recherche'])) {
129 140
 	$ecran_securite_raison = "recherche";
141
+}
130 142
 if (isset($_REQUEST['exec'])
131 143
 and $_REQUEST['exec'] == 'info_plugin'
132
-and preg_match(',[<],', (string)$_REQUEST['plugin']))
144
+and preg_match(',[<],', (string)$_REQUEST['plugin'])) {
133 145
 	$ecran_securite_raison = "plugin";
146
+}
134 147
 if (isset($_REQUEST['exec'])
135 148
 and $_REQUEST['exec'] == 'puce_statut'
136 149
 and isset($_REQUEST['id'])
137
-and !intval($_REQUEST['id']))
150
+and !intval($_REQUEST['id'])) {
138 151
 	$ecran_securite_raison = "puce_statut";
152
+}
139 153
 if (isset($_REQUEST['action'])
140 154
 and $_REQUEST['action'] == 'configurer') {
141 155
 	if (@file_exists('inc_version.php')
@@ -160,21 +174,24 @@  discard block
 block discarded – undo
160 174
 	@get_magic_quotes_gpc() ?
161 175
 		stripslashes(serialize($_REQUEST)) : serialize($_REQUEST),
162 176
 	chr(0)
163
-) !== false)
177
+) !== false) {
164 178
 	$ecran_securite_raison = "%00";
179
+}
165 180
 
166 181
 /*
167 182
  * Bloque les requêtes fond=formulaire_
168 183
  */
169 184
 if (isset($_REQUEST['fond'])
170
-and preg_match(',^formulaire_,i', $_REQUEST['fond']))
185
+and preg_match(',^formulaire_,i', $_REQUEST['fond'])) {
171 186
 	$ecran_securite_raison = "fond=formulaire_";
187
+}
172 188
 
173 189
 /*
174 190
  * Bloque les requêtes du type ?GLOBALS[type_urls]=toto (bug vieux php)
175 191
  */
176
-if (isset($_REQUEST['GLOBALS']))
192
+if (isset($_REQUEST['GLOBALS'])) {
177 193
 	$ecran_securite_raison = "GLOBALS[GLOBALS]";
194
+}
178 195
 
179 196
 /*
180 197
  * Bloque les requêtes des bots sur:
@@ -185,29 +202,34 @@  discard block
 block discarded – undo
185 202
 	(isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
186 203
 	or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
187 204
 )
188
-)
205
+) {
189 206
 	$ecran_securite_raison = "robot agenda/double pagination";
207
+}
190 208
 
191 209
 /*
192 210
  * Bloque une vieille page de tests de CFG (<1.11)
193 211
  * Bloque un XSS sur une page inexistante
194 212
  */
195 213
 if (isset($_REQUEST['page'])) {
196
-	if ($_REQUEST['page'] == 'test_cfg')
197
-		$ecran_securite_raison = "test_cfg";
198
-	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page']))
199
-		$ecran_securite_raison = "xsspage";
214
+	if ($_REQUEST['page'] == 'test_cfg') {
215
+			$ecran_securite_raison = "test_cfg";
216
+	}
217
+	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page'])) {
218
+			$ecran_securite_raison = "xsspage";
219
+	}
200 220
 	if ($_REQUEST['page'] == '404'
201
-	and isset($_REQUEST['erreur']))
202
-		$ecran_securite_raison = "xss404";
203
-}
221
+	and isset($_REQUEST['erreur'])) {
222
+			$ecran_securite_raison = "xss404";
223
+	}
224
+	}
204 225
 
205 226
 /*
206 227
  * XSS par array
207 228
  */
208
-foreach (array('var_login') as $var)
209
-if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var]))
229
+foreach (array('var_login') as $var) {
230
+    if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var]))
210 231
 	$ecran_securite_raison = "xss ".$var;
232
+}
211 233
 
212 234
 /*
213 235
  * Parade antivirale contre un cheval de troie
@@ -217,18 +239,21 @@  discard block
 block discarded – undo
217 239
 	function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
218 240
 		// si jamais on est arrivé ici sur une erreur php
219 241
 		// et qu'un autre gestionnaire d'erreur est défini, l'appeller
220
-		if ($b && $GLOBALS['tmp_xhgfjokl'])
221
-			call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
242
+		if ($b && $GLOBALS['tmp_xhgfjokl']) {
243
+					call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
244
+		}
222 245
 	}
223 246
 }
224
-if (isset($_POST['tmp_lkojfghx3']))
247
+if (isset($_POST['tmp_lkojfghx3'])) {
225 248
 	$ecran_securite_raison = "gumblar";
249
+}
226 250
 
227 251
 /*
228 252
  * Outils XML mal sécurisés < 2.0.9
229 253
  */
230
-if (isset($_REQUEST['transformer_xml']))
254
+if (isset($_REQUEST['transformer_xml'])) {
231 255
 	$ecran_securite_raison = "transformer_xml";
256
+}
232 257
 
233 258
 /*
234 259
  * Outils XML mal sécurisés again
@@ -246,11 +271,13 @@  discard block
 block discarded – undo
246 271
  * Sauvegarde mal securisée < 2.0.9
247 272
  */
248 273
 if (isset($_REQUEST['nom_sauvegarde'])
249
-and strstr((string)$_REQUEST['nom_sauvegarde'], '/'))
274
+and strstr((string)$_REQUEST['nom_sauvegarde'], '/')) {
250 275
 	$ecran_securite_raison = 'nom_sauvegarde manipulee';
276
+}
251 277
 if (isset($_REQUEST['znom_sauvegarde'])
252
-and strstr((string)$_REQUEST['znom_sauvegarde'], '/'))
278
+and strstr((string)$_REQUEST['znom_sauvegarde'], '/')) {
253 279
 	$ecran_securite_raison = 'znom_sauvegarde manipulee';
280
+}
254 281
 
255 282
 
256 283
 /*
@@ -258,8 +285,9 @@  discard block
 block discarded – undo
258 285
  * on vérifie 'page' pour ne pas bloquer ... drupal
259 286
  */
260 287
 if (isset($_REQUEST['op']) and isset($_REQUEST['page'])
261
-and $_REQUEST['op'] !== preg_replace('/[^\-\w]/', '', $_REQUEST['op']))
288
+and $_REQUEST['op'] !== preg_replace('/[^\-\w]/', '', $_REQUEST['op'])) {
262 289
 	$ecran_securite_raison = 'op';
290
+}
263 291
 
264 292
 /*
265 293
  * Forms & Table ne se méfiait pas assez des uploads de fichiers
@@ -267,8 +295,9 @@  discard block
 block discarded – undo
267 295
 if (count($_FILES)){
268 296
 	foreach($_FILES as $k => $v){
269 297
 		 if (preg_match(',^fichier_\d+$,', $k)
270
-		 and preg_match(',\.php,i', $v['name']))
271
-		 	unset($_FILES[$k]);
298
+		 and preg_match(',\.php,i', $v['name'])) {
299
+		 		 	unset($_FILES[$k]);
300
+		 }
272 301
 	}
273 302
 }
274 303
 /*
@@ -285,21 +314,24 @@  discard block
 block discarded – undo
285 314
  * reinstall=oui un peu trop permissif
286 315
  */
287 316
 if (isset($_REQUEST['reinstall'])
288
-and $_REQUEST['reinstall'] == 'oui')
317
+and $_REQUEST['reinstall'] == 'oui') {
289 318
 	$ecran_securite_raison = 'reinstall=oui';
319
+}
290 320
 
291 321
 /*
292 322
  * Échappement xss referer
293 323
  */
294
-if (isset($_SERVER['HTTP_REFERER']))
324
+if (isset($_SERVER['HTTP_REFERER'])) {
295 325
 	$_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
326
+}
296 327
 
297 328
 
298 329
 /*
299 330
  * Echappement HTTP_X_FORWARDED_HOST
300 331
  */
301
-if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
332
+if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
302 333
 	$_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
334
+}
303 335
 
304 336
 
305 337
 /*
@@ -307,9 +339,10 @@  discard block
 block discarded – undo
307 339
  */
308 340
 if (strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false){
309 341
 	$zzzz = implode("", array_keys($_REQUEST));
310
-	if (strlen($zzzz) != strcspn($zzzz, '<>"\''))
311
-		$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
312
-}
342
+	if (strlen($zzzz) != strcspn($zzzz, '<>"\'')) {
343
+			$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
344
+	}
345
+	}
313 346
 
314 347
 /*
315 348
  * Injection par connect
@@ -358,8 +391,9 @@  discard block
 block discarded – undo
358 391
 /*
359 392
  * Bloque les bots quand le load déborde
360 393
  */
361
-if (!defined('_ECRAN_SECURITE_LOAD'))
394
+if (!defined('_ECRAN_SECURITE_LOAD')) {
362 395
 	define('_ECRAN_SECURITE_LOAD', 4);
396
+}
363 397
 
364 398
 if (
365 399
 	defined('_ECRAN_SECURITE_LOAD')
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -23,18 +23,18 @@  discard block
 block discarded – undo
23 23
  * var_isbot=1 peut etre utilise pour monitorer la disponibilite pour les bots (sujets a 503 de delestage si
24 24
  * le load depasse ECRAN_SECURITE_LOAD)
25 25
  */
26
-if (!defined('_IS_BOT') and isset($_GET['var_isbot'])){
26
+if (!defined('_IS_BOT') and isset($_GET['var_isbot'])) {
27 27
 	define('_IS_BOT', $_GET['var_isbot'] ? true : false);
28 28
 }
29 29
 
30 30
 /*
31 31
  * Détecteur de robot d'indexation
32 32
  */
33
-if (!defined('_IS_BOT')){
33
+if (!defined('_IS_BOT')) {
34 34
 	define('_IS_BOT',
35 35
 		isset($_SERVER['HTTP_USER_AGENT'])
36 36
 		and preg_match(','
37
-		. implode ('|', array(
37
+		. implode('|', array(
38 38
 			// mots generiques
39 39
 			'bot',
40 40
 			'slurp',
@@ -175,18 +175,18 @@  discard block
 block discarded – undo
175 175
 			'yats',
176 176
 			'yeti',
177 177
 			'zeerch'
178
-		)) . ',i',
179
-		(string)$_SERVER['HTTP_USER_AGENT'])
178
+		)).',i',
179
+		(string) $_SERVER['HTTP_USER_AGENT'])
180 180
 	);
181 181
 }
182
-if (!defined('_IS_BOT_FRIEND')){
182
+if (!defined('_IS_BOT_FRIEND')) {
183 183
 	define('_IS_BOT_FRIEND',
184 184
 		isset($_SERVER['HTTP_USER_AGENT'])
185
-		and preg_match(',' . implode ('|', array(
185
+		and preg_match(','.implode('|', array(
186 186
 			'facebookexternalhit',
187 187
 			'flipboardproxy'
188
-		)) . ',i',
189
-		(string)$_SERVER['HTTP_USER_AGENT'])
188
+		)).',i',
189
+		(string) $_SERVER['HTTP_USER_AGENT'])
190 190
 	);
191 191
 }
192 192
 
@@ -200,15 +200,15 @@  discard block
 block discarded – undo
200 200
 foreach ($_GET as $var => $val)
201 201
 	if ($_GET[$var] and strncmp($var, "id_", 3) == 0
202 202
 	and !in_array($var, array('id_table', 'id_base')))
203
-		$_GET[$var] = is_array($_GET[$var])?@array_map('intval', $_GET[$var]):intval($_GET[$var]);
203
+		$_GET[$var] = is_array($_GET[$var]) ? @array_map('intval', $_GET[$var]) : intval($_GET[$var]);
204 204
 foreach ($_POST as $var => $val)
205 205
 	if ($_POST[$var] and strncmp($var, "id_", 3) == 0
206 206
 	and !in_array($var, array('id_table', 'id_base')))
207
-		$_POST[$var] = is_array($_POST[$var])?@array_map('intval', $_POST[$var]):intval($_POST[$var]);
207
+		$_POST[$var] = is_array($_POST[$var]) ? @array_map('intval', $_POST[$var]) : intval($_POST[$var]);
208 208
 foreach ($GLOBALS as $var => $val)
209 209
 	if ($GLOBALS[$var] and strncmp($var, "id_", 3) == 0
210 210
 	and !in_array($var, array('id_table', 'id_base')))
211
-		$GLOBALS[$var] = is_array($GLOBALS[$var])?@array_map('intval', $GLOBALS[$var]):intval($GLOBALS[$var]);
211
+		$GLOBALS[$var] = is_array($GLOBALS[$var]) ? @array_map('intval', $GLOBALS[$var]) : intval($GLOBALS[$var]);
212 212
 
213 213
 /*
214 214
  * Interdit la variable $cjpeg_command, qui était utilisée sans
@@ -219,18 +219,18 @@  discard block
 block discarded – undo
219 219
 /*
220 220
  * Contrôle de quelques variables (XSS)
221 221
  */
222
-foreach(array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
222
+foreach (array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
223 223
 	if (isset($_GET[$var]))
224
-		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
224
+		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string) $_GET[$var]);
225 225
 	if (isset($_POST[$var]))
226
-		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
226
+		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string) $_POST[$var]);
227 227
 }
228 228
 
229 229
 /*
230 230
  * Filtre l'accès à spip_acces_doc (injection SQL en 1.8.2x)
231 231
  */
232
-if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
233
-	$file = addslashes((string)$_GET['file']);
232
+if (preg_match(',^(.*/)?spip_acces_doc\.,', (string) $_SERVER['REQUEST_URI'])) {
233
+	$file = addslashes((string) $_GET['file']);
234 234
 }
235 235
 
236 236
 /*
@@ -245,28 +245,28 @@  discard block
 block discarded – undo
245 245
  * Agenda joue à l'injection php
246 246
  */
247 247
 if (isset($_REQUEST['partie_cal'])
248
-and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal']))
248
+and $_REQUEST['partie_cal'] !== htmlentities((string) $_REQUEST['partie_cal']))
249 249
 	$ecran_securite_raison = "partie_cal";
250 250
 if (isset($_REQUEST['echelle'])
251
-and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle']))
251
+and $_REQUEST['echelle'] !== htmlentities((string) $_REQUEST['echelle']))
252 252
 	$ecran_securite_raison = "echelle";
253 253
 
254 254
 /*
255 255
  * Espace privé
256 256
  */
257 257
 if (isset($_REQUEST['exec'])
258
-and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec']))
258
+and !preg_match(',^[\w-]+$,', (string) $_REQUEST['exec']))
259 259
 	$ecran_securite_raison = "exec";
260 260
 if (isset($_REQUEST['cherche_auteur'])
261
-and preg_match(',[<],', (string)$_REQUEST['cherche_auteur']))
261
+and preg_match(',[<],', (string) $_REQUEST['cherche_auteur']))
262 262
 	$ecran_securite_raison = "cherche_auteur";
263 263
 if (isset($_REQUEST['exec'])
264 264
 and $_REQUEST['exec'] == 'auteurs'
265
-and preg_match(',[<],', (string)$_REQUEST['recherche']))
265
+and preg_match(',[<],', (string) $_REQUEST['recherche']))
266 266
 	$ecran_securite_raison = "recherche";
267 267
 if (isset($_REQUEST['exec'])
268 268
 and $_REQUEST['exec'] == 'info_plugin'
269
-and preg_match(',[<],', (string)$_REQUEST['plugin']))
269
+and preg_match(',[<],', (string) $_REQUEST['plugin']))
270 270
 	$ecran_securite_raison = "plugin";
271 271
 if (isset($_REQUEST['exec'])
272 272
 and $_REQUEST['exec'] == 'puce_statut'
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 	or @file_exists('ecrire/inc_version.php')) {
280 280
 		function action_configurer() {
281 281
 			include_spip('inc/autoriser');
282
-			if(!autoriser('configurer', _request('configuration'))) {
282
+			if (!autoriser('configurer', _request('configuration'))) {
283 283
 				include_spip('inc/minipres');
284 284
 				echo minipres(_T('info_acces_interdit'));
285 285
 				exit;
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
  */
321 321
 if (_IS_BOT and (
322 322
 	(isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
323
-	or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
323
+	or (strpos((string) $_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string) $_SERVER['REQUEST_URI']))
324 324
 )
325 325
 )
326 326
 	$ecran_securite_raison = "robot agenda/double pagination";
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 if (isset($_REQUEST['page'])) {
333 333
 	if ($_REQUEST['page'] == 'test_cfg')
334 334
 		$ecran_securite_raison = "test_cfg";
335
-	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page']))
335
+	if ($_REQUEST['page'] !== htmlspecialchars((string) $_REQUEST['page']))
336 336
 		$ecran_securite_raison = "xsspage";
337 337
 	if ($_REQUEST['page'] == '404'
338 338
 	and isset($_REQUEST['erreur']))
@@ -370,12 +370,12 @@  discard block
 block discarded – undo
370 370
 /*
371 371
  * Outils XML mal sécurisés again
372 372
  */
373
-if (isset($_REQUEST['var_url']) and $_REQUEST['var_url'] and isset($_REQUEST['exec']) and $_REQUEST['exec']=='valider_xml'){
373
+if (isset($_REQUEST['var_url']) and $_REQUEST['var_url'] and isset($_REQUEST['exec']) and $_REQUEST['exec'] == 'valider_xml') {
374 374
 	$url = trim($_REQUEST['var_url']);
375
-	if (strncmp($url,'/',1)==0
376
-	  or (($p=strpos($url,'..'))!==false AND strpos($url,'..',$p+3)!==false)
377
-	  or (($p=strpos($url,'..'))!==false AND strpos($url,'IMG',$p+3)!==false)
378
-		or (strpos($url,'://')!==false or strpos($url,':\\')!==false)) {
375
+	if (strncmp($url, '/', 1) == 0
376
+	  or (($p = strpos($url, '..')) !== false AND strpos($url, '..', $p + 3) !== false)
377
+	  or (($p = strpos($url, '..')) !== false AND strpos($url, 'IMG', $p + 3) !== false)
378
+		or (strpos($url, '://') !== false or strpos($url, ':\\') !== false)) {
379 379
 		$ecran_securite_raison = 'URL interdite pour var_url';
380 380
 	}
381 381
 }
@@ -384,10 +384,10 @@  discard block
 block discarded – undo
384 384
  * Sauvegarde mal securisée < 2.0.9
385 385
  */
386 386
 if (isset($_REQUEST['nom_sauvegarde'])
387
-and strstr((string)$_REQUEST['nom_sauvegarde'], '/'))
387
+and strstr((string) $_REQUEST['nom_sauvegarde'], '/'))
388 388
 	$ecran_securite_raison = 'nom_sauvegarde manipulee';
389 389
 if (isset($_REQUEST['znom_sauvegarde'])
390
-and strstr((string)$_REQUEST['znom_sauvegarde'], '/'))
390
+and strstr((string) $_REQUEST['znom_sauvegarde'], '/'))
391 391
 	$ecran_securite_raison = 'znom_sauvegarde manipulee';
392 392
 
393 393
 
@@ -402,8 +402,8 @@  discard block
 block discarded – undo
402 402
 /*
403 403
  * Forms & Table ne se méfiait pas assez des uploads de fichiers
404 404
  */
405
-if (count($_FILES)){
406
-	foreach($_FILES as $k => $v){
405
+if (count($_FILES)) {
406
+	foreach ($_FILES as $k => $v) {
407 407
 		 if (preg_match(',^fichier_\d+$,', $k)
408 408
 		 and preg_match(',\.php,i', $v['name']))
409 409
 		 	unset($_FILES[$k]);
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
  * et Contact trop laxiste avec une variable externe
414 414
  * on bloque pas le post pour eviter de perdre des donnees mais on unset la variable et c'est tout
415 415
  */
416
-if (isset($_REQUEST['pj_enregistrees_nom']) and $_REQUEST['pj_enregistrees_nom']){
416
+if (isset($_REQUEST['pj_enregistrees_nom']) and $_REQUEST['pj_enregistrees_nom']) {
417 417
 	unset($_REQUEST['pj_enregistrees_nom']);
418 418
 	unset($_GET['pj_enregistrees_nom']);
419 419
 	unset($_POST['pj_enregistrees_nom']);
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 /*
444 444
  * Réinjection des clés en html dans l'admin r19561
445 445
  */
446
-if (strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false){
446
+if (strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false) {
447 447
 	$zzzz = implode("", array_keys($_REQUEST));
448 448
 	if (strlen($zzzz) != strcspn($zzzz, '<>"\''))
449 449
 		$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
Please login to merge, or discard this patch.
Indentation   +288 added lines, -288 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * Test utilisateur
16 16
  */
17 17
 if (isset($_GET['test_ecran_securite']))
18
-	$ecran_securite_raison = 'test '._ECRAN_SECURITE;
18
+    $ecran_securite_raison = 'test '._ECRAN_SECURITE;
19 19
 
20 20
 /*
21 21
  * Monitoring
@@ -24,170 +24,170 @@  discard block
 block discarded – undo
24 24
  * le load depasse ECRAN_SECURITE_LOAD)
25 25
  */
26 26
 if (!defined('_IS_BOT') and isset($_GET['var_isbot'])){
27
-	define('_IS_BOT', $_GET['var_isbot'] ? true : false);
27
+    define('_IS_BOT', $_GET['var_isbot'] ? true : false);
28 28
 }
29 29
 
30 30
 /*
31 31
  * Détecteur de robot d'indexation
32 32
  */
33 33
 if (!defined('_IS_BOT')){
34
-	define('_IS_BOT',
35
-		isset($_SERVER['HTTP_USER_AGENT'])
36
-		and preg_match(','
37
-		. implode ('|', array(
38
-			// mots generiques
39
-			'bot',
40
-			'slurp',
41
-			'crawler',
42
-			'spider',
43
-			'webvac',
44
-			'yandex',
45
-			'MSIE 6\.0', // botnet 99,9% du temps
46
-			// UA plus cibles 
47
-			'200please',
48
-			'80legs',
49
-			'a6-indexer',
50
-			'aboundex',
51
-			'accoona',
52
-			'addthis',
53
-			'adressendeutschland',
54
-			'alexa',
55
-			'altavista',
56
-			'analyticsseo',
57
-			'archive',
58
-			'aspseek',
59
-			'baidu',
60
-			'begunadvertising',
61
-			'bingpreview',
62
-			'bloglines',
63
-			'browsershots',
64
-			'bubing',
65
-			'butterfly',
66
-			'changedetection',
67
-			'charlotte',
68
-			'chilkat',
69
-			'china',
70
-			'coccoc',
71
-			'crowsnest',
72
-			'dataminr',
73
-			'daumoa',
74
-			'dlweb',
75
-			'ec2linkfinder',
76
-			'estyle',
77
-			'ezooms',
78
-			'facebookexternalhit',
79
-			'facebookplatform',
80
-			'fairshare',
81
-			'feedfetcher',
82
-			'feedfetcher-google',
83
-			'feedly',
84
-			'fetch',
85
-			'flipboardproxy',
86
-			'genieo',
87
-			'google',
88
-			'grapeshot',
89
-			'hatena-useragent',
90
-			'head',
91
-			'hosttracker',
92
-			'hubspot',
93
-			'ia_archiver',
94
-			'ichiro',
95
-			'iltrovatore-setaccio',
96
-			'immediatenet',
97
-			'ina',
98
-			'infegyatlas',
99
-			'infohelfer',
100
-			'instapaper',
101
-			'jabse',
102
-			'james',
103
-			'kumkie',
104
-			'linkdex',
105
-			'linkfluence',
106
-			'linkwalker',
107
-			'litefinder',
108
-			'loadimpactpageanalyzer',
109
-			'luminate',
110
-			'lycos',
111
-			'lycosa',
112
-			'mediapartners-google',
113
-			'msai',
114
-			'najdi',
115
-			'netcraftsurveyagent',
116
-			'netestate',
117
-			'netseer',
118
-			'nuhk',
119
-			'panscient',
120
-			'parsijoo',
121
-			'plukkie',
122
-			'proximic',
123
-			'owlin',
124
-			'qirina',
125
-			'qualidator',
126
-			'rambler',
127
-			'readability',
128
-			'sbsearch',
129
-			'scooter',
130
-			'scrapy',
131
-			'scrubby',
132
-			'scrubbybloglines',
133
-			'shareaholic',
134
-			'shopwiki',
135
-			'sistrix',
136
-			'sitechecker',
137
-			'siteexplorer',
138
-			'sogou',
139
-			'special_archiver',
140
-			'speedy',
141
-			'spinn3r',
142
-			'spreadtrum',
143
-			'steeler',
144
-			'subscriber',
145
-			'suma',
146
-			'superdownloads',
147
-			'svenska-webbsido',
148
-			'teoma',
149
-			'thumbshots',
150
-			'tineye',
151
-			'trendiction',
152
-			'tweetedtimes',
153
-			'tweetmeme',
154
-			'uaslinkchecker',
155
-			'undrip',
156
-			'unwindfetchor',
157
-			'vedma',
158
-			'vkshare',
159
-			'vm',
160
-			'wch',
161
-			'webalta',
162
-			'webcookies',
163
-			'webthumbnail',
164
-			'wesee',
165
-			'wise-guys',
166
-			'woko',
167
-			'wotbox',
168
-			'y!j-bri',
169
-			'y!j-bro',
170
-			'y!j-brw',
171
-			'y!j-bsc',
172
-			'yahoo',
173
-			'yahoo!',
174
-			'yahooysmcm',
175
-			'yats',
176
-			'yeti',
177
-			'zeerch'
178
-		)) . ',i',
179
-		(string)$_SERVER['HTTP_USER_AGENT'])
180
-	);
34
+    define('_IS_BOT',
35
+        isset($_SERVER['HTTP_USER_AGENT'])
36
+        and preg_match(','
37
+        . implode ('|', array(
38
+            // mots generiques
39
+            'bot',
40
+            'slurp',
41
+            'crawler',
42
+            'spider',
43
+            'webvac',
44
+            'yandex',
45
+            'MSIE 6\.0', // botnet 99,9% du temps
46
+            // UA plus cibles 
47
+            '200please',
48
+            '80legs',
49
+            'a6-indexer',
50
+            'aboundex',
51
+            'accoona',
52
+            'addthis',
53
+            'adressendeutschland',
54
+            'alexa',
55
+            'altavista',
56
+            'analyticsseo',
57
+            'archive',
58
+            'aspseek',
59
+            'baidu',
60
+            'begunadvertising',
61
+            'bingpreview',
62
+            'bloglines',
63
+            'browsershots',
64
+            'bubing',
65
+            'butterfly',
66
+            'changedetection',
67
+            'charlotte',
68
+            'chilkat',
69
+            'china',
70
+            'coccoc',
71
+            'crowsnest',
72
+            'dataminr',
73
+            'daumoa',
74
+            'dlweb',
75
+            'ec2linkfinder',
76
+            'estyle',
77
+            'ezooms',
78
+            'facebookexternalhit',
79
+            'facebookplatform',
80
+            'fairshare',
81
+            'feedfetcher',
82
+            'feedfetcher-google',
83
+            'feedly',
84
+            'fetch',
85
+            'flipboardproxy',
86
+            'genieo',
87
+            'google',
88
+            'grapeshot',
89
+            'hatena-useragent',
90
+            'head',
91
+            'hosttracker',
92
+            'hubspot',
93
+            'ia_archiver',
94
+            'ichiro',
95
+            'iltrovatore-setaccio',
96
+            'immediatenet',
97
+            'ina',
98
+            'infegyatlas',
99
+            'infohelfer',
100
+            'instapaper',
101
+            'jabse',
102
+            'james',
103
+            'kumkie',
104
+            'linkdex',
105
+            'linkfluence',
106
+            'linkwalker',
107
+            'litefinder',
108
+            'loadimpactpageanalyzer',
109
+            'luminate',
110
+            'lycos',
111
+            'lycosa',
112
+            'mediapartners-google',
113
+            'msai',
114
+            'najdi',
115
+            'netcraftsurveyagent',
116
+            'netestate',
117
+            'netseer',
118
+            'nuhk',
119
+            'panscient',
120
+            'parsijoo',
121
+            'plukkie',
122
+            'proximic',
123
+            'owlin',
124
+            'qirina',
125
+            'qualidator',
126
+            'rambler',
127
+            'readability',
128
+            'sbsearch',
129
+            'scooter',
130
+            'scrapy',
131
+            'scrubby',
132
+            'scrubbybloglines',
133
+            'shareaholic',
134
+            'shopwiki',
135
+            'sistrix',
136
+            'sitechecker',
137
+            'siteexplorer',
138
+            'sogou',
139
+            'special_archiver',
140
+            'speedy',
141
+            'spinn3r',
142
+            'spreadtrum',
143
+            'steeler',
144
+            'subscriber',
145
+            'suma',
146
+            'superdownloads',
147
+            'svenska-webbsido',
148
+            'teoma',
149
+            'thumbshots',
150
+            'tineye',
151
+            'trendiction',
152
+            'tweetedtimes',
153
+            'tweetmeme',
154
+            'uaslinkchecker',
155
+            'undrip',
156
+            'unwindfetchor',
157
+            'vedma',
158
+            'vkshare',
159
+            'vm',
160
+            'wch',
161
+            'webalta',
162
+            'webcookies',
163
+            'webthumbnail',
164
+            'wesee',
165
+            'wise-guys',
166
+            'woko',
167
+            'wotbox',
168
+            'y!j-bri',
169
+            'y!j-bro',
170
+            'y!j-brw',
171
+            'y!j-bsc',
172
+            'yahoo',
173
+            'yahoo!',
174
+            'yahooysmcm',
175
+            'yats',
176
+            'yeti',
177
+            'zeerch'
178
+        )) . ',i',
179
+        (string)$_SERVER['HTTP_USER_AGENT'])
180
+    );
181 181
 }
182 182
 if (!defined('_IS_BOT_FRIEND')){
183
-	define('_IS_BOT_FRIEND',
184
-		isset($_SERVER['HTTP_USER_AGENT'])
185
-		and preg_match(',' . implode ('|', array(
186
-			'facebookexternalhit',
187
-			'flipboardproxy'
188
-		)) . ',i',
189
-		(string)$_SERVER['HTTP_USER_AGENT'])
190
-	);
183
+    define('_IS_BOT_FRIEND',
184
+        isset($_SERVER['HTTP_USER_AGENT'])
185
+        and preg_match(',' . implode ('|', array(
186
+            'facebookexternalhit',
187
+            'flipboardproxy'
188
+        )) . ',i',
189
+        (string)$_SERVER['HTTP_USER_AGENT'])
190
+    );
191 191
 }
192 192
 
193 193
 /*
@@ -198,17 +198,17 @@  discard block
 block discarded – undo
198 198
  * (id_base est une variable de la config des widgets de WordPress)
199 199
  */
200 200
 foreach ($_GET as $var => $val)
201
-	if ($_GET[$var] and strncmp($var, "id_", 3) == 0
202
-	and !in_array($var, array('id_table', 'id_base')))
203
-		$_GET[$var] = is_array($_GET[$var])?@array_map('intval', $_GET[$var]):intval($_GET[$var]);
201
+    if ($_GET[$var] and strncmp($var, "id_", 3) == 0
202
+    and !in_array($var, array('id_table', 'id_base')))
203
+        $_GET[$var] = is_array($_GET[$var])?@array_map('intval', $_GET[$var]):intval($_GET[$var]);
204 204
 foreach ($_POST as $var => $val)
205
-	if ($_POST[$var] and strncmp($var, "id_", 3) == 0
206
-	and !in_array($var, array('id_table', 'id_base')))
207
-		$_POST[$var] = is_array($_POST[$var])?@array_map('intval', $_POST[$var]):intval($_POST[$var]);
205
+    if ($_POST[$var] and strncmp($var, "id_", 3) == 0
206
+    and !in_array($var, array('id_table', 'id_base')))
207
+        $_POST[$var] = is_array($_POST[$var])?@array_map('intval', $_POST[$var]):intval($_POST[$var]);
208 208
 foreach ($GLOBALS as $var => $val)
209
-	if ($GLOBALS[$var] and strncmp($var, "id_", 3) == 0
210
-	and !in_array($var, array('id_table', 'id_base')))
211
-		$GLOBALS[$var] = is_array($GLOBALS[$var])?@array_map('intval', $GLOBALS[$var]):intval($GLOBALS[$var]);
209
+    if ($GLOBALS[$var] and strncmp($var, "id_", 3) == 0
210
+    and !in_array($var, array('id_table', 'id_base')))
211
+        $GLOBALS[$var] = is_array($GLOBALS[$var])?@array_map('intval', $GLOBALS[$var]):intval($GLOBALS[$var]);
212 212
 
213 213
 /*
214 214
  * Interdit la variable $cjpeg_command, qui était utilisée sans
@@ -220,17 +220,17 @@  discard block
 block discarded – undo
220 220
  * Contrôle de quelques variables (XSS)
221 221
  */
222 222
 foreach(array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
223
-	if (isset($_GET[$var]))
224
-		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
225
-	if (isset($_POST[$var]))
226
-		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
223
+    if (isset($_GET[$var]))
224
+        $_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
225
+    if (isset($_POST[$var]))
226
+        $_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
227 227
 }
228 228
 
229 229
 /*
230 230
  * Filtre l'accès à spip_acces_doc (injection SQL en 1.8.2x)
231 231
  */
232 232
 if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
233
-	$file = addslashes((string)$_GET['file']);
233
+    $file = addslashes((string)$_GET['file']);
234 234
 }
235 235
 
236 236
 /*
@@ -239,79 +239,79 @@  discard block
 block discarded – undo
239 239
 if (isset($_REQUEST['mode']) and isset($_REQUEST['page'])
240 240
 and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
241 241
 and $_REQUEST['page'] == "identifiants")
242
-	$ecran_securite_raison = "identifiants";
242
+    $ecran_securite_raison = "identifiants";
243 243
 
244 244
 /*
245 245
  * Agenda joue à l'injection php
246 246
  */
247 247
 if (isset($_REQUEST['partie_cal'])
248 248
 and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal']))
249
-	$ecran_securite_raison = "partie_cal";
249
+    $ecran_securite_raison = "partie_cal";
250 250
 if (isset($_REQUEST['echelle'])
251 251
 and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle']))
252
-	$ecran_securite_raison = "echelle";
252
+    $ecran_securite_raison = "echelle";
253 253
 
254 254
 /*
255 255
  * Espace privé
256 256
  */
257 257
 if (isset($_REQUEST['exec'])
258 258
 and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec']))
259
-	$ecran_securite_raison = "exec";
259
+    $ecran_securite_raison = "exec";
260 260
 if (isset($_REQUEST['cherche_auteur'])
261 261
 and preg_match(',[<],', (string)$_REQUEST['cherche_auteur']))
262
-	$ecran_securite_raison = "cherche_auteur";
262
+    $ecran_securite_raison = "cherche_auteur";
263 263
 if (isset($_REQUEST['exec'])
264 264
 and $_REQUEST['exec'] == 'auteurs'
265 265
 and preg_match(',[<],', (string)$_REQUEST['recherche']))
266
-	$ecran_securite_raison = "recherche";
266
+    $ecran_securite_raison = "recherche";
267 267
 if (isset($_REQUEST['exec'])
268 268
 and $_REQUEST['exec'] == 'info_plugin'
269 269
 and preg_match(',[<],', (string)$_REQUEST['plugin']))
270
-	$ecran_securite_raison = "plugin";
270
+    $ecran_securite_raison = "plugin";
271 271
 if (isset($_REQUEST['exec'])
272 272
 and $_REQUEST['exec'] == 'puce_statut'
273 273
 and isset($_REQUEST['id'])
274 274
 and !intval($_REQUEST['id']))
275
-	$ecran_securite_raison = "puce_statut";
275
+    $ecran_securite_raison = "puce_statut";
276 276
 if (isset($_REQUEST['action'])
277 277
 and $_REQUEST['action'] == 'configurer') {
278
-	if (@file_exists('inc_version.php')
279
-	or @file_exists('ecrire/inc_version.php')) {
280
-		function action_configurer() {
281
-			include_spip('inc/autoriser');
282
-			if(!autoriser('configurer', _request('configuration'))) {
283
-				include_spip('inc/minipres');
284
-				echo minipres(_T('info_acces_interdit'));
285
-				exit;
286
-			}
287
-			require _DIR_RESTREINT.'action/configurer.php';
288
-			action_configurer_dist();
289
-		}
290
-	}
278
+    if (@file_exists('inc_version.php')
279
+    or @file_exists('ecrire/inc_version.php')) {
280
+        function action_configurer() {
281
+            include_spip('inc/autoriser');
282
+            if(!autoriser('configurer', _request('configuration'))) {
283
+                include_spip('inc/minipres');
284
+                echo minipres(_T('info_acces_interdit'));
285
+                exit;
286
+            }
287
+            require _DIR_RESTREINT.'action/configurer.php';
288
+            action_configurer_dist();
289
+        }
290
+    }
291 291
 }
292 292
 
293 293
 /*
294 294
  * Bloque les requêtes contenant %00 (manipulation d'include)
295 295
  */
296 296
 if (strpos(
297
-	@get_magic_quotes_gpc() ?
298
-		stripslashes(serialize($_REQUEST)) : serialize($_REQUEST),
299
-	chr(0)
297
+    @get_magic_quotes_gpc() ?
298
+        stripslashes(serialize($_REQUEST)) : serialize($_REQUEST),
299
+    chr(0)
300 300
 ) !== false)
301
-	$ecran_securite_raison = "%00";
301
+    $ecran_securite_raison = "%00";
302 302
 
303 303
 /*
304 304
  * Bloque les requêtes fond=formulaire_
305 305
  */
306 306
 if (isset($_REQUEST['fond'])
307 307
 and preg_match(',^formulaire_,i', $_REQUEST['fond']))
308
-	$ecran_securite_raison = "fond=formulaire_";
308
+    $ecran_securite_raison = "fond=formulaire_";
309 309
 
310 310
 /*
311 311
  * Bloque les requêtes du type ?GLOBALS[type_urls]=toto (bug vieux php)
312 312
  */
313 313
 if (isset($_REQUEST['GLOBALS']))
314
-	$ecran_securite_raison = "GLOBALS[GLOBALS]";
314
+    $ecran_securite_raison = "GLOBALS[GLOBALS]";
315 315
 
316 316
 /*
317 317
  * Bloque les requêtes des bots sur:
@@ -319,24 +319,24 @@  discard block
 block discarded – undo
319 319
  * les paginations entremélées
320 320
  */
321 321
 if (_IS_BOT and (
322
-	(isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
323
-	or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
322
+    (isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
323
+    or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
324 324
 )
325 325
 )
326
-	$ecran_securite_raison = "robot agenda/double pagination";
326
+    $ecran_securite_raison = "robot agenda/double pagination";
327 327
 
328 328
 /*
329 329
  * Bloque une vieille page de tests de CFG (<1.11)
330 330
  * Bloque un XSS sur une page inexistante
331 331
  */
332 332
 if (isset($_REQUEST['page'])) {
333
-	if ($_REQUEST['page'] == 'test_cfg')
334
-		$ecran_securite_raison = "test_cfg";
335
-	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page']))
336
-		$ecran_securite_raison = "xsspage";
337
-	if ($_REQUEST['page'] == '404'
338
-	and isset($_REQUEST['erreur']))
339
-		$ecran_securite_raison = "xss404";
333
+    if ($_REQUEST['page'] == 'test_cfg')
334
+        $ecran_securite_raison = "test_cfg";
335
+    if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page']))
336
+        $ecran_securite_raison = "xsspage";
337
+    if ($_REQUEST['page'] == '404'
338
+    and isset($_REQUEST['erreur']))
339
+        $ecran_securite_raison = "xss404";
340 340
 }
341 341
 
342 342
 /*
@@ -344,40 +344,40 @@  discard block
 block discarded – undo
344 344
  */
345 345
 foreach (array('var_login') as $var)
346 346
 if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var]))
347
-	$ecran_securite_raison = "xss ".$var;
347
+    $ecran_securite_raison = "xss ".$var;
348 348
 
349 349
 /*
350 350
  * Parade antivirale contre un cheval de troie
351 351
  */
352 352
 if (!function_exists('tmp_lkojfghx')) {
353
-	function tmp_lkojfghx() {}
354
-	function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
355
-		// si jamais on est arrivé ici sur une erreur php
356
-		// et qu'un autre gestionnaire d'erreur est défini, l'appeller
357
-		if ($b && $GLOBALS['tmp_xhgfjokl'])
358
-			call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
359
-	}
353
+    function tmp_lkojfghx() {}
354
+    function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
355
+        // si jamais on est arrivé ici sur une erreur php
356
+        // et qu'un autre gestionnaire d'erreur est défini, l'appeller
357
+        if ($b && $GLOBALS['tmp_xhgfjokl'])
358
+            call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
359
+    }
360 360
 }
361 361
 if (isset($_POST['tmp_lkojfghx3']))
362
-	$ecran_securite_raison = "gumblar";
362
+    $ecran_securite_raison = "gumblar";
363 363
 
364 364
 /*
365 365
  * Outils XML mal sécurisés < 2.0.9
366 366
  */
367 367
 if (isset($_REQUEST['transformer_xml']))
368
-	$ecran_securite_raison = "transformer_xml";
368
+    $ecran_securite_raison = "transformer_xml";
369 369
 
370 370
 /*
371 371
  * Outils XML mal sécurisés again
372 372
  */
373 373
 if (isset($_REQUEST['var_url']) and $_REQUEST['var_url'] and isset($_REQUEST['exec']) and $_REQUEST['exec']=='valider_xml'){
374
-	$url = trim($_REQUEST['var_url']);
375
-	if (strncmp($url,'/',1)==0
376
-	  or (($p=strpos($url,'..'))!==false AND strpos($url,'..',$p+3)!==false)
377
-	  or (($p=strpos($url,'..'))!==false AND strpos($url,'IMG',$p+3)!==false)
378
-		or (strpos($url,'://')!==false or strpos($url,':\\')!==false)) {
379
-		$ecran_securite_raison = 'URL interdite pour var_url';
380
-	}
374
+    $url = trim($_REQUEST['var_url']);
375
+    if (strncmp($url,'/',1)==0
376
+      or (($p=strpos($url,'..'))!==false AND strpos($url,'..',$p+3)!==false)
377
+      or (($p=strpos($url,'..'))!==false AND strpos($url,'IMG',$p+3)!==false)
378
+        or (strpos($url,'://')!==false or strpos($url,':\\')!==false)) {
379
+        $ecran_securite_raison = 'URL interdite pour var_url';
380
+    }
381 381
 }
382 382
 
383 383
 /*
@@ -385,10 +385,10 @@  discard block
 block discarded – undo
385 385
  */
386 386
 if (isset($_REQUEST['nom_sauvegarde'])
387 387
 and strstr((string)$_REQUEST['nom_sauvegarde'], '/'))
388
-	$ecran_securite_raison = 'nom_sauvegarde manipulee';
388
+    $ecran_securite_raison = 'nom_sauvegarde manipulee';
389 389
 if (isset($_REQUEST['znom_sauvegarde'])
390 390
 and strstr((string)$_REQUEST['znom_sauvegarde'], '/'))
391
-	$ecran_securite_raison = 'znom_sauvegarde manipulee';
391
+    $ecran_securite_raison = 'znom_sauvegarde manipulee';
392 392
 
393 393
 
394 394
 /*
@@ -397,26 +397,26 @@  discard block
 block discarded – undo
397 397
  */
398 398
 if (isset($_REQUEST['op']) and isset($_REQUEST['page'])
399 399
 and $_REQUEST['op'] !== preg_replace('/[^\-\w]/', '', $_REQUEST['op']))
400
-	$ecran_securite_raison = 'op';
400
+    $ecran_securite_raison = 'op';
401 401
 
402 402
 /*
403 403
  * Forms & Table ne se méfiait pas assez des uploads de fichiers
404 404
  */
405 405
 if (count($_FILES)){
406
-	foreach($_FILES as $k => $v){
407
-		 if (preg_match(',^fichier_\d+$,', $k)
408
-		 and preg_match(',\.php,i', $v['name']))
409
-		 	unset($_FILES[$k]);
410
-	}
406
+    foreach($_FILES as $k => $v){
407
+            if (preg_match(',^fichier_\d+$,', $k)
408
+         and preg_match(',\.php,i', $v['name']))
409
+                unset($_FILES[$k]);
410
+    }
411 411
 }
412 412
 /*
413 413
  * et Contact trop laxiste avec une variable externe
414 414
  * on bloque pas le post pour eviter de perdre des donnees mais on unset la variable et c'est tout
415 415
  */
416 416
 if (isset($_REQUEST['pj_enregistrees_nom']) and $_REQUEST['pj_enregistrees_nom']){
417
-	unset($_REQUEST['pj_enregistrees_nom']);
418
-	unset($_GET['pj_enregistrees_nom']);
419
-	unset($_POST['pj_enregistrees_nom']);
417
+    unset($_REQUEST['pj_enregistrees_nom']);
418
+    unset($_GET['pj_enregistrees_nom']);
419
+    unset($_POST['pj_enregistrees_nom']);
420 420
 }
421 421
 
422 422
 /*
@@ -424,66 +424,66 @@  discard block
 block discarded – undo
424 424
  */
425 425
 if (isset($_REQUEST['reinstall'])
426 426
 and $_REQUEST['reinstall'] == 'oui')
427
-	$ecran_securite_raison = 'reinstall=oui';
427
+    $ecran_securite_raison = 'reinstall=oui';
428 428
 
429 429
 /*
430 430
  * Échappement xss referer
431 431
  */
432 432
 if (isset($_SERVER['HTTP_REFERER']))
433
-	$_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
433
+    $_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
434 434
 
435 435
 
436 436
 /*
437 437
  * Echappement HTTP_X_FORWARDED_HOST
438 438
  */
439 439
 if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
440
-	$_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
440
+    $_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
441 441
 
442 442
 
443 443
 /*
444 444
  * Réinjection des clés en html dans l'admin r19561
445 445
  */
446 446
 if (strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false){
447
-	$zzzz = implode("", array_keys($_REQUEST));
448
-	if (strlen($zzzz) != strcspn($zzzz, '<>"\''))
449
-		$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
447
+    $zzzz = implode("", array_keys($_REQUEST));
448
+    if (strlen($zzzz) != strcspn($zzzz, '<>"\''))
449
+        $ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
450 450
 }
451 451
 
452 452
 /*
453 453
  * Injection par connect
454 454
  */
455 455
 if (isset($_REQUEST['connect'])
456
-	and
457
-	// cas qui permettent de sortir d'un commentaire PHP
458
-	(strpos($_REQUEST['connect'], "?") !== false
459
-	 or strpos($_REQUEST['connect'], "<") !== false
460
-	 or strpos($_REQUEST['connect'], ">") !== false
461
-	 or strpos($_REQUEST['connect'], "\n") !== false
462
-	 or strpos($_REQUEST['connect'], "\r") !== false)
463
-	) {
464
-	$ecran_securite_raison = "malformed connect argument";
456
+    and
457
+    // cas qui permettent de sortir d'un commentaire PHP
458
+    (strpos($_REQUEST['connect'], "?") !== false
459
+     or strpos($_REQUEST['connect'], "<") !== false
460
+     or strpos($_REQUEST['connect'], ">") !== false
461
+     or strpos($_REQUEST['connect'], "\n") !== false
462
+     or strpos($_REQUEST['connect'], "\r") !== false)
463
+    ) {
464
+    $ecran_securite_raison = "malformed connect argument";
465 465
 }
466 466
 
467 467
 /*
468 468
  * S'il y a une raison de mourir, mourons
469 469
  */
470 470
 if (isset($ecran_securite_raison)) {
471
-	header("HTTP/1.0 403 Forbidden");
472
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
473
-	header("Cache-Control: no-cache, must-revalidate");
474
-	header("Pragma: no-cache");
475
-	header("Content-Type: text/html");
476
-	die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
471
+    header("HTTP/1.0 403 Forbidden");
472
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
473
+    header("Cache-Control: no-cache, must-revalidate");
474
+    header("Pragma: no-cache");
475
+    header("Content-Type: text/html");
476
+    die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
477 477
 }
478 478
 
479 479
 /*
480 480
  * Un filtre filtrer_entites securise
481 481
  */
482 482
 if (!function_exists('filtre_filtrer_entites_dist')) {
483
-	function filtre_filtrer_entites_dist($t) {
484
-		include_spip('inc/texte');
485
-		return interdire_scripts(filtrer_entites($t));
486
-	}
483
+    function filtre_filtrer_entites_dist($t) {
484
+        include_spip('inc/texte');
485
+        return interdire_scripts(filtrer_entites($t));
486
+    }
487 487
 }
488 488
 
489 489
 
@@ -497,34 +497,34 @@  discard block
 block discarded – undo
497 497
  * Bloque les bots quand le load déborde
498 498
  */
499 499
 if (!defined('_ECRAN_SECURITE_LOAD'))
500
-	define('_ECRAN_SECURITE_LOAD', 4);
500
+    define('_ECRAN_SECURITE_LOAD', 4);
501 501
 
502 502
 if (
503
-	defined('_ECRAN_SECURITE_LOAD')
504
-	and _ECRAN_SECURITE_LOAD > 0
505
-	and _IS_BOT
506
-	and !_IS_BOT_FRIEND
507
-	and $_SERVER['REQUEST_METHOD'] === 'GET'
508
-	and (
509
-		(function_exists('sys_getloadavg')
510
-		  and $load = sys_getloadavg()
511
-		  and is_array($load)
512
-		  and $load = array_shift($load)
513
-		)
514
-		or
515
-		(@is_readable('/proc/loadavg')
516
-		  and $load = file_get_contents('/proc/loadavg')
517
-		  and $load = floatval($load)
518
-		)
519
-	)
520
-	and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
521
-	and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
503
+    defined('_ECRAN_SECURITE_LOAD')
504
+    and _ECRAN_SECURITE_LOAD > 0
505
+    and _IS_BOT
506
+    and !_IS_BOT_FRIEND
507
+    and $_SERVER['REQUEST_METHOD'] === 'GET'
508
+    and (
509
+        (function_exists('sys_getloadavg')
510
+          and $load = sys_getloadavg()
511
+          and is_array($load)
512
+          and $load = array_shift($load)
513
+        )
514
+        or
515
+        (@is_readable('/proc/loadavg')
516
+          and $load = file_get_contents('/proc/loadavg')
517
+          and $load = floatval($load)
518
+        )
519
+    )
520
+    and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
521
+    and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
522 522
 ) {
523
-	header("HTTP/1.0 503 Service Unavailable");
524
-	header("Retry-After: 300");
525
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
526
-	header("Cache-Control: no-cache, must-revalidate");
527
-	header("Pragma: no-cache");
528
-	header("Content-Type: text/html");
529
-	die("<html><title>Status 503: Site temporarily unavailable</title><body><h1>Status 503</h1><p>Site temporarily unavailable (load average $load)</p></body></html>");
523
+    header("HTTP/1.0 503 Service Unavailable");
524
+    header("Retry-After: 300");
525
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
526
+    header("Cache-Control: no-cache, must-revalidate");
527
+    header("Pragma: no-cache");
528
+    header("Content-Type: text/html");
529
+    die("<html><title>Status 503: Site temporarily unavailable</title><body><h1>Status 503</h1><p>Site temporarily unavailable (load average $load)</p></body></html>");
530 530
 }
Please login to merge, or discard this patch.
ecrire/inc/lien.php 3 patches
Doc Comments   +13 added lines, -1 removed lines patch added patch discarded remove patch
@@ -42,6 +42,9 @@  discard block
 block discarded – undo
42 42
 define('_RACCOURCI_LIEN', "/\[([^][]*?([[]\w*[]][^][]*)*)->(>?)([^]]*)\]/msS");
43 43
 
44 44
 // http://code.spip.net/@expanser_liens
45
+/**
46
+ * @return string
47
+ */
45 48
 function expanser_liens($t, $connect = '', $env = array()) {
46 49
 
47 50
 	$t = pipeline('pre_liens', $t);
@@ -56,6 +59,9 @@  discard block
 block discarded – undo
56 59
 // Meme analyse mais pour eliminer les liens
57 60
 // et ne laisser que leur titre, a expliciter si ce n'est fait
58 61
 // http://code.spip.net/@nettoyer_raccourcis_typo
62
+/**
63
+ * @param string $texte
64
+ */
59 65
 function nettoyer_raccourcis_typo($texte, $connect = '') {
60 66
 	return $texte;
61 67
 }
@@ -96,6 +102,9 @@  discard block
 block discarded – undo
96 102
 // 'url':   seulement U  (i.e. generer_url_RACCOURCI)
97 103
 
98 104
 // http://code.spip.net/@calculer_url
105
+/**
106
+ * @return string
107
+ */
99 108
 function calculer_url($ref, $texte = '', $pour = 'url', $connect = '', $echappe_typo = true) {
100 109
 	$r = traiter_lien_implicite($ref, $texte, $pour, $connect, $echappe_typo);
101 110
 
@@ -256,7 +265,7 @@  discard block
 block discarded – undo
256 265
  * @param int $id Identifiant de l'objet
257 266
  * @param string $type Type d'objet
258 267
  * @param string|null $connect Connecteur SQL utilisé
259
- * @return array {
268
+ * @return string {
260 269
  * @var string $titre Titre si présent, sinon ''
261 270
  * @var string $lang Langue si présente, sinon ''
262 271
  * }
@@ -302,6 +311,9 @@  discard block
 block discarded – undo
302 311
 define('_RACCOURCI_MODELE_DEBUT', '@^' . _RACCOURCI_MODELE . '@isS');
303 312
 
304 313
 // http://code.spip.net/@traiter_modeles
314
+/**
315
+ * @return string
316
+ */
305 317
 function traiter_modeles($texte, $doublons = false, $echap = '', $connect = '', $liens = null, $env = array()) {
306 318
 	// preserver la compatibilite : true = recherche des documents
307 319
 	if ($doublons === true) {
Please login to merge, or discard this patch.
Indentation   +273 added lines, -273 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('base/abstract_sql');
@@ -23,16 +23,16 @@  discard block
 block discarded – undo
23 23
 //
24 24
 
25 25
 function inc_lien_dist(
26
-	$lien,
27
-	$texte = '',
28
-	$class = '',
29
-	$title = '',
30
-	$hlang = '',
31
-	$rel = '',
32
-	$connect = '',
33
-	$env = array()
26
+    $lien,
27
+    $texte = '',
28
+    $class = '',
29
+    $title = '',
30
+    $hlang = '',
31
+    $rel = '',
32
+    $connect = '',
33
+    $env = array()
34 34
 ) {
35
-	return $lien;
35
+    return $lien;
36 36
 }
37 37
 
38 38
 // Regexp des raccourcis, aussi utilisee pour la fusion de sauvegarde Spip
@@ -44,30 +44,30 @@  discard block
 block discarded – undo
44 44
 // http://code.spip.net/@expanser_liens
45 45
 function expanser_liens($t, $connect = '', $env = array()) {
46 46
 
47
-	$t = pipeline('pre_liens', $t);
47
+    $t = pipeline('pre_liens', $t);
48 48
 
49
-	// on passe a traiter_modeles la liste des liens reperes pour lui permettre
50
-	// de remettre le texte d'origine dans les parametres du modele
51
-	$t = traiter_modeles($t, false, false, $connect);
49
+    // on passe a traiter_modeles la liste des liens reperes pour lui permettre
50
+    // de remettre le texte d'origine dans les parametres du modele
51
+    $t = traiter_modeles($t, false, false, $connect);
52 52
 
53
-	return $t;
53
+    return $t;
54 54
 }
55 55
 
56 56
 // Meme analyse mais pour eliminer les liens
57 57
 // et ne laisser que leur titre, a expliciter si ce n'est fait
58 58
 // http://code.spip.net/@nettoyer_raccourcis_typo
59 59
 function nettoyer_raccourcis_typo($texte, $connect = '') {
60
-	return $texte;
60
+    return $texte;
61 61
 }
62 62
 
63 63
 // Repere dans la partie texte d'un raccourci [texte->...]
64 64
 // la langue et la bulle eventuelles
65 65
 // http://code.spip.net/@traiter_raccourci_lien_atts
66 66
 function traiter_raccourci_lien_atts($texte) {
67
-	$bulle = '';
68
-	$hlang = '';
67
+    $bulle = '';
68
+    $hlang = '';
69 69
 
70
-	return array(trim($texte), $bulle, $hlang);
70
+    return array(trim($texte), $bulle, $hlang);
71 71
 }
72 72
 
73 73
 define('_RACCOURCI_CHAPO', '/^(\W*)(\W*)(\w*\d+([?#].*)?)$/');
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
  * @return string
84 84
  */
85 85
 function virtuel_redirige($virtuel, $url = false) {
86
-	return $virtuel;
86
+    return $virtuel;
87 87
 }
88 88
 
89 89
 // Cherche un lien du type [->raccourci 123]
@@ -97,114 +97,114 @@  discard block
 block discarded – undo
97 97
 
98 98
 // http://code.spip.net/@calculer_url
99 99
 function calculer_url($ref, $texte = '', $pour = 'url', $connect = '', $echappe_typo = true) {
100
-	$r = traiter_lien_implicite($ref, $texte, $pour, $connect, $echappe_typo);
100
+    $r = traiter_lien_implicite($ref, $texte, $pour, $connect, $echappe_typo);
101 101
 
102
-	return $r ? $r : traiter_lien_explicite($ref, $texte, $pour, $connect, $echappe_typo);
102
+    return $r ? $r : traiter_lien_explicite($ref, $texte, $pour, $connect, $echappe_typo);
103 103
 }
104 104
 
105 105
 define('_EXTRAIRE_LIEN', ',^\s*(?:' . _PROTOCOLES_STD . '):?/?/?\s*$,iS');
106 106
 
107 107
 // http://code.spip.net/@traiter_lien_explicite
108 108
 function traiter_lien_explicite($ref, $texte = '', $pour = 'url', $connect = '', $echappe_typo = true) {
109
-	if (preg_match(_EXTRAIRE_LIEN, $ref)) {
110
-		return ($pour != 'tout') ? '' : array('', '', '', '');
111
-	}
112
-
113
-	$lien = entites_html(trim($ref));
114
-
115
-	// Liens explicites
116
-	if (!$texte) {
117
-		$texte = str_replace('"', '', $lien);
118
-		// evite l'affichage de trops longues urls.
119
-		$lien_court = charger_fonction('lien_court', 'inc');
120
-		$texte = $lien_court($texte);
121
-		if ($echappe_typo) {
122
-			$texte = "<html>" . quote_amp($texte) . "</html>";
123
-		}
124
-	}
125
-
126
-	// petites corrections d'URL
127
-	if (preg_match('/^www\.[^@]+$/S', $lien)) {
128
-		$lien = "http://" . $lien;
129
-	} else {
130
-		if (strpos($lien, "@") && email_valide($lien)) {
131
-			if (!$texte) {
132
-				$texte = $lien;
133
-			}
134
-			$lien = "mailto:" . $lien;
135
-		}
136
-	}
137
-
138
-	if ($pour == 'url') {
139
-		return $lien;
140
-	}
141
-
142
-	if ($pour == 'titre') {
143
-		return $texte;
144
-	}
145
-
146
-	return array('url' => $lien, 'titre' => $texte);
109
+    if (preg_match(_EXTRAIRE_LIEN, $ref)) {
110
+        return ($pour != 'tout') ? '' : array('', '', '', '');
111
+    }
112
+
113
+    $lien = entites_html(trim($ref));
114
+
115
+    // Liens explicites
116
+    if (!$texte) {
117
+        $texte = str_replace('"', '', $lien);
118
+        // evite l'affichage de trops longues urls.
119
+        $lien_court = charger_fonction('lien_court', 'inc');
120
+        $texte = $lien_court($texte);
121
+        if ($echappe_typo) {
122
+            $texte = "<html>" . quote_amp($texte) . "</html>";
123
+        }
124
+    }
125
+
126
+    // petites corrections d'URL
127
+    if (preg_match('/^www\.[^@]+$/S', $lien)) {
128
+        $lien = "http://" . $lien;
129
+    } else {
130
+        if (strpos($lien, "@") && email_valide($lien)) {
131
+            if (!$texte) {
132
+                $texte = $lien;
133
+            }
134
+            $lien = "mailto:" . $lien;
135
+        }
136
+    }
137
+
138
+    if ($pour == 'url') {
139
+        return $lien;
140
+    }
141
+
142
+    if ($pour == 'titre') {
143
+        return $texte;
144
+    }
145
+
146
+    return array('url' => $lien, 'titre' => $texte);
147 147
 }
148 148
 
149 149
 function liens_implicite_glose_dist($texte, $id, $type, $args, $ancre, $connect = '') {
150
-	if (function_exists($f = 'glossaire_' . $ancre)) {
151
-		$url = $f($texte, $id);
152
-	} else {
153
-		$url = glossaire_std($texte);
154
-	}
150
+    if (function_exists($f = 'glossaire_' . $ancre)) {
151
+        $url = $f($texte, $id);
152
+    } else {
153
+        $url = glossaire_std($texte);
154
+    }
155 155
 
156
-	return $url;
156
+    return $url;
157 157
 }
158 158
 
159 159
 // http://code.spip.net/@traiter_lien_implicite
160 160
 function traiter_lien_implicite($ref, $texte = '', $pour = 'url', $connect = '') {
161
-	if (!($match = typer_raccourci($ref))) {
162
-		return false;
163
-	}
164
-	@list($type, , $id, , $args, , $ancre) = $match;
165
-	// attention dans le cas des sites le lien doit pointer non pas sur
166
-	// la page locale du site, mais directement sur le site lui-meme
167
-	if ($f = charger_fonction("implicite_$type", "liens", true)) {
168
-		$url = $f($texte, $id, $type, $args, $ancre, $connect);
169
-	}
170
-	if (!$url) {
171
-		$url = generer_url_entite($id, $type, $args, $ancre, $connect ? $connect : null);
172
-	}
173
-	if (!$url) {
174
-		return false;
175
-	}
176
-	if (is_array($url)) {
177
-		@list($type, $id) = $url;
178
-		$url = generer_url_entite($id, $type, $args, $ancre, $connect ? $connect : null);
179
-	}
180
-	if ($pour === 'url') {
181
-		return $url;
182
-	}
183
-	$r = traiter_raccourci_titre($id, $type, $connect);
184
-	if ($r) {
185
-		$r['class'] = ($type == 'site') ? 'spip_out' : 'spip_in';
186
-	}
187
-	if ($texte = trim($texte)) {
188
-		$r['titre'] = $texte;
189
-	}
190
-	if (!@$r['titre']) {
191
-		$r['titre'] = _T($type) . " $id";
192
-	}
193
-	if ($pour == 'titre') {
194
-		return $r['titre'];
195
-	}
196
-	$r['url'] = $url;
197
-
198
-	// dans le cas d'un lien vers un doc, ajouter le type='mime/type'
199
-	if ($type == 'document'
200
-		and $mime = sql_getfetsel('mime_type', 'spip_types_documents',
201
-			"extension IN (" . sql_get_select("extension", "spip_documents", "id_document=" . sql_quote($id)) . ")",
202
-			'', '', '', '', $connect)
203
-	) {
204
-		$r['mime'] = $mime;
205
-	}
206
-
207
-	return $r;
161
+    if (!($match = typer_raccourci($ref))) {
162
+        return false;
163
+    }
164
+    @list($type, , $id, , $args, , $ancre) = $match;
165
+    // attention dans le cas des sites le lien doit pointer non pas sur
166
+    // la page locale du site, mais directement sur le site lui-meme
167
+    if ($f = charger_fonction("implicite_$type", "liens", true)) {
168
+        $url = $f($texte, $id, $type, $args, $ancre, $connect);
169
+    }
170
+    if (!$url) {
171
+        $url = generer_url_entite($id, $type, $args, $ancre, $connect ? $connect : null);
172
+    }
173
+    if (!$url) {
174
+        return false;
175
+    }
176
+    if (is_array($url)) {
177
+        @list($type, $id) = $url;
178
+        $url = generer_url_entite($id, $type, $args, $ancre, $connect ? $connect : null);
179
+    }
180
+    if ($pour === 'url') {
181
+        return $url;
182
+    }
183
+    $r = traiter_raccourci_titre($id, $type, $connect);
184
+    if ($r) {
185
+        $r['class'] = ($type == 'site') ? 'spip_out' : 'spip_in';
186
+    }
187
+    if ($texte = trim($texte)) {
188
+        $r['titre'] = $texte;
189
+    }
190
+    if (!@$r['titre']) {
191
+        $r['titre'] = _T($type) . " $id";
192
+    }
193
+    if ($pour == 'titre') {
194
+        return $r['titre'];
195
+    }
196
+    $r['url'] = $url;
197
+
198
+    // dans le cas d'un lien vers un doc, ajouter le type='mime/type'
199
+    if ($type == 'document'
200
+        and $mime = sql_getfetsel('mime_type', 'spip_types_documents',
201
+            "extension IN (" . sql_get_select("extension", "spip_documents", "id_document=" . sql_quote($id)) . ")",
202
+            '', '', '', '', $connect)
203
+    ) {
204
+        $r['mime'] = $mime;
205
+    }
206
+
207
+    return $r;
208 208
 }
209 209
 
210 210
 // analyse des raccourcis issus de [TITRE->RACCOURCInnn] et connexes
@@ -213,41 +213,41 @@  discard block
 block discarded – undo
213 213
 
214 214
 // http://code.spip.net/@typer_raccourci
215 215
 function typer_raccourci($lien) {
216
-	if (!preg_match(_RACCOURCI_URL, $lien, $match)) {
217
-		return array();
218
-	}
219
-	$f = $match[1];
220
-	// valeur par defaut et alias historiques
221
-	if (!$f) {
222
-		$f = 'article';
223
-	} else {
224
-		if ($f == 'art') {
225
-			$f = 'article';
226
-		} else {
227
-			if ($f == 'br') {
228
-				$f = 'breve';
229
-			} else {
230
-				if ($f == 'rub') {
231
-					$f = 'rubrique';
232
-				} else {
233
-					if ($f == 'aut') {
234
-						$f = 'auteur';
235
-					} else {
236
-						if ($f == 'doc' or $f == 'im' or $f == 'img' or $f == 'image' or $f == 'emb') {
237
-							$f = 'document';
238
-						} else {
239
-							if (preg_match('/^br..?ve$/S', $f)) {
240
-								$f = 'breve';
241
-							}
242
-						}
243
-					}
244
-				}
245
-			}
246
-		}
247
-	} # accents :(
248
-	$match[0] = $f;
249
-
250
-	return $match;
216
+    if (!preg_match(_RACCOURCI_URL, $lien, $match)) {
217
+        return array();
218
+    }
219
+    $f = $match[1];
220
+    // valeur par defaut et alias historiques
221
+    if (!$f) {
222
+        $f = 'article';
223
+    } else {
224
+        if ($f == 'art') {
225
+            $f = 'article';
226
+        } else {
227
+            if ($f == 'br') {
228
+                $f = 'breve';
229
+            } else {
230
+                if ($f == 'rub') {
231
+                    $f = 'rubrique';
232
+                } else {
233
+                    if ($f == 'aut') {
234
+                        $f = 'auteur';
235
+                    } else {
236
+                        if ($f == 'doc' or $f == 'im' or $f == 'img' or $f == 'image' or $f == 'emb') {
237
+                            $f = 'document';
238
+                        } else {
239
+                            if (preg_match('/^br..?ve$/S', $f)) {
240
+                                $f = 'breve';
241
+                            }
242
+                        }
243
+                    }
244
+                }
245
+            }
246
+        }
247
+    } # accents :(
248
+    $match[0] = $f;
249
+
250
+    return $match;
251 251
 }
252 252
 
253 253
 /**
@@ -262,25 +262,25 @@  discard block
 block discarded – undo
262 262
  * }
263 263
  **/
264 264
 function traiter_raccourci_titre($id, $type, $connect = null) {
265
-	$trouver_table = charger_fonction('trouver_table', 'base');
266
-	$desc = $trouver_table(table_objet($type));
267
-	if (!($desc and $s = $desc['titre'])) {
268
-		return array();
269
-	}
270
-	$_id = $desc['key']['PRIMARY KEY'];
271
-	$r = sql_fetsel($s, $desc['table'], "$_id=$id", '', '', '', '', $connect);
272
-	if (!$r) {
273
-		return array();
274
-	}
275
-	$r['titre'] = supprimer_numero($r['titre']);
276
-	if (!$r['titre'] and !empty($r['surnom'])) {
277
-		$r['titre'] = $r['surnom'];
278
-	}
279
-	if (!isset($r['lang'])) {
280
-		$r['lang'] = '';
281
-	}
282
-
283
-	return $r;
265
+    $trouver_table = charger_fonction('trouver_table', 'base');
266
+    $desc = $trouver_table(table_objet($type));
267
+    if (!($desc and $s = $desc['titre'])) {
268
+        return array();
269
+    }
270
+    $_id = $desc['key']['PRIMARY KEY'];
271
+    $r = sql_fetsel($s, $desc['table'], "$_id=$id", '', '', '', '', $connect);
272
+    if (!$r) {
273
+        return array();
274
+    }
275
+    $r['titre'] = supprimer_numero($r['titre']);
276
+    if (!$r['titre'] and !empty($r['surnom'])) {
277
+        $r['titre'] = $r['surnom'];
278
+    }
279
+    if (!isset($r['lang'])) {
280
+        $r['lang'] = '';
281
+    }
282
+
283
+    return $r;
284 284
 }
285 285
 
286 286
 // traite les modeles (dans la fonction typo), en remplacant
@@ -292,115 +292,115 @@  discard block
 block discarded – undo
292 292
 // http://code.spip.net/@traiter_modeles
293 293
 
294 294
 define('_RACCOURCI_MODELE',
295
-	'(<([a-z_-]{3,})' # <modele
296
-	. '\s*([0-9]*)\s*' # id
297
-	. '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
298
-	. '\s*/?' . '>)' # fin du modele >
299
-	. '\s*(<\/a>)?' # eventuel </a>
295
+    '(<([a-z_-]{3,})' # <modele
296
+    . '\s*([0-9]*)\s*' # id
297
+    . '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
298
+    . '\s*/?' . '>)' # fin du modele >
299
+    . '\s*(<\/a>)?' # eventuel </a>
300 300
 );
301 301
 
302 302
 define('_RACCOURCI_MODELE_DEBUT', '@^' . _RACCOURCI_MODELE . '@isS');
303 303
 
304 304
 // http://code.spip.net/@traiter_modeles
305 305
 function traiter_modeles($texte, $doublons = false, $echap = '', $connect = '', $liens = null, $env = array()) {
306
-	// preserver la compatibilite : true = recherche des documents
307
-	if ($doublons === true) {
308
-		$doublons = array('documents' => array('doc', 'emb', 'img'));
309
-	}
310
-	// detecter les modeles (rapide)
311
-	if (strpos($texte, "<") !== false and
312
-		preg_match_all('/<[a-z_-]{3,}\s*[0-9|]+/iS', $texte, $matches, PREG_SET_ORDER)
313
-	) {
314
-		include_spip('public/assembler');
315
-		$wrap_embed_html = charger_fonction("wrap_embed_html", "inc", true);
316
-		foreach ($matches as $match) {
317
-			// Recuperer l'appel complet (y compris un eventuel lien)
318
-
319
-			$a = strpos($texte, $match[0]);
320
-			preg_match(_RACCOURCI_MODELE_DEBUT,
321
-				substr($texte, $a), $regs);
322
-			$regs[] = ""; // s'assurer qu'il y a toujours un 5e arg, eventuellement vide
323
-			list(, $mod, $type, $id, $params, $fin) = $regs;
324
-			if ($fin and
325
-				preg_match('/<a\s[^<>]*>\s*$/i',
326
-					substr($texte, 0, $a), $r)
327
-			) {
328
-				$lien = array(
329
-					'href' => extraire_attribut($r[0], 'href'),
330
-					'class' => extraire_attribut($r[0], 'class'),
331
-					'mime' => extraire_attribut($r[0], 'type'),
332
-					'title' => extraire_attribut($r[0], 'title'),
333
-					'hreflang' => extraire_attribut($r[0], 'hreflang')
334
-				);
335
-				$n = strlen($r[0]);
336
-				$a -= $n;
337
-				$cherche = $n + strlen($regs[0]);
338
-			} else {
339
-				$lien = false;
340
-				$cherche = strlen($mod);
341
-			}
342
-
343
-			// calculer le modele
344
-			# hack indexation
345
-			if ($doublons) {
346
-				$texte .= preg_replace(',[|][^|=]*,s', ' ', $params);
347
-			} # version normale
348
-			else {
349
-				// si un tableau de liens a ete passe, reinjecter le contenu d'origine
350
-				// dans les parametres, plutot que les liens echappes
351
-				if (!is_null($liens)) {
352
-					$params = str_replace($liens[0], $liens[1], $params);
353
-				}
354
-				$modele = inclure_modele($type, $id, $params, $lien, $connect, $env);
355
-				// en cas d'echec, 
356
-				// si l'objet demande a une url, 
357
-				// creer un petit encadre vers elle
358
-				if ($modele === false) {
359
-					if (!$lien) {
360
-						$lien = traiter_lien_implicite("$type$id", '', 'tout', $connect);
361
-					}
362
-					if ($lien) {
363
-						$modele = '<a href="'
364
-							. $lien['url']
365
-							. '" class="spip_modele'
366
-							. '">'
367
-							. sinon($lien['titre'], _T('ecrire:info_sans_titre'))
368
-							. "</a>";
369
-					} else {
370
-						$modele = "";
371
-						if (test_espace_prive()) {
372
-							$modele = entites_html(substr($texte, $a, $cherche));
373
-							if (!is_null($liens)) {
374
-								$modele = "<pre>" . str_replace($liens[0], $liens[1], $modele) . "</pre>";
375
-							}
376
-						}
377
-					}
378
-				}
379
-				// le remplacer dans le texte
380
-				if ($modele !== false) {
381
-					$modele = protege_js_modeles($modele);
382
-					if ($wrap_embed_html) {
383
-						$modele = $wrap_embed_html($mod, $modele);
384
-					}
385
-					$rempl = code_echappement($modele, $echap);
386
-					$texte = substr($texte, 0, $a)
387
-						. $rempl
388
-						. substr($texte, $a + $cherche);
389
-				}
390
-			}
391
-
392
-			// hack pour tout l'espace prive
393
-			if (((!_DIR_RESTREINT) or ($doublons)) and ($id)) {
394
-				foreach ($doublons ? $doublons : array('documents' => array('doc', 'emb', 'img')) as $quoi => $modeles) {
395
-					if (in_array($type, $modeles)) {
396
-						$GLOBALS["doublons_{$quoi}_inclus"][] = $id;
397
-					}
398
-				}
399
-			}
400
-		}
401
-	}
402
-
403
-	return $texte;
306
+    // preserver la compatibilite : true = recherche des documents
307
+    if ($doublons === true) {
308
+        $doublons = array('documents' => array('doc', 'emb', 'img'));
309
+    }
310
+    // detecter les modeles (rapide)
311
+    if (strpos($texte, "<") !== false and
312
+        preg_match_all('/<[a-z_-]{3,}\s*[0-9|]+/iS', $texte, $matches, PREG_SET_ORDER)
313
+    ) {
314
+        include_spip('public/assembler');
315
+        $wrap_embed_html = charger_fonction("wrap_embed_html", "inc", true);
316
+        foreach ($matches as $match) {
317
+            // Recuperer l'appel complet (y compris un eventuel lien)
318
+
319
+            $a = strpos($texte, $match[0]);
320
+            preg_match(_RACCOURCI_MODELE_DEBUT,
321
+                substr($texte, $a), $regs);
322
+            $regs[] = ""; // s'assurer qu'il y a toujours un 5e arg, eventuellement vide
323
+            list(, $mod, $type, $id, $params, $fin) = $regs;
324
+            if ($fin and
325
+                preg_match('/<a\s[^<>]*>\s*$/i',
326
+                    substr($texte, 0, $a), $r)
327
+            ) {
328
+                $lien = array(
329
+                    'href' => extraire_attribut($r[0], 'href'),
330
+                    'class' => extraire_attribut($r[0], 'class'),
331
+                    'mime' => extraire_attribut($r[0], 'type'),
332
+                    'title' => extraire_attribut($r[0], 'title'),
333
+                    'hreflang' => extraire_attribut($r[0], 'hreflang')
334
+                );
335
+                $n = strlen($r[0]);
336
+                $a -= $n;
337
+                $cherche = $n + strlen($regs[0]);
338
+            } else {
339
+                $lien = false;
340
+                $cherche = strlen($mod);
341
+            }
342
+
343
+            // calculer le modele
344
+            # hack indexation
345
+            if ($doublons) {
346
+                $texte .= preg_replace(',[|][^|=]*,s', ' ', $params);
347
+            } # version normale
348
+            else {
349
+                // si un tableau de liens a ete passe, reinjecter le contenu d'origine
350
+                // dans les parametres, plutot que les liens echappes
351
+                if (!is_null($liens)) {
352
+                    $params = str_replace($liens[0], $liens[1], $params);
353
+                }
354
+                $modele = inclure_modele($type, $id, $params, $lien, $connect, $env);
355
+                // en cas d'echec, 
356
+                // si l'objet demande a une url, 
357
+                // creer un petit encadre vers elle
358
+                if ($modele === false) {
359
+                    if (!$lien) {
360
+                        $lien = traiter_lien_implicite("$type$id", '', 'tout', $connect);
361
+                    }
362
+                    if ($lien) {
363
+                        $modele = '<a href="'
364
+                            . $lien['url']
365
+                            . '" class="spip_modele'
366
+                            . '">'
367
+                            . sinon($lien['titre'], _T('ecrire:info_sans_titre'))
368
+                            . "</a>";
369
+                    } else {
370
+                        $modele = "";
371
+                        if (test_espace_prive()) {
372
+                            $modele = entites_html(substr($texte, $a, $cherche));
373
+                            if (!is_null($liens)) {
374
+                                $modele = "<pre>" . str_replace($liens[0], $liens[1], $modele) . "</pre>";
375
+                            }
376
+                        }
377
+                    }
378
+                }
379
+                // le remplacer dans le texte
380
+                if ($modele !== false) {
381
+                    $modele = protege_js_modeles($modele);
382
+                    if ($wrap_embed_html) {
383
+                        $modele = $wrap_embed_html($mod, $modele);
384
+                    }
385
+                    $rempl = code_echappement($modele, $echap);
386
+                    $texte = substr($texte, 0, $a)
387
+                        . $rempl
388
+                        . substr($texte, $a + $cherche);
389
+                }
390
+            }
391
+
392
+            // hack pour tout l'espace prive
393
+            if (((!_DIR_RESTREINT) or ($doublons)) and ($id)) {
394
+                foreach ($doublons ? $doublons : array('documents' => array('doc', 'emb', 'img')) as $quoi => $modeles) {
395
+                    if (in_array($type, $modeles)) {
396
+                        $GLOBALS["doublons_{$quoi}_inclus"][] = $id;
397
+                    }
398
+                }
399
+            }
400
+        }
401
+    }
402
+
403
+    return $texte;
404 404
 }
405 405
 
406 406
 //
@@ -408,15 +408,15 @@  discard block
 block discarded – undo
408 408
 //
409 409
 // http://code.spip.net/@traiter_raccourci_ancre
410 410
 function traiter_raccourci_ancre($letexte) {
411
-	return $letexte;
411
+    return $letexte;
412 412
 }
413 413
 
414 414
 // http://code.spip.net/@traiter_raccourci_glossaire
415 415
 function traiter_raccourci_glossaire($texte) {
416
-	return $texte;
416
+    return $texte;
417 417
 }
418 418
 
419 419
 // http://code.spip.net/@glossaire_std
420 420
 function glossaire_std($terme) {
421
-	return $terme;
421
+    return $terme;
422 422
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	return $r ? $r : traiter_lien_explicite($ref, $texte, $pour, $connect, $echappe_typo);
103 103
 }
104 104
 
105
-define('_EXTRAIRE_LIEN', ',^\s*(?:' . _PROTOCOLES_STD . '):?/?/?\s*$,iS');
105
+define('_EXTRAIRE_LIEN', ',^\s*(?:'._PROTOCOLES_STD.'):?/?/?\s*$,iS');
106 106
 
107 107
 // http://code.spip.net/@traiter_lien_explicite
108 108
 function traiter_lien_explicite($ref, $texte = '', $pour = 'url', $connect = '', $echappe_typo = true) {
@@ -119,19 +119,19 @@  discard block
 block discarded – undo
119 119
 		$lien_court = charger_fonction('lien_court', 'inc');
120 120
 		$texte = $lien_court($texte);
121 121
 		if ($echappe_typo) {
122
-			$texte = "<html>" . quote_amp($texte) . "</html>";
122
+			$texte = "<html>".quote_amp($texte)."</html>";
123 123
 		}
124 124
 	}
125 125
 
126 126
 	// petites corrections d'URL
127 127
 	if (preg_match('/^www\.[^@]+$/S', $lien)) {
128
-		$lien = "http://" . $lien;
128
+		$lien = "http://".$lien;
129 129
 	} else {
130 130
 		if (strpos($lien, "@") && email_valide($lien)) {
131 131
 			if (!$texte) {
132 132
 				$texte = $lien;
133 133
 			}
134
-			$lien = "mailto:" . $lien;
134
+			$lien = "mailto:".$lien;
135 135
 		}
136 136
 	}
137 137
 
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 }
148 148
 
149 149
 function liens_implicite_glose_dist($texte, $id, $type, $args, $ancre, $connect = '') {
150
-	if (function_exists($f = 'glossaire_' . $ancre)) {
150
+	if (function_exists($f = 'glossaire_'.$ancre)) {
151 151
 		$url = $f($texte, $id);
152 152
 	} else {
153 153
 		$url = glossaire_std($texte);
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 	if (!($match = typer_raccourci($ref))) {
162 162
 		return false;
163 163
 	}
164
-	@list($type, , $id, , $args, , $ancre) = $match;
164
+	@list($type,, $id,, $args,, $ancre) = $match;
165 165
 	// attention dans le cas des sites le lien doit pointer non pas sur
166 166
 	// la page locale du site, mais directement sur le site lui-meme
167 167
 	if ($f = charger_fonction("implicite_$type", "liens", true)) {
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 		$r['titre'] = $texte;
189 189
 	}
190 190
 	if (!@$r['titre']) {
191
-		$r['titre'] = _T($type) . " $id";
191
+		$r['titre'] = _T($type)." $id";
192 192
 	}
193 193
 	if ($pour == 'titre') {
194 194
 		return $r['titre'];
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 	// dans le cas d'un lien vers un doc, ajouter le type='mime/type'
199 199
 	if ($type == 'document'
200 200
 		and $mime = sql_getfetsel('mime_type', 'spip_types_documents',
201
-			"extension IN (" . sql_get_select("extension", "spip_documents", "id_document=" . sql_quote($id)) . ")",
201
+			"extension IN (".sql_get_select("extension", "spip_documents", "id_document=".sql_quote($id)).")",
202 202
 			'', '', '', '', $connect)
203 203
 	) {
204 204
 		$r['mime'] = $mime;
@@ -295,11 +295,11 @@  discard block
 block discarded – undo
295 295
 	'(<([a-z_-]{3,})' # <modele
296 296
 	. '\s*([0-9]*)\s*' # id
297 297
 	. '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
298
-	. '\s*/?' . '>)' # fin du modele >
298
+	. '\s*/?'.'>)' # fin du modele >
299 299
 	. '\s*(<\/a>)?' # eventuel </a>
300 300
 );
301 301
 
302
-define('_RACCOURCI_MODELE_DEBUT', '@^' . _RACCOURCI_MODELE . '@isS');
302
+define('_RACCOURCI_MODELE_DEBUT', '@^'._RACCOURCI_MODELE.'@isS');
303 303
 
304 304
 // http://code.spip.net/@traiter_modeles
305 305
 function traiter_modeles($texte, $doublons = false, $echap = '', $connect = '', $liens = null, $env = array()) {
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 						if (test_espace_prive()) {
372 372
 							$modele = entites_html(substr($texte, $a, $cherche));
373 373
 							if (!is_null($liens)) {
374
-								$modele = "<pre>" . str_replace($liens[0], $liens[1], $modele) . "</pre>";
374
+								$modele = "<pre>".str_replace($liens[0], $liens[1], $modele)."</pre>";
375 375
 							}
376 376
 						}
377 377
 					}
Please login to merge, or discard this patch.
index.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,3 +1,3 @@
 block discarded – undo
1 1
 <?php
2
-	# appel SPIP
3
-	include('spip.php');
2
+    # appel SPIP
3
+    include('spip.php');
Please login to merge, or discard this patch.
prive/objets/liste/objets-trad_fonctions.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -11,24 +11,24 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 function lister_traductions($id_trad, $objet) {
18
-	$table_objet_sql = table_objet_sql($objet);
19
-	$primary = id_table_objet($objet);
18
+    $table_objet_sql = table_objet_sql($objet);
19
+    $primary = id_table_objet($objet);
20 20
 
21
-	$select = "$primary as id,lang";
22
-	$where = 'id_trad=' . intval($id_trad);
23
-	$trouver_table = charger_fonction('trouver_table','base');
24
-	$desc = $trouver_table($table_objet_sql);
25
-	if (isset($desc['field']['statut'])) {
26
-		$select .= ',statut';
27
-		$where .= ' AND statut!='.sql_quote('poubelle');
28
-	}
21
+    $select = "$primary as id,lang";
22
+    $where = 'id_trad=' . intval($id_trad);
23
+    $trouver_table = charger_fonction('trouver_table','base');
24
+    $desc = $trouver_table($table_objet_sql);
25
+    if (isset($desc['field']['statut'])) {
26
+        $select .= ',statut';
27
+        $where .= ' AND statut!='.sql_quote('poubelle');
28
+    }
29 29
 
30
-	$rows = sql_allfetsel($select, $table_objet_sql, $where);
31
-	lang_select();
30
+    $rows = sql_allfetsel($select, $table_objet_sql, $where);
31
+    lang_select();
32 32
 
33
-	return $rows;
33
+    return $rows;
34 34
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -19,8 +19,8 @@
 block discarded – undo
19 19
 	$primary = id_table_objet($objet);
20 20
 
21 21
 	$select = "$primary as id,lang";
22
-	$where = 'id_trad=' . intval($id_trad);
23
-	$trouver_table = charger_fonction('trouver_table','base');
22
+	$where = 'id_trad='.intval($id_trad);
23
+	$trouver_table = charger_fonction('trouver_table', 'base');
24 24
 	$desc = $trouver_table($table_objet_sql);
25 25
 	if (isset($desc['field']['statut'])) {
26 26
 		$select .= ',statut';
Please login to merge, or discard this patch.