Completed
Pull Request — master (#40)
by
unknown
04:13
created
ecrire/public/jointures.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -231,7 +231,7 @@
 block discarded – undo
231 231
  *
232 232
  * @param array $depart
233 233
  * @param array $arrivee
234
- * @param string|array $col
234
+ * @param string $col
235 235
  * @return bool
236 236
  */
237 237
 function nogroupby_if($depart, $arrivee, $col) {
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 				$echap ?
179 179
 					array("'$id_table'", "'$j2'", "'$j1'", "'$obj='.sql_quote('$type')")
180 180
 					:
181
-					array($id_table, $j2, $j1, "$obj=" . sql_quote($type));
181
+					array($id_table, $j2, $j1, "$obj=".sql_quote($type));
182 182
 		} else {
183 183
 			$boucle->join["L$n"] = $echap ? array("'$id_table'", "'$j'") : array($id_table, $j);
184 184
 		}
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	$groups = liste_champs_jointures($nom, $desc, true);
212 212
 	if (!$pk) {
213 213
 		foreach ($groups as $id_prim) {
214
-			$id_field = $nom . '.' . $id_prim;
214
+			$id_field = $nom.'.'.$id_prim;
215 215
 			if (!in_array($id_field, $boucle->group)) {
216 216
 				$boucle->group[] = $id_field;
217 217
 			}
Please login to merge, or discard this patch.
Indentation   +378 added lines, -378 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
 
@@ -33,11 +33,11 @@  discard block
 block discarded – undo
33 33
  *     Chaine sinon : le nom du champ (non décomposable donc)
34 34
  */
35 35
 function decompose_champ_id_objet($champ) {
36
-	if (($champ !== 'id_objet') and preg_match(',^id_([a-z_]+)$,', $champ, $regs)) {
37
-		return array('id_objet', 'objet', objet_type($regs[1]));
38
-	}
36
+    if (($champ !== 'id_objet') and preg_match(',^id_([a-z_]+)$,', $champ, $regs)) {
37
+        return array('id_objet', 'objet', objet_type($regs[1]));
38
+    }
39 39
 
40
-	return $champ;
40
+    return $champ;
41 41
 }
42 42
 
43 43
 /**
@@ -56,20 +56,20 @@  discard block
 block discarded – undo
56 56
  *     - array(id_objet, objet), si le champ n'existe pas mais qu'on peut décomposer
57 57
  */
58 58
 function trouver_champs_decomposes($champ, $desc) {
59
-	if (!is_array($desc) // on ne se risque pas en conjectures si on ne connait pas la table
60
-		or array_key_exists($champ, $desc['field'])
61
-	) {
62
-		return array($champ);
63
-	}
64
-	// si le champ se décompose, tester que les colonnes décomposées sont présentes
65
-	if (is_array($decompose = decompose_champ_id_objet($champ))) {
66
-		array_pop($decompose);
67
-		if (count(array_intersect($decompose, array_keys($desc['field']))) == count($decompose)) {
68
-			return $decompose;
69
-		}
70
-	}
71
-
72
-	return array($champ);
59
+    if (!is_array($desc) // on ne se risque pas en conjectures si on ne connait pas la table
60
+        or array_key_exists($champ, $desc['field'])
61
+    ) {
62
+        return array($champ);
63
+    }
64
+    // si le champ se décompose, tester que les colonnes décomposées sont présentes
65
+    if (is_array($decompose = decompose_champ_id_objet($champ))) {
66
+        array_pop($decompose);
67
+        if (count(array_intersect($decompose, array_keys($desc['field']))) == count($decompose)) {
68
+            return $decompose;
69
+        }
70
+    }
71
+
72
+    return array($champ);
73 73
 }
74 74
 
75 75
 
@@ -99,23 +99,23 @@  discard block
 block discarded – undo
99 99
  *     Alias de la table de jointure (Lx)
100 100
  */
101 101
 function calculer_jointure(&$boucle, $depart, $arrivee, $col = '', $cond = false, $max_liens = 5) {
102
-	// les jointures minimales sont optimales :
103
-	// on contraint le nombre d'etapes en l'augmentant
104
-	// jusqu'a ce qu'on trouve une jointure ou qu'on atteigne la limite maxi 
105
-	$max = 1;
106
-	$res = false;
107
-	$milieu_exclus = ($col ? $col : array());
108
-	while ($max <= $max_liens and !$res) {
109
-		$res = calculer_chaine_jointures($boucle, $depart, $arrivee, array(), $milieu_exclus, $max);
110
-		$max++;
111
-	}
112
-	if (!$res) {
113
-		return "";
114
-	}
115
-
116
-	list($nom, $desc) = $depart;
117
-
118
-	return fabrique_jointures($boucle, $res, $cond, $desc, $nom, $col);
102
+    // les jointures minimales sont optimales :
103
+    // on contraint le nombre d'etapes en l'augmentant
104
+    // jusqu'a ce qu'on trouve une jointure ou qu'on atteigne la limite maxi 
105
+    $max = 1;
106
+    $res = false;
107
+    $milieu_exclus = ($col ? $col : array());
108
+    while ($max <= $max_liens and !$res) {
109
+        $res = calculer_chaine_jointures($boucle, $depart, $arrivee, array(), $milieu_exclus, $max);
110
+        $max++;
111
+    }
112
+    if (!$res) {
113
+        return "";
114
+    }
115
+
116
+    list($nom, $desc) = $depart;
117
+
118
+    return fabrique_jointures($boucle, $res, $cond, $desc, $nom, $col);
119 119
 }
120 120
 
121 121
 /**
@@ -154,73 +154,73 @@  discard block
 block discarded – undo
154 154
  *     Alias de la table de jointure (Lx)
155 155
  */
156 156
 function fabrique_jointures(&$boucle, $res, $cond = false, $desc = array(), $nom = '', $col = '', $echap = true) {
157
-	static $num = array();
158
-	$id_table = "";
159
-	$cpt = &$num[$boucle->descr['nom']][$boucle->descr['gram']][$boucle->id_boucle];
160
-	foreach ($res as $cle => $r) {
161
-		list($d, $a, $j) = $r;
162
-		if (!$id_table) {
163
-			$id_table = $d;
164
-		}
165
-		$n = ++$cpt;
166
-		if (is_array($j)) { // c'est un lien sur un champ du type id_objet,objet,'article'
167
-			list($j1, $j2, $obj, $type) = $j;
168
-			// trouver de quel cote est (id_objet,objet)
169
-			if ($j1 == "id_$obj") {
170
-				$obj = "$id_table.$obj";
171
-			} else {
172
-				$obj = "L$n.$obj";
173
-			}
174
-			// le where complementaire est envoye dans la jointure pour pouvoir etre elimine avec la jointure
175
-			// en cas d'optimisation
176
-			//$boucle->where[] = array("'='","'$obj'","sql_quote('$type')");
177
-			$boucle->join["L$n"] =
178
-				$echap ?
179
-					array("'$id_table'", "'$j2'", "'$j1'", "'$obj='.sql_quote('$type')")
180
-					:
181
-					array($id_table, $j2, $j1, "$obj=" . sql_quote($type));
182
-		} else {
183
-			$boucle->join["L$n"] = $echap ? array("'$id_table'", "'$j'") : array($id_table, $j);
184
-		}
185
-		$boucle->from[$id_table = "L$n"] = $a[0];
186
-	}
187
-
188
-
189
-	// pas besoin de group by
190
-	// (cf http://article.gmane.org/gmane.comp.web.spip.devel/30555)
191
-	// si une seule jointure et sur une table avec primary key formee
192
-	// de l'index principal et de l'index de jointure (non conditionnel! [6031])
193
-	// et operateur d'egalite (http://trac.rezo.net/trac/spip/ticket/477)
194
-
195
-	if ($pk = (isset($a[1]) && (count($boucle->from) == 2) && !$cond)) {
196
-		$pk = nogroupby_if($desc, $a[1], $col);
197
-	}
198
-
199
-	// pas de group by 
200
-	// si une seule jointure
201
-	// et si l'index de jointure est une primary key a l'arrivee !
202
-	if (!$pk
203
-		and (count($boucle->from) == 2)
204
-		and isset($a[1]['key']['PRIMARY KEY'])
205
-		and ($j == $a[1]['key']['PRIMARY KEY'])
206
-	) {
207
-		$pk = true;
208
-	}
209
-
210
-	// la clause Group by est en conflit avec ORDER BY, a completer
211
-	$groups = liste_champs_jointures($nom, $desc, true);
212
-	if (!$pk) {
213
-		foreach ($groups as $id_prim) {
214
-			$id_field = $nom . '.' . $id_prim;
215
-			if (!in_array($id_field, $boucle->group)) {
216
-				$boucle->group[] = $id_field;
217
-			}
218
-		}
219
-	}
220
-
221
-	$boucle->modificateur['lien'] = true;
222
-
223
-	return "L$n";
157
+    static $num = array();
158
+    $id_table = "";
159
+    $cpt = &$num[$boucle->descr['nom']][$boucle->descr['gram']][$boucle->id_boucle];
160
+    foreach ($res as $cle => $r) {
161
+        list($d, $a, $j) = $r;
162
+        if (!$id_table) {
163
+            $id_table = $d;
164
+        }
165
+        $n = ++$cpt;
166
+        if (is_array($j)) { // c'est un lien sur un champ du type id_objet,objet,'article'
167
+            list($j1, $j2, $obj, $type) = $j;
168
+            // trouver de quel cote est (id_objet,objet)
169
+            if ($j1 == "id_$obj") {
170
+                $obj = "$id_table.$obj";
171
+            } else {
172
+                $obj = "L$n.$obj";
173
+            }
174
+            // le where complementaire est envoye dans la jointure pour pouvoir etre elimine avec la jointure
175
+            // en cas d'optimisation
176
+            //$boucle->where[] = array("'='","'$obj'","sql_quote('$type')");
177
+            $boucle->join["L$n"] =
178
+                $echap ?
179
+                    array("'$id_table'", "'$j2'", "'$j1'", "'$obj='.sql_quote('$type')")
180
+                    :
181
+                    array($id_table, $j2, $j1, "$obj=" . sql_quote($type));
182
+        } else {
183
+            $boucle->join["L$n"] = $echap ? array("'$id_table'", "'$j'") : array($id_table, $j);
184
+        }
185
+        $boucle->from[$id_table = "L$n"] = $a[0];
186
+    }
187
+
188
+
189
+    // pas besoin de group by
190
+    // (cf http://article.gmane.org/gmane.comp.web.spip.devel/30555)
191
+    // si une seule jointure et sur une table avec primary key formee
192
+    // de l'index principal et de l'index de jointure (non conditionnel! [6031])
193
+    // et operateur d'egalite (http://trac.rezo.net/trac/spip/ticket/477)
194
+
195
+    if ($pk = (isset($a[1]) && (count($boucle->from) == 2) && !$cond)) {
196
+        $pk = nogroupby_if($desc, $a[1], $col);
197
+    }
198
+
199
+    // pas de group by 
200
+    // si une seule jointure
201
+    // et si l'index de jointure est une primary key a l'arrivee !
202
+    if (!$pk
203
+        and (count($boucle->from) == 2)
204
+        and isset($a[1]['key']['PRIMARY KEY'])
205
+        and ($j == $a[1]['key']['PRIMARY KEY'])
206
+    ) {
207
+        $pk = true;
208
+    }
209
+
210
+    // la clause Group by est en conflit avec ORDER BY, a completer
211
+    $groups = liste_champs_jointures($nom, $desc, true);
212
+    if (!$pk) {
213
+        foreach ($groups as $id_prim) {
214
+            $id_field = $nom . '.' . $id_prim;
215
+            if (!in_array($id_field, $boucle->group)) {
216
+                $boucle->group[] = $id_field;
217
+            }
218
+        }
219
+    }
220
+
221
+    $boucle->modificateur['lien'] = true;
222
+
223
+    return "L$n";
224 224
 }
225 225
 
226 226
 /**
@@ -235,16 +235,16 @@  discard block
 block discarded – undo
235 235
  * @return bool
236 236
  */
237 237
 function nogroupby_if($depart, $arrivee, $col) {
238
-	$pk = $arrivee['key']['PRIMARY KEY'];
239
-	if (!$pk) {
240
-		return false;
241
-	}
242
-	$id_primary = $depart['key']['PRIMARY KEY'];
243
-	if (is_array($col)) {
244
-		$col = implode(', *', $col);
245
-	} // cas id_objet, objet
246
-	return (preg_match("/^$id_primary, *$col$/", $pk) or
247
-		preg_match("/^$col, *$id_primary$/", $pk));
238
+    $pk = $arrivee['key']['PRIMARY KEY'];
239
+    if (!$pk) {
240
+        return false;
241
+    }
242
+    $id_primary = $depart['key']['PRIMARY KEY'];
243
+    if (is_array($col)) {
244
+        $col = implode(', *', $col);
245
+    } // cas id_objet, objet
246
+    return (preg_match("/^$id_primary, *$col$/", $pk) or
247
+        preg_match("/^$col, *$id_primary$/", $pk));
248 248
 }
249 249
 
250 250
 /**
@@ -262,46 +262,46 @@  discard block
 block discarded – undo
262 262
  */
263 263
 function liste_champs_jointures($nom, $desc, $primary = false) {
264 264
 
265
-	static $nojoin = array('idx', 'maj', 'date', 'statut');
265
+    static $nojoin = array('idx', 'maj', 'date', 'statut');
266 266
 
267
-	// si cle primaire demandee, la privilegier
268
-	if ($primary && isset($desc['key']['PRIMARY KEY'])) {
269
-		return split_key($desc['key']['PRIMARY KEY']);
270
-	}
267
+    // si cle primaire demandee, la privilegier
268
+    if ($primary && isset($desc['key']['PRIMARY KEY'])) {
269
+        return split_key($desc['key']['PRIMARY KEY']);
270
+    }
271 271
 
272
-	// les champs declares explicitement pour les jointures
273
-	if (isset($desc['join'])) {
274
-		return $desc['join'];
275
-	}
276
-	/*elseif (isset($GLOBALS['tables_principales'][$nom]['join'])) return $GLOBALS['tables_principales'][$nom]['join'];
272
+    // les champs declares explicitement pour les jointures
273
+    if (isset($desc['join'])) {
274
+        return $desc['join'];
275
+    }
276
+    /*elseif (isset($GLOBALS['tables_principales'][$nom]['join'])) return $GLOBALS['tables_principales'][$nom]['join'];
277 277
 	elseif (isset($GLOBALS['tables_auxiliaires'][$nom]['join'])) return $GLOBALS['tables_auxiliaires'][$nom]['join'];*/
278 278
 
279
-	// si pas de cle, c'est fichu
280
-	if (!isset($desc['key'])) {
281
-		return array();
282
-	}
283
-
284
-	// si cle primaire
285
-	if (isset($desc['key']['PRIMARY KEY'])) {
286
-		return split_key($desc['key']['PRIMARY KEY']);
287
-	}
288
-
289
-	// ici on se rabat sur les cles secondaires, 
290
-	// en eliminant celles qui sont pas pertinentes (idx, maj)
291
-	// si jamais le resultat n'est pas pertinent pour une table donnee,
292
-	// il faut declarer explicitement le champ 'join' de sa description
293
-
294
-	$join = array();
295
-	foreach ($desc['key'] as $v) {
296
-		$join = split_key($v, $join);
297
-	}
298
-	foreach ($join as $k) {
299
-		if (in_array($k, $nojoin)) {
300
-			unset($join[$k]);
301
-		}
302
-	}
303
-
304
-	return $join;
279
+    // si pas de cle, c'est fichu
280
+    if (!isset($desc['key'])) {
281
+        return array();
282
+    }
283
+
284
+    // si cle primaire
285
+    if (isset($desc['key']['PRIMARY KEY'])) {
286
+        return split_key($desc['key']['PRIMARY KEY']);
287
+    }
288
+
289
+    // ici on se rabat sur les cles secondaires, 
290
+    // en eliminant celles qui sont pas pertinentes (idx, maj)
291
+    // si jamais le resultat n'est pas pertinent pour une table donnee,
292
+    // il faut declarer explicitement le champ 'join' de sa description
293
+
294
+    $join = array();
295
+    foreach ($desc['key'] as $v) {
296
+        $join = split_key($v, $join);
297
+    }
298
+    foreach ($join as $k) {
299
+        if (in_array($k, $nojoin)) {
300
+            unset($join[$k]);
301
+        }
302
+    }
303
+
304
+    return $join;
305 305
 }
306 306
 
307 307
 /**
@@ -312,14 +312,14 @@  discard block
 block discarded – undo
312 312
  * @return array
313 313
  */
314 314
 function split_key($v, $join = array()) {
315
-	foreach (preg_split('/,\s*/', $v) as $k) {
316
-		if (strpos($k, '(') !== false) {
317
-			$k = explode('(', $k);
318
-			$k = trim(reset($k));
319
-		}
320
-		$join[$k] = $k;
321
-	}
322
-	return $join;
315
+    foreach (preg_split('/,\s*/', $v) as $k) {
316
+        if (strpos($k, '(') !== false) {
317
+            $k = explode('(', $k);
318
+            $k = trim(reset($k));
319
+        }
320
+        $join[$k] = $k;
321
+    }
322
+    return $join;
323 323
 }
324 324
 
325 325
 /**
@@ -342,126 +342,126 @@  discard block
 block discarded – undo
342 342
  * @return array
343 343
  */
344 344
 function calculer_chaine_jointures(
345
-	&$boucle,
346
-	$depart,
347
-	$arrivee,
348
-	$vu = array(),
349
-	$milieu_exclus = array(),
350
-	$max_liens = 5
345
+    &$boucle,
346
+    $depart,
347
+    $arrivee,
348
+    $vu = array(),
349
+    $milieu_exclus = array(),
350
+    $max_liens = 5
351 351
 ) {
352
-	static $trouver_table;
353
-	if (!$trouver_table) {
354
-		$trouver_table = charger_fonction('trouver_table', 'base');
355
-	}
356
-
357
-	if (is_string($milieu_exclus)) {
358
-		$milieu_exclus = array($milieu_exclus);
359
-	}
360
-	// quand on a exclus id_objet comme cle de jointure, il faut aussi exclure objet
361
-	// faire une jointure sur objet tout seul n'a pas de sens
362
-	if (in_array('id_objet', $milieu_exclus) and !in_array('objet', $milieu_exclus)) {
363
-		$milieu_exclus[] = 'objet';
364
-	}
365
-
366
-	list($dnom, $ddesc) = $depart;
367
-	list($anom, $adesc) = $arrivee;
368
-	if (!count($vu)) {
369
-		$vu[] = $dnom; // ne pas oublier la table de depart
370
-		$vu[] = $anom; // ne pas oublier la table d'arrivee
371
-	}
372
-
373
-	$akeys = array();
374
-	foreach ($adesc['key'] as $k) {
375
-		// respecter l'ordre de $adesc['key'] pour ne pas avoir id_trad en premier entre autres...
376
-		$akeys = array_merge($akeys, preg_split('/,\s*/', $k));
377
-	}
378
-
379
-	// enlever les cles d'arrivee exclues par l'appel
380
-	$akeys = array_diff($akeys, $milieu_exclus);
381
-
382
-	// cles candidates au depart
383
-	$keys = liste_champs_jointures($dnom, $ddesc);
384
-	// enlever les cles dde depart exclues par l'appel
385
-	$keys = array_diff($keys, $milieu_exclus);
386
-
387
-	$v = !$keys ? false : array_intersect(array_values($keys), $akeys);
388
-
389
-	if ($v) {
390
-		return array(array($dnom, array($adesc['table'], $adesc), array_shift($v)));
391
-	}
392
-
393
-	// regarder si l'on a (id_objet,objet) au depart et si on peut le mapper sur un id_xx
394
-	if (count(array_intersect(array('id_objet', 'objet'), $keys)) == 2) {
395
-		// regarder si l'une des cles d'arrivee peut se decomposer en 
396
-		// id_objet,objet
397
-		// si oui on la prend
398
-		foreach ($akeys as $key) {
399
-			$v = decompose_champ_id_objet($key);
400
-			if (is_array($v)) {
401
-				$objet = array_shift($v); // objet,'article'
402
-				array_unshift($v, $key); // id_article,objet,'article'
403
-				array_unshift($v, $objet); // id_objet,id_article,objet,'article'
404
-				return array(array($dnom, array($adesc['table'], $adesc), $v));
405
-			}
406
-		}
407
-	} else {
408
-		// regarder si l'une des cles de depart peut se decomposer en 
409
-		// id_objet,objet a l'arrivee
410
-		// si oui on la prend
411
-		foreach ($keys as $key) {
412
-			if (count($v = trouver_champs_decomposes($key, $adesc)) > 1) {
413
-				if (count($v) == count(array_intersect($v, $akeys))) {
414
-					$v = decompose_champ_id_objet($key); // id_objet,objet,'article'
415
-					array_unshift($v, $key); // id_article,id_objet,objet,'article'
416
-					return array(array($dnom, array($adesc['table'], $adesc), $v));
417
-				}
418
-			}
419
-		}
420
-	}
421
-	// si l'on voulait une jointure direct, c'est rate !
422
-	if ($max_liens <= 1) {
423
-		return array();
424
-	}
425
-
426
-	// sinon essayer de passer par une autre table
427
-	$new = $vu;
428
-	foreach ($boucle->jointures as $v) {
429
-		if ($v
430
-			and !in_array($v, $vu)
431
-			and $def = $trouver_table($v, $boucle->sql_serveur)
432
-			and !in_array($def['table_sql'], $vu)
433
-		) {
434
-			// ne pas tester les cles qui sont exclues a l'appel
435
-			// ie la cle de la jointure precedente
436
-			$test_cles = $milieu_exclus;
437
-			$new[] = $v;
438
-			$max_iter = 50; // securite
439
-			while (count($jointure_directe_possible = calculer_chaine_jointures($boucle, $depart, array($v, $def), $vu,
440
-					$test_cles, 1))
441
-				and $max_iter--) {
442
-				$jointure_directe_possible = reset($jointure_directe_possible);
443
-				$milieu = end($jointure_directe_possible);
444
-				$exclure_fin = $milieu_exclus;
445
-				if (is_string($milieu)) {
446
-					$exclure_fin[] = $milieu;
447
-					$test_cles[] = $milieu;
448
-				} else {
449
-					$exclure_fin = array_merge($exclure_fin, $milieu);
450
-					$test_cles = array_merge($test_cles, $milieu);
451
-				}
452
-				// essayer de rejoindre l'arrivee a partir de cette etape intermediaire
453
-				// sans repasser par la meme cle milieu, ni une cle deja vue !
454
-				$r = calculer_chaine_jointures($boucle, array($v, $def), $arrivee, $new, $exclure_fin, $max_liens - 1);
455
-				if ($r) {
456
-					array_unshift($r, $jointure_directe_possible);
457
-
458
-					return $r;
459
-				}
460
-			}
461
-		}
462
-	}
463
-
464
-	return array();
352
+    static $trouver_table;
353
+    if (!$trouver_table) {
354
+        $trouver_table = charger_fonction('trouver_table', 'base');
355
+    }
356
+
357
+    if (is_string($milieu_exclus)) {
358
+        $milieu_exclus = array($milieu_exclus);
359
+    }
360
+    // quand on a exclus id_objet comme cle de jointure, il faut aussi exclure objet
361
+    // faire une jointure sur objet tout seul n'a pas de sens
362
+    if (in_array('id_objet', $milieu_exclus) and !in_array('objet', $milieu_exclus)) {
363
+        $milieu_exclus[] = 'objet';
364
+    }
365
+
366
+    list($dnom, $ddesc) = $depart;
367
+    list($anom, $adesc) = $arrivee;
368
+    if (!count($vu)) {
369
+        $vu[] = $dnom; // ne pas oublier la table de depart
370
+        $vu[] = $anom; // ne pas oublier la table d'arrivee
371
+    }
372
+
373
+    $akeys = array();
374
+    foreach ($adesc['key'] as $k) {
375
+        // respecter l'ordre de $adesc['key'] pour ne pas avoir id_trad en premier entre autres...
376
+        $akeys = array_merge($akeys, preg_split('/,\s*/', $k));
377
+    }
378
+
379
+    // enlever les cles d'arrivee exclues par l'appel
380
+    $akeys = array_diff($akeys, $milieu_exclus);
381
+
382
+    // cles candidates au depart
383
+    $keys = liste_champs_jointures($dnom, $ddesc);
384
+    // enlever les cles dde depart exclues par l'appel
385
+    $keys = array_diff($keys, $milieu_exclus);
386
+
387
+    $v = !$keys ? false : array_intersect(array_values($keys), $akeys);
388
+
389
+    if ($v) {
390
+        return array(array($dnom, array($adesc['table'], $adesc), array_shift($v)));
391
+    }
392
+
393
+    // regarder si l'on a (id_objet,objet) au depart et si on peut le mapper sur un id_xx
394
+    if (count(array_intersect(array('id_objet', 'objet'), $keys)) == 2) {
395
+        // regarder si l'une des cles d'arrivee peut se decomposer en 
396
+        // id_objet,objet
397
+        // si oui on la prend
398
+        foreach ($akeys as $key) {
399
+            $v = decompose_champ_id_objet($key);
400
+            if (is_array($v)) {
401
+                $objet = array_shift($v); // objet,'article'
402
+                array_unshift($v, $key); // id_article,objet,'article'
403
+                array_unshift($v, $objet); // id_objet,id_article,objet,'article'
404
+                return array(array($dnom, array($adesc['table'], $adesc), $v));
405
+            }
406
+        }
407
+    } else {
408
+        // regarder si l'une des cles de depart peut se decomposer en 
409
+        // id_objet,objet a l'arrivee
410
+        // si oui on la prend
411
+        foreach ($keys as $key) {
412
+            if (count($v = trouver_champs_decomposes($key, $adesc)) > 1) {
413
+                if (count($v) == count(array_intersect($v, $akeys))) {
414
+                    $v = decompose_champ_id_objet($key); // id_objet,objet,'article'
415
+                    array_unshift($v, $key); // id_article,id_objet,objet,'article'
416
+                    return array(array($dnom, array($adesc['table'], $adesc), $v));
417
+                }
418
+            }
419
+        }
420
+    }
421
+    // si l'on voulait une jointure direct, c'est rate !
422
+    if ($max_liens <= 1) {
423
+        return array();
424
+    }
425
+
426
+    // sinon essayer de passer par une autre table
427
+    $new = $vu;
428
+    foreach ($boucle->jointures as $v) {
429
+        if ($v
430
+            and !in_array($v, $vu)
431
+            and $def = $trouver_table($v, $boucle->sql_serveur)
432
+            and !in_array($def['table_sql'], $vu)
433
+        ) {
434
+            // ne pas tester les cles qui sont exclues a l'appel
435
+            // ie la cle de la jointure precedente
436
+            $test_cles = $milieu_exclus;
437
+            $new[] = $v;
438
+            $max_iter = 50; // securite
439
+            while (count($jointure_directe_possible = calculer_chaine_jointures($boucle, $depart, array($v, $def), $vu,
440
+                    $test_cles, 1))
441
+                and $max_iter--) {
442
+                $jointure_directe_possible = reset($jointure_directe_possible);
443
+                $milieu = end($jointure_directe_possible);
444
+                $exclure_fin = $milieu_exclus;
445
+                if (is_string($milieu)) {
446
+                    $exclure_fin[] = $milieu;
447
+                    $test_cles[] = $milieu;
448
+                } else {
449
+                    $exclure_fin = array_merge($exclure_fin, $milieu);
450
+                    $test_cles = array_merge($test_cles, $milieu);
451
+                }
452
+                // essayer de rejoindre l'arrivee a partir de cette etape intermediaire
453
+                // sans repasser par la meme cle milieu, ni une cle deja vue !
454
+                $r = calculer_chaine_jointures($boucle, array($v, $def), $arrivee, $new, $exclure_fin, $max_liens - 1);
455
+                if ($r) {
456
+                    array_unshift($r, $jointure_directe_possible);
457
+
458
+                    return $r;
459
+                }
460
+            }
461
+        }
462
+    }
463
+
464
+    return array();
465 465
 }
466 466
 
467 467
 /**
@@ -472,18 +472,18 @@  discard block
 block discarded – undo
472 472
  * @return array
473 473
  */
474 474
 function trouver_cles_table($keys) {
475
-	$res = array();
476
-	foreach ($keys as $v) {
477
-		if (!strpos($v, ",")) {
478
-			$res[$v] = 1;
479
-		} else {
480
-			foreach (preg_split("/\s*,\s*/", $v) as $k) {
481
-				$res[$k] = 1;
482
-			}
483
-		}
484
-	}
485
-
486
-	return array_keys($res);
475
+    $res = array();
476
+    foreach ($keys as $v) {
477
+        if (!strpos($v, ",")) {
478
+            $res[$v] = 1;
479
+        } else {
480
+            foreach (preg_split("/\s*,\s*/", $v) as $k) {
481
+                $res[$k] = 1;
482
+            }
483
+        }
484
+    }
485
+
486
+    return array_keys($res);
487 487
 }
488 488
 
489 489
 
@@ -510,33 +510,33 @@  discard block
 block discarded – undo
510 510
  *     - 'alias' : alias utilisé pour la table (si pertinent. ie: avec `$boucle->from` transmis par exemple)
511 511
  */
512 512
 function chercher_champ_dans_tables($cle, $tables, $connect, $checkarrivee = false) {
513
-	static $trouver_table = '';
514
-	if (!$trouver_table) {
515
-		$trouver_table = charger_fonction('trouver_table', 'base');
516
-	}
517
-
518
-	if (!is_array($cle)) {
519
-		$cle = array($cle);
520
-	}
521
-
522
-	foreach ($tables as $k => $table) {
523
-		if ($table && $desc = $trouver_table($table, $connect)) {
524
-			if (isset($desc['field'])
525
-				// verifier que toutes les cles cherchees sont la
526
-				and (count(array_intersect($cle, array_keys($desc['field']))) == count($cle))
527
-				// si on sait ou on veut arriver, il faut que ca colle
528
-				and ($checkarrivee == false || $checkarrivee == $desc['table'])
529
-			) {
530
-				return array(
531
-					'desc' => $desc,
532
-					'table' => $desc['table'],
533
-					'alias' => $k,
534
-				);
535
-			}
536
-		}
537
-	}
538
-
539
-	return false;
513
+    static $trouver_table = '';
514
+    if (!$trouver_table) {
515
+        $trouver_table = charger_fonction('trouver_table', 'base');
516
+    }
517
+
518
+    if (!is_array($cle)) {
519
+        $cle = array($cle);
520
+    }
521
+
522
+    foreach ($tables as $k => $table) {
523
+        if ($table && $desc = $trouver_table($table, $connect)) {
524
+            if (isset($desc['field'])
525
+                // verifier que toutes les cles cherchees sont la
526
+                and (count(array_intersect($cle, array_keys($desc['field']))) == count($cle))
527
+                // si on sait ou on veut arriver, il faut que ca colle
528
+                and ($checkarrivee == false || $checkarrivee == $desc['table'])
529
+            ) {
530
+                return array(
531
+                    'desc' => $desc,
532
+                    'table' => $desc['table'],
533
+                    'alias' => $k,
534
+                );
535
+            }
536
+        }
537
+    }
538
+
539
+    return false;
540 540
 }
541 541
 
542 542
 /**
@@ -562,52 +562,52 @@  discard block
 block discarded – undo
562 562
  */
563 563
 function trouver_champ_exterieur($cle, $joints, &$boucle, $checkarrivee = false) {
564 564
 
565
-	// support de la recherche multi champ :
566
-	// si en seconde etape on a decompose le champ id_xx en id_objet,objet
567
-	// on reentre ici soit en cherchant une table les 2 champs id_objet,objet
568
-	// soit une table avec les 3 champs id_xx, id_objet, objet
569
-	if (!is_array($cle)) {
570
-		$cle = array($cle);
571
-	}
572
-
573
-	if ($infos = chercher_champ_dans_tables($cle, $joints, $boucle->sql_serveur, $checkarrivee)) {
574
-		return array($infos['table'], $infos['desc'], $cle);
575
-	}
576
-
577
-	// au premier coup, on essaye de decomposer, si possible
578
-	if (count($cle) == 1
579
-		and $c = reset($cle)
580
-		and is_array($decompose = decompose_champ_id_objet($c))
581
-	) {
582
-
583
-		$desc = $boucle->show;
584
-
585
-		// cas 1 : la cle id_xx est dans la table de depart
586
-		// -> on cherche uniquement id_objet,objet a l'arrivee
587
-		if (isset($desc['field'][$c])) {
588
-			$cle = array();
589
-			$cle[] = array_shift($decompose); // id_objet
590
-			$cle[] = array_shift($decompose); // objet
591
-			return trouver_champ_exterieur($cle, $joints, $boucle, $checkarrivee);
592
-		}
593
-		// cas 2 : la cle id_xx n'est pas dans la table de depart
594
-		// -> il faut trouver une cle de depart zzz telle que
595
-		// id_objet,objet,zzz soit a l'arrivee
596
-		else {
597
-			$depart = liste_champs_jointures((isset($desc['table']) ? $desc['table'] : ''), $desc);
598
-			foreach ($depart as $d) {
599
-				$cle = array();
600
-				$cle[] = array_shift($decompose); // id_objet
601
-				$cle[] = array_shift($decompose); // objet
602
-				$cle[] = $d;
603
-				if ($ext = trouver_champ_exterieur($cle, $joints, $boucle, $checkarrivee)) {
604
-					return $ext;
605
-				}
606
-			}
607
-		}
608
-	}
609
-
610
-	return "";
565
+    // support de la recherche multi champ :
566
+    // si en seconde etape on a decompose le champ id_xx en id_objet,objet
567
+    // on reentre ici soit en cherchant une table les 2 champs id_objet,objet
568
+    // soit une table avec les 3 champs id_xx, id_objet, objet
569
+    if (!is_array($cle)) {
570
+        $cle = array($cle);
571
+    }
572
+
573
+    if ($infos = chercher_champ_dans_tables($cle, $joints, $boucle->sql_serveur, $checkarrivee)) {
574
+        return array($infos['table'], $infos['desc'], $cle);
575
+    }
576
+
577
+    // au premier coup, on essaye de decomposer, si possible
578
+    if (count($cle) == 1
579
+        and $c = reset($cle)
580
+        and is_array($decompose = decompose_champ_id_objet($c))
581
+    ) {
582
+
583
+        $desc = $boucle->show;
584
+
585
+        // cas 1 : la cle id_xx est dans la table de depart
586
+        // -> on cherche uniquement id_objet,objet a l'arrivee
587
+        if (isset($desc['field'][$c])) {
588
+            $cle = array();
589
+            $cle[] = array_shift($decompose); // id_objet
590
+            $cle[] = array_shift($decompose); // objet
591
+            return trouver_champ_exterieur($cle, $joints, $boucle, $checkarrivee);
592
+        }
593
+        // cas 2 : la cle id_xx n'est pas dans la table de depart
594
+        // -> il faut trouver une cle de depart zzz telle que
595
+        // id_objet,objet,zzz soit a l'arrivee
596
+        else {
597
+            $depart = liste_champs_jointures((isset($desc['table']) ? $desc['table'] : ''), $desc);
598
+            foreach ($depart as $d) {
599
+                $cle = array();
600
+                $cle[] = array_shift($decompose); // id_objet
601
+                $cle[] = array_shift($decompose); // objet
602
+                $cle[] = $d;
603
+                if ($ext = trouver_champ_exterieur($cle, $joints, $boucle, $checkarrivee)) {
604
+                    return $ext;
605
+                }
606
+            }
607
+        }
608
+    }
609
+
610
+    return "";
611 611
 }
612 612
 
613 613
 /**
@@ -639,21 +639,21 @@  discard block
 block discarded – undo
639 639
  * @return string
640 640
  */
641 641
 function trouver_jointure_champ($champ, &$boucle, $jointures = false, $cond = false, $checkarrivee = false) {
642
-	if ($jointures === false) {
643
-		$jointures = $boucle->jointures;
644
-	}
645
-	// TODO : aberration, on utilise $jointures pour trouver le champ
646
-	// mais pas poour construire la jointure ensuite
647
-	$arrivee = trouver_champ_exterieur($champ, $jointures, $boucle, $checkarrivee);
648
-	if ($arrivee) {
649
-		$desc = $boucle->show;
650
-		array_pop($arrivee); // enlever la cle en 3eme argument
651
-		$cle = calculer_jointure($boucle, array($desc['id_table'], $desc), $arrivee, '', $cond);
652
-		if ($cle) {
653
-			return $cle;
654
-		}
655
-	}
656
-	spip_log("trouver_jointure_champ: $champ inconnu");
657
-
658
-	return '';
642
+    if ($jointures === false) {
643
+        $jointures = $boucle->jointures;
644
+    }
645
+    // TODO : aberration, on utilise $jointures pour trouver le champ
646
+    // mais pas poour construire la jointure ensuite
647
+    $arrivee = trouver_champ_exterieur($champ, $jointures, $boucle, $checkarrivee);
648
+    if ($arrivee) {
649
+        $desc = $boucle->show;
650
+        array_pop($arrivee); // enlever la cle en 3eme argument
651
+        $cle = calculer_jointure($boucle, array($desc['id_table'], $desc), $arrivee, '', $cond);
652
+        if ($cle) {
653
+            return $cle;
654
+        }
655
+    }
656
+    spip_log("trouver_jointure_champ: $champ inconnu");
657
+
658
+    return '';
659 659
 }
Please login to merge, or discard this patch.
ecrire/public/normaliser.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -75,6 +75,9 @@
 block discarded – undo
75 75
 }
76 76
 
77 77
 
78
+/**
79
+ * @param string $nom
80
+ */
78 81
 function phraser_logo_faux_filtres($nom) {
79 82
 	switch ($nom) {
80 83
 		case 'top':
Please login to merge, or discard this patch.
Indentation   +159 added lines, -159 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
 // Les fonctions de ce fichier sont appelees en certains points 
@@ -25,135 +25,135 @@  discard block
 block discarded – undo
25 25
 // -> http://www.spip.net/fr_article901.html
26 26
 
27 27
 function phraser_vieux_logos(&$p) {
28
-	if ($p->param[0][0]) {
29
-		$args = array('');
30
-	} else {
31
-		$args = array_shift($p->param);
32
-	}
33
-
34
-	foreach ($p->param as $couple) {
35
-		$nom = trim($couple[0]);
36
-		if ($nom == '') {
37
-			array_shift($p->param);
38
-			break;
39
-		}
40
-		$r = phraser_logo_faux_filtres($nom);
41
-		if ($r === 0) {
42
-			$c = new Texte;
43
-			$c->texte = $nom;
44
-			$args[] = array($c);
45
-			array_shift($p->param);
46
-			spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
47
-		} elseif ($r === 2) {
48
-			$p->etoile = '**';
49
-			array_shift($p->param);
50
-			spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
51
-		} elseif ($r === 1) {
52
-			array_shift($p->param);
53
-			$p->etoile = '*';
54
-			spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
55
-
56
-		} elseif (preg_match("/^" . NOM_DE_CHAMP . '(.*)$/sS', $nom, $m)) {
57
-			$champ = new Champ();
58
-			$champ->nom_boucle = $m[2];
59
-			$champ->nom_champ = $m[3];
60
-			$champ->etoile = $m[5];
61
-			$champ = array($champ);
62
-			if ($m[6]) {
63
-				$r = new Texte;
64
-				$r->texte = $m[6];
65
-				$champ[] = $r;
66
-			}
67
-			$args[] = $champ;
68
-			array_shift($p->param);
69
-			spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
70
-
71
-		} // le cas else est la seule incompatibilite
72
-
73
-	}
74
-	array_unshift($p->param, $args);
28
+    if ($p->param[0][0]) {
29
+        $args = array('');
30
+    } else {
31
+        $args = array_shift($p->param);
32
+    }
33
+
34
+    foreach ($p->param as $couple) {
35
+        $nom = trim($couple[0]);
36
+        if ($nom == '') {
37
+            array_shift($p->param);
38
+            break;
39
+        }
40
+        $r = phraser_logo_faux_filtres($nom);
41
+        if ($r === 0) {
42
+            $c = new Texte;
43
+            $c->texte = $nom;
44
+            $args[] = array($c);
45
+            array_shift($p->param);
46
+            spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
47
+        } elseif ($r === 2) {
48
+            $p->etoile = '**';
49
+            array_shift($p->param);
50
+            spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
51
+        } elseif ($r === 1) {
52
+            array_shift($p->param);
53
+            $p->etoile = '*';
54
+            spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
55
+
56
+        } elseif (preg_match("/^" . NOM_DE_CHAMP . '(.*)$/sS', $nom, $m)) {
57
+            $champ = new Champ();
58
+            $champ->nom_boucle = $m[2];
59
+            $champ->nom_champ = $m[3];
60
+            $champ->etoile = $m[5];
61
+            $champ = array($champ);
62
+            if ($m[6]) {
63
+                $r = new Texte;
64
+                $r->texte = $m[6];
65
+                $champ[] = $r;
66
+            }
67
+            $args[] = $champ;
68
+            array_shift($p->param);
69
+            spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
70
+
71
+        } // le cas else est la seule incompatibilite
72
+
73
+    }
74
+    array_unshift($p->param, $args);
75 75
 }
76 76
 
77 77
 
78 78
 function phraser_logo_faux_filtres($nom) {
79
-	switch ($nom) {
80
-		case 'top':
81
-		case 'left':
82
-		case 'right':
83
-		case 'center':
84
-		case 'bottom':
85
-			return 0;
86
-		case 'lien':
87
-			return 1;
88
-		case 'fichier':
89
-			return 2;
90
-		default:
91
-			return $nom;
92
-	}
79
+    switch ($nom) {
80
+        case 'top':
81
+        case 'left':
82
+        case 'right':
83
+        case 'center':
84
+        case 'bottom':
85
+            return 0;
86
+        case 'lien':
87
+            return 1;
88
+        case 'fichier':
89
+            return 2;
90
+        default:
91
+            return $nom;
92
+    }
93 93
 }
94 94
 
95 95
 
96 96
 // La balise embed_document est a present le modele emb
97 97
 
98 98
 function phraser_vieux_emb(&$p) {
99
-	if (!is_array($p->param)) {
100
-		$p->param = array();
101
-	}
102
-
103
-	// Produire le premier argument {emb}
104
-	$texte = new Texte;
105
-	$texte->texte = 'emb';
106
-	$param = array('', array($texte));
107
-
108
-	// Transformer les filtres en arguments
109
-	for ($i = 0; $i < count($p->param); $i++) {
110
-		if ($p->param[$i][0]) {
111
-			if (!strstr($p->param[$i][0], '=')) {
112
-				break;
113
-			}# on a rencontre un vrai filtre, c'est fini
114
-			$texte = new Texte;
115
-			$texte->texte = $p->param[$i][0];
116
-			$param[] = array($texte);
117
-		}
118
-		array_shift($p->param);
119
-	}
120
-	array_unshift($p->param, $param);
121
-	spip_log('balise EMBED_DOCUMENT obsolete', 'vieilles_defs');
122
-	$p->nom_champ = 'MODELE';
99
+    if (!is_array($p->param)) {
100
+        $p->param = array();
101
+    }
102
+
103
+    // Produire le premier argument {emb}
104
+    $texte = new Texte;
105
+    $texte->texte = 'emb';
106
+    $param = array('', array($texte));
107
+
108
+    // Transformer les filtres en arguments
109
+    for ($i = 0; $i < count($p->param); $i++) {
110
+        if ($p->param[$i][0]) {
111
+            if (!strstr($p->param[$i][0], '=')) {
112
+                break;
113
+            }# on a rencontre un vrai filtre, c'est fini
114
+            $texte = new Texte;
115
+            $texte->texte = $p->param[$i][0];
116
+            $param[] = array($texte);
117
+        }
118
+        array_shift($p->param);
119
+    }
120
+    array_unshift($p->param, $param);
121
+    spip_log('balise EMBED_DOCUMENT obsolete', 'vieilles_defs');
122
+    $p->nom_champ = 'MODELE';
123 123
 }
124 124
 
125 125
 // Vieux formulaire de recherch
126 126
 
127 127
 function phraser_vieux_recherche($p) {
128
-	if ($p->param[0][0]) {
129
-		$c = new Texte;
130
-		$c->texte = $p->param[0][0];
131
-		$p->param[0][1] = array($c);
132
-		$p->param[0][0] = '';
133
-		$p->fonctions = array();
134
-		spip_log('FORMULAIRE_RECHERCHE avec filtre ' . $c->texte, 'vieilles_defs');
135
-	}
128
+    if ($p->param[0][0]) {
129
+        $c = new Texte;
130
+        $c->texte = $p->param[0][0];
131
+        $p->param[0][1] = array($c);
132
+        $p->param[0][0] = '';
133
+        $p->fonctions = array();
134
+        spip_log('FORMULAIRE_RECHERCHE avec filtre ' . $c->texte, 'vieilles_defs');
135
+    }
136 136
 }
137 137
 
138 138
 // Gerer la notation [(#EXPOSER|on,off)]
139 139
 function phraser_vieux_exposer($p) {
140
-	if ($a = $p->fonctions) {
141
-		preg_match("#([^,]*)(,(.*))?#", $a[0][0], $regs);
142
-		$args = array();
143
-		if ($regs[1]) {
144
-			$a = new Texte;
145
-			$a->texte = $regs[1];
146
-			$args = array('', array($a));
147
-			if ($regs[3]) {
148
-				$a = new Texte;
149
-				$a->texte = $regs[3];
150
-				$args[] = array($a);
151
-			}
152
-		}
153
-		$p->param[0] = $args;
154
-		$p->fonctions = array();
155
-		$p->nom_champ = 'EXPOSE';
156
-	}
140
+    if ($a = $p->fonctions) {
141
+        preg_match("#([^,]*)(,(.*))?#", $a[0][0], $regs);
142
+        $args = array();
143
+        if ($regs[1]) {
144
+            $a = new Texte;
145
+            $a->texte = $regs[1];
146
+            $args = array('', array($a));
147
+            if ($regs[3]) {
148
+                $a = new Texte;
149
+                $a->texte = $regs[3];
150
+                $args[] = array($a);
151
+            }
152
+        }
153
+        $p->param[0] = $args;
154
+        $p->fonctions = array();
155
+        $p->nom_champ = 'EXPOSE';
156
+    }
157 157
 }
158 158
 
159 159
 function phraser_vieux_modele($p) { normaliser_args_inclumodel($p); }
@@ -161,55 +161,55 @@  discard block
 block discarded – undo
161 161
 function phraser_vieux_inclu($p) { normaliser_args_inclumodel($p); }
162 162
 
163 163
 function normaliser_args_inclumodel($p) {
164
-	$params = $p->param;
165
-	if (!$params) {
166
-		return;
167
-	}
168
-	$args = $params[0];
169
-	if ($args[0]) {
170
-		return;
171
-	} // filtre immediat
172
-	array_shift($p->param);
173
-	foreach ($p->param as $l) {
174
-		if (!array_shift($l)) {
175
-			$args = array_merge($args, $l);
176
-			array_shift($p->param);
177
-		} else {
178
-			break;
179
-		} // filtre
180
-	}
181
-	array_unshift($p->param, $args);
164
+    $params = $p->param;
165
+    if (!$params) {
166
+        return;
167
+    }
168
+    $args = $params[0];
169
+    if ($args[0]) {
170
+        return;
171
+    } // filtre immediat
172
+    array_shift($p->param);
173
+    foreach ($p->param as $l) {
174
+        if (!array_shift($l)) {
175
+            $args = array_merge($args, $l);
176
+            array_shift($p->param);
177
+        } else {
178
+            break;
179
+        } // filtre
180
+    }
181
+    array_unshift($p->param, $args);
182 182
 }
183 183
 
184 184
 function normaliser_inclure($champ) {
185
-	normaliser_args_inclumodel($champ);
186
-	$l = $champ->param[0];
187
-	if (is_array($l) and !$l[0]) {
188
-		foreach ($l as $k => $p) {
189
-			if ($p and $p[0]->type == 'texte' and !strpos($p[0]->texte, '=')) {
190
-				$p[0]->texte = trim($p[0]->texte);
191
-			}
192
-		}
193
-		foreach ($l as $k => $p) {
194
-			if (!$p or $p[0]->type != 'texte' or
195
-				!preg_match('/^fond\s*=\s*(.*)$/', $p[0]->texte, $r)
196
-			) {
197
-				continue;
198
-			}
199
-
200
-			if ($r[1]) {
201
-				$p[0]->texte = $r[1];
202
-			} else {
203
-				unset($p[0]);
204
-			}
205
-			$champ->texte = $p;
206
-			unset($champ->param[0][$k]);
207
-			if (count($champ->param[0]) == 1) {
208
-				array_shift($champ->param);
209
-			}
210
-
211
-			return;
212
-		}
213
-	}
214
-	spip_log("inclure sans fond ni fichier");
185
+    normaliser_args_inclumodel($champ);
186
+    $l = $champ->param[0];
187
+    if (is_array($l) and !$l[0]) {
188
+        foreach ($l as $k => $p) {
189
+            if ($p and $p[0]->type == 'texte' and !strpos($p[0]->texte, '=')) {
190
+                $p[0]->texte = trim($p[0]->texte);
191
+            }
192
+        }
193
+        foreach ($l as $k => $p) {
194
+            if (!$p or $p[0]->type != 'texte' or
195
+                !preg_match('/^fond\s*=\s*(.*)$/', $p[0]->texte, $r)
196
+            ) {
197
+                continue;
198
+            }
199
+
200
+            if ($r[1]) {
201
+                $p[0]->texte = $r[1];
202
+            } else {
203
+                unset($p[0]);
204
+            }
205
+            $champ->texte = $p;
206
+            unset($champ->param[0][$k]);
207
+            if (count($champ->param[0]) == 1) {
208
+                array_shift($champ->param);
209
+            }
210
+
211
+            return;
212
+        }
213
+    }
214
+    spip_log("inclure sans fond ni fichier");
215 215
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 			$p->etoile = '*';
54 54
 			spip_log("filtre de logo obsolete $nom", 'vieilles_defs');
55 55
 
56
-		} elseif (preg_match("/^" . NOM_DE_CHAMP . '(.*)$/sS', $nom, $m)) {
56
+		} elseif (preg_match("/^".NOM_DE_CHAMP.'(.*)$/sS', $nom, $m)) {
57 57
 			$champ = new Champ();
58 58
 			$champ->nom_boucle = $m[2];
59 59
 			$champ->nom_champ = $m[3];
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 		$p->param[0][1] = array($c);
132 132
 		$p->param[0][0] = '';
133 133
 		$p->fonctions = array();
134
-		spip_log('FORMULAIRE_RECHERCHE avec filtre ' . $c->texte, 'vieilles_defs');
134
+		spip_log('FORMULAIRE_RECHERCHE avec filtre '.$c->texte, 'vieilles_defs');
135 135
 	}
136 136
 }
137 137
 
Please login to merge, or discard this patch.
ecrire/public/parametrer.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -231,7 +231,7 @@
 block discarded – undo
231 231
  *
232 232
  * @uses public_tester_redirection_dist()
233 233
  * @param string $fond
234
- * @param array $contexte
234
+ * @param string $contexte
235 235
  * @param string $connect
236 236
  * @return array|bool
237 237
  */
Please login to merge, or discard this patch.
Indentation   +221 added lines, -221 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/lang');
@@ -19,16 +19,16 @@  discard block
 block discarded – undo
19 19
 // NB: mes_fonctions peut initialiser $dossier_squelettes (old-style)
20 20
 // donc il faut l'inclure "en globals"
21 21
 if ($f = find_in_path('mes_fonctions.php')) {
22
-	global $dossier_squelettes;
23
-	include_once(_ROOT_CWD . $f);
22
+    global $dossier_squelettes;
23
+    include_once(_ROOT_CWD . $f);
24 24
 }
25 25
 
26 26
 if (@is_readable(_CACHE_PLUGINS_FCT)) {
27
-	// chargement optimise precompile
28
-	include_once(_CACHE_PLUGINS_FCT);
27
+    // chargement optimise precompile
28
+    include_once(_CACHE_PLUGINS_FCT);
29 29
 }
30 30
 if (test_espace_prive()) {
31
-	include_spip('inc/filtres_ecrire');
31
+    include_spip('inc/filtres_ecrire');
32 32
 }
33 33
 
34 34
 # Determine le squelette associe a une requete 
@@ -46,180 +46,180 @@  discard block
 block discarded – undo
46 46
 
47 47
 // http://code.spip.net/@public_parametrer_dist
48 48
 function public_parametrer_dist($fond, $contexte = '', $cache = '', $connect = '') {
49
-	static $composer, $styliser, $notes = null;
50
-	$page = tester_redirection($fond, $contexte, $connect);
51
-	if ($page) {
52
-		return $page;
53
-	}
54
-
55
-	if (isset($contexte['lang'])) {
56
-		$lang = $contexte['lang'];
57
-	} elseif (!isset($lang)) {
58
-		$lang = $GLOBALS['meta']['langue_site'];
59
-	}
60
-
61
-	$select = ((!isset($GLOBALS['forcer_lang']) or !$GLOBALS['forcer_lang']) and $lang <> $GLOBALS['spip_lang']);
62
-	if ($select) {
63
-		$select = lang_select($lang);
64
-	}
65
-
66
-	$debug = (defined('_VAR_MODE') && _VAR_MODE == 'debug');
67
-
68
-	if (!$styliser) {
69
-		$styliser = charger_fonction('styliser', 'public');
70
-	}
71
-	list($skel, $mime_type, $gram, $sourcefile) =
72
-		$styliser($fond, $contexte, $GLOBALS['spip_lang'], $connect);
73
-
74
-	if ($skel) {
75
-
76
-		// sauver le nom de l'eventuel squelette en cours d'execution
77
-		// (recursion possible a cause des modeles)
78
-		if ($debug) {
79
-			$courant = @$GLOBALS['debug_objets']['courant'];
80
-			$GLOBALS['debug_objets']['contexte'][$sourcefile] = $contexte;
81
-		}
82
-
83
-		// charger le squelette en specifiant les langages cibles et source
84
-		// au cas il faudrait le compiler (source posterieure au resultat)
85
-
86
-		if (!$composer) {
87
-			$composer = charger_fonction('composer', 'public');
88
-		}
89
-		$fonc = $composer($skel, $mime_type, $gram, $sourcefile, $connect);
90
-	} else {
91
-		$fonc = '';
92
-	}
93
-
94
-	if (!$fonc) { // squelette inconnu (==='') ou faux (===false)
95
-		$page = $fonc;
96
-	} else {
97
-		// Preparer l'appel de la fonction principale du squelette 
98
-
99
-		spip_timer($a = 'calcul page ' . rand(0, 1000));
100
-
101
-		// On cree un marqueur de notes unique lie a cette composition
102
-		// et on enregistre l'etat courant des globales de notes...
103
-		if (is_null($notes)) {
104
-			$notes = charger_fonction('notes', 'inc', true);
105
-		}
106
-		if ($notes) {
107
-			$notes('', 'empiler');
108
-		}
109
-
110
-		// Rajouter d'office ces deux parametres
111
-		// (mais vaudrait mieux que le compilateur sache le simuler
112
-		// car ca interdit l'usage de criteres conditionnels dessus).
113
-		if (!isset($contexte['date'])) {
114
-			$contexte['date'] = date("Y-m-d H:i:s");
115
-			$contexte['date_default'] = true;
116
-		} else {
117
-			$contexte['date'] = normaliser_date($contexte['date'], true);
118
-		}
119
-
120
-		if (!isset($contexte['date_redac'])) {
121
-			$contexte['date_redac'] = date("Y-m-d H:i:s");
122
-			$contexte['date_redac_default'] = true;
123
-		} else {
124
-			$contexte['date_redac'] = normaliser_date($contexte['date_redac'], true);
125
-		}
126
-
127
-		// Passer le nom du cache pour produire sa destruction automatique
128
-		$page = $fonc(array('cache' => $cache), array($contexte));
129
-
130
-		// Restituer les globales de notes telles qu'elles etaient avant l'appel
131
-		// Si l'inclus n'a pas affiche ses notes, tant pis (elles *doivent*
132
-		// etre dans son resultat, autrement elles ne seraient pas prises en
133
-		// compte a chaque calcul d'un texte contenant un modele, mais seulement
134
-		// quand le modele serait calcule, et on aurait des resultats incoherents)
135
-		if ($notes) {
136
-			$notes('', 'depiler');
137
-		}
138
-
139
-		// reinjecter en dynamique la pile des notes
140
-		// si il y a des inclure dynamiques
141
-		// si la pile n'est pas vide
142
-		// la generalisation de cette injection permettrait de corriger le point juste au dessus
143
-		// en faisant remonter les notes a l'incluant (A tester et valider avant application)
144
-		if ($notes) {
145
-			$page['notes'] = $notes('', 'sauver_etat');
146
-		}
147
-
148
-		// spip_log: un joli contexte
149
-		$infos = array();
150
-		foreach (array_filter($contexte) as $var => $val) {
151
-			if (is_array($val)) {
152
-				$val = serialize($val);
153
-			}
154
-			if (strlen("$val") > 30) {
155
-				$val = substr("$val", 0, 27) . '..';
156
-			}
157
-			if (strstr($val, ' ')) {
158
-				$val = "'$val'";
159
-			}
160
-			$infos[] = $var . '=' . $val;
161
-		}
162
-		$profile = spip_timer($a);
163
-		spip_log("calcul ($profile) [$skel] "
164
-			. join(', ', $infos)
165
-			. ' (' . strlen($page['texte']) . ' octets)');
166
-
167
-		if (defined('_CALCUL_PROFILER') AND intval($profile)>_CALCUL_PROFILER){
168
-			spip_log("calcul ($profile) [$skel] "
169
-				. join(', ', $infos)
170
-				.' ('.strlen($page['texte']).' octets) | '.$_SERVER['REQUEST_URI'],"profiler"._LOG_AVERTISSEMENT);
171
-		}
172
-
173
-		if ($debug) {
174
-			// si c'est ce que demande le debusqueur, lui passer la main
175
-			$t = strlen($page['texte']) ? $page['texte'] : " ";
176
-			$GLOBALS['debug_objets']['resultat'][$fonc . 'tout'] = $t;
177
-			$GLOBALS['debug_objets']['courant'] = $courant;
178
-			$GLOBALS['debug_objets']['profile'][$sourcefile] = $profile;
179
-			if ($GLOBALS['debug_objets']['sourcefile']
180
-				and (_request('var_mode_objet') == $fonc)
181
-				and (_request('var_mode_affiche') == 'resultat')
182
-			) {
183
-				erreur_squelette();
184
-			}
185
-		}
186
-		// Si #CACHE{} n'etait pas la, le mettre a $delais
187
-		if (!isset($page['entetes']['X-Spip-Cache'])) {
188
-			// Dans l'espace prive ou dans un modeles/ on pose un cache 0 par defaut
189
-			// si aucun #CACHE{} spécifié
190
-			// le contexte implicite qui conditionne le cache assure qu'on retombe pas sur le meme
191
-			// entre public et prive
192
-			if (test_espace_prive() or strncmp($fond, 'modeles/', 8) == 0) {
193
-				$page['entetes']['X-Spip-Cache'] = 0;
194
-			} else {
195
-				$page['entetes']['X-Spip-Cache'] = isset($GLOBALS['delais']) ? $GLOBALS['delais'] : 36000;
196
-			}
197
-		}
198
-
199
-		$page['contexte'] = $contexte;
200
-
201
-		// faire remonter le fichier source
202
-		static $js_inclus = false;
203
-		if (defined('_VAR_INCLURE') and _VAR_INCLURE) {
204
-			$page['sourcefile'] = $sourcefile;
205
-			$page['texte'] =
206
-				"<div class='inclure_blocs'><h6>" . $page['sourcefile'] . "</h6>" . $page['texte'] . "</div>"
207
-				. ($js_inclus ? "" : "<script type='text/javascript'>jQuery(function(){jQuery('.inclure_blocs > h6:first-child').hover(function(){jQuery(this).parent().addClass('hover')},function(){jQuery(this).parent().removeClass('hover')})});</script>");
208
-			$js_inclus = true;
209
-		}
210
-
211
-		// Si un modele contenait #SESSION, on note l'info dans $page
212
-		if (isset($GLOBALS['cache_utilise_session'])) {
213
-			$page['invalideurs']['session'] = $GLOBALS['cache_utilise_session'];
214
-			unset($GLOBALS['cache_utilise_session']);
215
-		}
216
-	}
217
-
218
-	if ($select) {
219
-		lang_select();
220
-	}
221
-
222
-	return $page;
49
+    static $composer, $styliser, $notes = null;
50
+    $page = tester_redirection($fond, $contexte, $connect);
51
+    if ($page) {
52
+        return $page;
53
+    }
54
+
55
+    if (isset($contexte['lang'])) {
56
+        $lang = $contexte['lang'];
57
+    } elseif (!isset($lang)) {
58
+        $lang = $GLOBALS['meta']['langue_site'];
59
+    }
60
+
61
+    $select = ((!isset($GLOBALS['forcer_lang']) or !$GLOBALS['forcer_lang']) and $lang <> $GLOBALS['spip_lang']);
62
+    if ($select) {
63
+        $select = lang_select($lang);
64
+    }
65
+
66
+    $debug = (defined('_VAR_MODE') && _VAR_MODE == 'debug');
67
+
68
+    if (!$styliser) {
69
+        $styliser = charger_fonction('styliser', 'public');
70
+    }
71
+    list($skel, $mime_type, $gram, $sourcefile) =
72
+        $styliser($fond, $contexte, $GLOBALS['spip_lang'], $connect);
73
+
74
+    if ($skel) {
75
+
76
+        // sauver le nom de l'eventuel squelette en cours d'execution
77
+        // (recursion possible a cause des modeles)
78
+        if ($debug) {
79
+            $courant = @$GLOBALS['debug_objets']['courant'];
80
+            $GLOBALS['debug_objets']['contexte'][$sourcefile] = $contexte;
81
+        }
82
+
83
+        // charger le squelette en specifiant les langages cibles et source
84
+        // au cas il faudrait le compiler (source posterieure au resultat)
85
+
86
+        if (!$composer) {
87
+            $composer = charger_fonction('composer', 'public');
88
+        }
89
+        $fonc = $composer($skel, $mime_type, $gram, $sourcefile, $connect);
90
+    } else {
91
+        $fonc = '';
92
+    }
93
+
94
+    if (!$fonc) { // squelette inconnu (==='') ou faux (===false)
95
+        $page = $fonc;
96
+    } else {
97
+        // Preparer l'appel de la fonction principale du squelette 
98
+
99
+        spip_timer($a = 'calcul page ' . rand(0, 1000));
100
+
101
+        // On cree un marqueur de notes unique lie a cette composition
102
+        // et on enregistre l'etat courant des globales de notes...
103
+        if (is_null($notes)) {
104
+            $notes = charger_fonction('notes', 'inc', true);
105
+        }
106
+        if ($notes) {
107
+            $notes('', 'empiler');
108
+        }
109
+
110
+        // Rajouter d'office ces deux parametres
111
+        // (mais vaudrait mieux que le compilateur sache le simuler
112
+        // car ca interdit l'usage de criteres conditionnels dessus).
113
+        if (!isset($contexte['date'])) {
114
+            $contexte['date'] = date("Y-m-d H:i:s");
115
+            $contexte['date_default'] = true;
116
+        } else {
117
+            $contexte['date'] = normaliser_date($contexte['date'], true);
118
+        }
119
+
120
+        if (!isset($contexte['date_redac'])) {
121
+            $contexte['date_redac'] = date("Y-m-d H:i:s");
122
+            $contexte['date_redac_default'] = true;
123
+        } else {
124
+            $contexte['date_redac'] = normaliser_date($contexte['date_redac'], true);
125
+        }
126
+
127
+        // Passer le nom du cache pour produire sa destruction automatique
128
+        $page = $fonc(array('cache' => $cache), array($contexte));
129
+
130
+        // Restituer les globales de notes telles qu'elles etaient avant l'appel
131
+        // Si l'inclus n'a pas affiche ses notes, tant pis (elles *doivent*
132
+        // etre dans son resultat, autrement elles ne seraient pas prises en
133
+        // compte a chaque calcul d'un texte contenant un modele, mais seulement
134
+        // quand le modele serait calcule, et on aurait des resultats incoherents)
135
+        if ($notes) {
136
+            $notes('', 'depiler');
137
+        }
138
+
139
+        // reinjecter en dynamique la pile des notes
140
+        // si il y a des inclure dynamiques
141
+        // si la pile n'est pas vide
142
+        // la generalisation de cette injection permettrait de corriger le point juste au dessus
143
+        // en faisant remonter les notes a l'incluant (A tester et valider avant application)
144
+        if ($notes) {
145
+            $page['notes'] = $notes('', 'sauver_etat');
146
+        }
147
+
148
+        // spip_log: un joli contexte
149
+        $infos = array();
150
+        foreach (array_filter($contexte) as $var => $val) {
151
+            if (is_array($val)) {
152
+                $val = serialize($val);
153
+            }
154
+            if (strlen("$val") > 30) {
155
+                $val = substr("$val", 0, 27) . '..';
156
+            }
157
+            if (strstr($val, ' ')) {
158
+                $val = "'$val'";
159
+            }
160
+            $infos[] = $var . '=' . $val;
161
+        }
162
+        $profile = spip_timer($a);
163
+        spip_log("calcul ($profile) [$skel] "
164
+            . join(', ', $infos)
165
+            . ' (' . strlen($page['texte']) . ' octets)');
166
+
167
+        if (defined('_CALCUL_PROFILER') AND intval($profile)>_CALCUL_PROFILER){
168
+            spip_log("calcul ($profile) [$skel] "
169
+                . join(', ', $infos)
170
+                .' ('.strlen($page['texte']).' octets) | '.$_SERVER['REQUEST_URI'],"profiler"._LOG_AVERTISSEMENT);
171
+        }
172
+
173
+        if ($debug) {
174
+            // si c'est ce que demande le debusqueur, lui passer la main
175
+            $t = strlen($page['texte']) ? $page['texte'] : " ";
176
+            $GLOBALS['debug_objets']['resultat'][$fonc . 'tout'] = $t;
177
+            $GLOBALS['debug_objets']['courant'] = $courant;
178
+            $GLOBALS['debug_objets']['profile'][$sourcefile] = $profile;
179
+            if ($GLOBALS['debug_objets']['sourcefile']
180
+                and (_request('var_mode_objet') == $fonc)
181
+                and (_request('var_mode_affiche') == 'resultat')
182
+            ) {
183
+                erreur_squelette();
184
+            }
185
+        }
186
+        // Si #CACHE{} n'etait pas la, le mettre a $delais
187
+        if (!isset($page['entetes']['X-Spip-Cache'])) {
188
+            // Dans l'espace prive ou dans un modeles/ on pose un cache 0 par defaut
189
+            // si aucun #CACHE{} spécifié
190
+            // le contexte implicite qui conditionne le cache assure qu'on retombe pas sur le meme
191
+            // entre public et prive
192
+            if (test_espace_prive() or strncmp($fond, 'modeles/', 8) == 0) {
193
+                $page['entetes']['X-Spip-Cache'] = 0;
194
+            } else {
195
+                $page['entetes']['X-Spip-Cache'] = isset($GLOBALS['delais']) ? $GLOBALS['delais'] : 36000;
196
+            }
197
+        }
198
+
199
+        $page['contexte'] = $contexte;
200
+
201
+        // faire remonter le fichier source
202
+        static $js_inclus = false;
203
+        if (defined('_VAR_INCLURE') and _VAR_INCLURE) {
204
+            $page['sourcefile'] = $sourcefile;
205
+            $page['texte'] =
206
+                "<div class='inclure_blocs'><h6>" . $page['sourcefile'] . "</h6>" . $page['texte'] . "</div>"
207
+                . ($js_inclus ? "" : "<script type='text/javascript'>jQuery(function(){jQuery('.inclure_blocs > h6:first-child').hover(function(){jQuery(this).parent().addClass('hover')},function(){jQuery(this).parent().removeClass('hover')})});</script>");
208
+            $js_inclus = true;
209
+        }
210
+
211
+        // Si un modele contenait #SESSION, on note l'info dans $page
212
+        if (isset($GLOBALS['cache_utilise_session'])) {
213
+            $page['invalideurs']['session'] = $GLOBALS['cache_utilise_session'];
214
+            unset($GLOBALS['cache_utilise_session']);
215
+        }
216
+    }
217
+
218
+    if ($select) {
219
+        lang_select();
220
+    }
221
+
222
+    return $page;
223 223
 }
224 224
 
225 225
 
@@ -236,11 +236,11 @@  discard block
 block discarded – undo
236 236
  * @return array|bool
237 237
  */
238 238
 function tester_redirection($fond, $contexte, $connect) {
239
-	static $tester_redirection = null;
240
-	if (is_null($tester_redirection)) {
241
-		$tester_redirection = charger_fonction('tester_redirection', 'public');
242
-	}
243
-	return $tester_redirection($fond, $contexte, $connect);
239
+    static $tester_redirection = null;
240
+    if (is_null($tester_redirection)) {
241
+        $tester_redirection = charger_fonction('tester_redirection', 'public');
242
+    }
243
+    return $tester_redirection($fond, $contexte, $connect);
244 244
 }
245 245
 
246 246
 
@@ -256,40 +256,40 @@  discard block
 block discarded – undo
256 256
  * @return array|bool
257 257
  */
258 258
 function public_tester_redirection_dist($fond, $contexte, $connect) {
259
-	if ($fond == 'article'
260
-		and $id_article = intval($contexte['id_article'])
261
-	) {
262
-		include_spip('public/quete'); // pour quete_virtuel et ses dependances
263
-		$m = quete_virtuel($id_article, $connect);
264
-		if (strlen($m)) {
265
-			include_spip('inc/texte');
266
-			// les navigateurs pataugent si l'URL est vide
267
-			if ($url = virtuel_redirige($m, true)) {
268
-				// passer en url absolue car cette redirection pourra
269
-				// etre utilisee dans un contexte d'url qui change
270
-				// y compris url arbo
271
-				$status = 302;
272
-				if (defined('_STATUS_REDIRECTION_VIRTUEL')) {
273
-					$status = _STATUS_REDIRECTION_VIRTUEL;
274
-				}
275
-				if (!preg_match(',^\w+:,', $url)) {
276
-					include_spip('inc/filtres_mini');
277
-					$url = url_absolue($url);
278
-				}
279
-				$url = str_replace('&amp;', '&', $url);
280
-
281
-				return array(
282
-					'texte' => "<"
283
-						. "?php include_spip('inc/headers');redirige_par_entete('"
284
-						. texte_script($url)
285
-						. "','',$status);"
286
-						. "?" . ">",
287
-					'process_ins' => 'php',
288
-					'status' => $status
289
-				);
290
-			}
291
-		}
292
-	}
293
-
294
-	return false;
259
+    if ($fond == 'article'
260
+        and $id_article = intval($contexte['id_article'])
261
+    ) {
262
+        include_spip('public/quete'); // pour quete_virtuel et ses dependances
263
+        $m = quete_virtuel($id_article, $connect);
264
+        if (strlen($m)) {
265
+            include_spip('inc/texte');
266
+            // les navigateurs pataugent si l'URL est vide
267
+            if ($url = virtuel_redirige($m, true)) {
268
+                // passer en url absolue car cette redirection pourra
269
+                // etre utilisee dans un contexte d'url qui change
270
+                // y compris url arbo
271
+                $status = 302;
272
+                if (defined('_STATUS_REDIRECTION_VIRTUEL')) {
273
+                    $status = _STATUS_REDIRECTION_VIRTUEL;
274
+                }
275
+                if (!preg_match(',^\w+:,', $url)) {
276
+                    include_spip('inc/filtres_mini');
277
+                    $url = url_absolue($url);
278
+                }
279
+                $url = str_replace('&amp;', '&', $url);
280
+
281
+                return array(
282
+                    'texte' => "<"
283
+                        . "?php include_spip('inc/headers');redirige_par_entete('"
284
+                        . texte_script($url)
285
+                        . "','',$status);"
286
+                        . "?" . ">",
287
+                    'process_ins' => 'php',
288
+                    'status' => $status
289
+                );
290
+            }
291
+        }
292
+    }
293
+
294
+    return false;
295 295
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 // donc il faut l'inclure "en globals"
21 21
 if ($f = find_in_path('mes_fonctions.php')) {
22 22
 	global $dossier_squelettes;
23
-	include_once(_ROOT_CWD . $f);
23
+	include_once(_ROOT_CWD.$f);
24 24
 }
25 25
 
26 26
 if (@is_readable(_CACHE_PLUGINS_FCT)) {
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 	} else {
97 97
 		// Preparer l'appel de la fonction principale du squelette 
98 98
 
99
-		spip_timer($a = 'calcul page ' . rand(0, 1000));
99
+		spip_timer($a = 'calcul page '.rand(0, 1000));
100 100
 
101 101
 		// On cree un marqueur de notes unique lie a cette composition
102 102
 		// et on enregistre l'etat courant des globales de notes...
@@ -152,28 +152,28 @@  discard block
 block discarded – undo
152 152
 				$val = serialize($val);
153 153
 			}
154 154
 			if (strlen("$val") > 30) {
155
-				$val = substr("$val", 0, 27) . '..';
155
+				$val = substr("$val", 0, 27).'..';
156 156
 			}
157 157
 			if (strstr($val, ' ')) {
158 158
 				$val = "'$val'";
159 159
 			}
160
-			$infos[] = $var . '=' . $val;
160
+			$infos[] = $var.'='.$val;
161 161
 		}
162 162
 		$profile = spip_timer($a);
163 163
 		spip_log("calcul ($profile) [$skel] "
164 164
 			. join(', ', $infos)
165
-			. ' (' . strlen($page['texte']) . ' octets)');
165
+			. ' ('.strlen($page['texte']).' octets)');
166 166
 
167
-		if (defined('_CALCUL_PROFILER') AND intval($profile)>_CALCUL_PROFILER){
167
+		if (defined('_CALCUL_PROFILER') AND intval($profile) > _CALCUL_PROFILER) {
168 168
 			spip_log("calcul ($profile) [$skel] "
169 169
 				. join(', ', $infos)
170
-				.' ('.strlen($page['texte']).' octets) | '.$_SERVER['REQUEST_URI'],"profiler"._LOG_AVERTISSEMENT);
170
+				.' ('.strlen($page['texte']).' octets) | '.$_SERVER['REQUEST_URI'], "profiler"._LOG_AVERTISSEMENT);
171 171
 		}
172 172
 
173 173
 		if ($debug) {
174 174
 			// si c'est ce que demande le debusqueur, lui passer la main
175 175
 			$t = strlen($page['texte']) ? $page['texte'] : " ";
176
-			$GLOBALS['debug_objets']['resultat'][$fonc . 'tout'] = $t;
176
+			$GLOBALS['debug_objets']['resultat'][$fonc.'tout'] = $t;
177 177
 			$GLOBALS['debug_objets']['courant'] = $courant;
178 178
 			$GLOBALS['debug_objets']['profile'][$sourcefile] = $profile;
179 179
 			if ($GLOBALS['debug_objets']['sourcefile']
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 		if (defined('_VAR_INCLURE') and _VAR_INCLURE) {
204 204
 			$page['sourcefile'] = $sourcefile;
205 205
 			$page['texte'] =
206
-				"<div class='inclure_blocs'><h6>" . $page['sourcefile'] . "</h6>" . $page['texte'] . "</div>"
206
+				"<div class='inclure_blocs'><h6>".$page['sourcefile']."</h6>".$page['texte']."</div>"
207 207
 				. ($js_inclus ? "" : "<script type='text/javascript'>jQuery(function(){jQuery('.inclure_blocs > h6:first-child').hover(function(){jQuery(this).parent().addClass('hover')},function(){jQuery(this).parent().removeClass('hover')})});</script>");
208 208
 			$js_inclus = true;
209 209
 		}
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 						. "?php include_spip('inc/headers');redirige_par_entete('"
284 284
 						. texte_script($url)
285 285
 						. "','',$status);"
286
-						. "?" . ">",
286
+						. "?".">",
287 287
 					'process_ins' => 'php',
288 288
 					'status' => $status
289 289
 				);
Please login to merge, or discard this patch.
ecrire/public/references.php 3 patches
Doc Comments   +16 added lines, -2 removed lines patch added patch discarded remove patch
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
  *           est dans une autre table et construit la jointure dessus
294 294
  *         - liste (table, champ, fonction) idem, mais en passant un
295 295
  *           nom de fonction qui s'occupera de créer la jointure.
296
- * @return array
296
+ * @return string[]
297 297
  *     Liste (nom du champ alias, nom du champ). Le nom du champ alias
298 298
  *     est une expression pour le SELECT de la boucle du style "mots.titre AS titre_mot"
299 299
  **/
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
  *     Nom de la balise
472 472
  * @param Champ $p
473 473
  *     AST au niveau de la balise
474
- * @return string
474
+ * @return Champ
475 475
  *     Code PHP pour d'exécution de la balise et de ses filtres
476 476
  **/
477 477
 function calculer_balise_DEFAUT_dist($nom, $p) {
@@ -755,6 +755,9 @@  discard block
 block discarded – undo
755 755
 //  - deux etoiles => pas de securite non plus !
756 756
 //
757 757
 // http://code.spip.net/@applique_filtres
758
+/**
759
+ * @param Champ $p
760
+ */
758 761
 function applique_filtres($p) {
759 762
 
760 763
 	// Traitements standards (cf. supra)
@@ -829,6 +832,9 @@  discard block
 block discarded – undo
829 832
 
830 833
 // Filtres et,ou,oui,non,sinon,xou,xor,and,or,not,yes
831 834
 // et comparateurs
835
+/**
836
+ * @param string $arg
837
+ */
832 838
 function filtre_logique($fonc, $code, $arg) {
833 839
 
834 840
 	switch (true) {
@@ -852,6 +858,9 @@  discard block
 block discarded – undo
852 858
 }
853 859
 
854 860
 // http://code.spip.net/@compose_filtres_args
861
+/**
862
+ * @param string $sep
863
+ */
855 864
 function compose_filtres_args($p, $args, $sep) {
856 865
 	$arglist = "";
857 866
 	foreach ($args as $arg) {
@@ -899,6 +908,11 @@  discard block
 block discarded – undo
899 908
 //
900 909
 
901 910
 // http://code.spip.net/@rindex_pile
911
+/**
912
+ * @param Champ $p
913
+ * @param string $champ
914
+ * @param string $motif
915
+ */
902 916
 function rindex_pile($p, $champ, $motif) {
903 917
 	$n = 0;
904 918
 	$b = $p->id_boucle;
Please login to merge, or discard this patch.
Indentation   +477 added lines, -477 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Compilateur\References
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -42,17 +42,17 @@  discard block
 block discarded – undo
42 42
  */
43 43
 function index_boucle($p) {
44 44
 
45
-	$idb = $p->id_boucle;
46
-	$explicite = $p->nom_boucle;
45
+    $idb = $p->id_boucle;
46
+    $explicite = $p->nom_boucle;
47 47
 
48
-	if (strlen($explicite)) {
49
-		// Recherche d'un champ dans un etage superieur
50
-		while (($idb !== $explicite) && ($idb !== '')) {
51
-			$idb = $p->boucles[$idb]->id_parent;
52
-		}
53
-	}
48
+    if (strlen($explicite)) {
49
+        // Recherche d'un champ dans un etage superieur
50
+        while (($idb !== $explicite) && ($idb !== '')) {
51
+            $idb = $p->boucles[$idb]->id_parent;
52
+        }
53
+    }
54 54
 
55
-	return $idb;
55
+    return $idb;
56 56
 }
57 57
 
58 58
 /**
@@ -86,69 +86,69 @@  discard block
 block discarded – undo
86 86
  *     Code PHP pour obtenir le champ SQL
87 87
  */
88 88
 function index_pile(
89
-	$idb,
90
-	$nom_champ,
91
-	&$boucles,
92
-	$explicite = '',
93
-	$defaut = null,
94
-	$remonte_pile = true,
95
-	$select = true
89
+    $idb,
90
+    $nom_champ,
91
+    &$boucles,
92
+    $explicite = '',
93
+    $defaut = null,
94
+    $remonte_pile = true,
95
+    $select = true
96 96
 ) {
97
-	if (!is_string($defaut)) {
98
-		$defaut = '@$Pile[0][\'' . strtolower($nom_champ) . '\']';
99
-	}
100
-
101
-	$i = 0;
102
-	if (strlen($explicite)) {
103
-		// Recherche d'un champ dans un etage superieur
104
-		while (($idb !== $explicite) && ($idb !== '')) {
105
-			#	spip_log("Cherchexpl: $nom_champ '$explicite' '$idb' '$i'");
106
-			$i++;
107
-			$idb = $boucles[$idb]->id_parent;
108
-		}
109
-	}
110
-
111
-	#	spip_log("Cherche: $nom_champ a partir de '$idb'");
112
-	$nom_champ = strtolower($nom_champ);
113
-	$conditionnel = array();
114
-	// attention: entre la boucle nommee 0, "" et le tableau vide,
115
-	// il y a incoherences qu'il vaut mieux eviter
116
-	while (isset($boucles[$idb])) {
117
-		$joker = true;
118
-		// modifie $joker si tous les champs sont autorisés.
119
-		// $t = le select pour le champ, si on l'a trouvé (ou si joker)
120
-		// $c = le nom du champ demandé
121
-		list($t, $c) = index_tables_en_pile($idb, $nom_champ, $boucles, $joker);
122
-		if ($t) {
123
-			if ($select and !in_array($t, $boucles[$idb]->select)) {
124
-				$boucles[$idb]->select[] = $t;
125
-			}
126
-			$champ = '$Pile[$SP' . ($i ? "-$i" : "") . '][\'' . $c . '\']';
127
-			if (!$joker) {
128
-				return index_compose($conditionnel, $champ);
129
-			}
130
-
131
-			// tant que l'on trouve des tables avec joker, on continue
132
-			// avec la boucle parente et on conditionne à l'exécution
133
-			// la présence du champ. Si le champ existe à l'exécution
134
-			// dans une boucle, il est pris, sinon on le cherche dans le parent...
135
-			$conditionnel[] = "isset($champ)?$champ";
136
-		}
137
-
138
-		if ($remonte_pile) {
139
-			#	spip_log("On remonte vers $i");
140
-			// Sinon on remonte d'un cran
141
-			$idb = $boucles[$idb]->id_parent;
142
-			$i++;
143
-		} else {
144
-			$idb = null;
145
-		}
146
-	}
147
-
148
-	#	spip_log("Pas vu $nom_champ");
149
-	// esperons qu'il y sera
150
-	// ou qu'on a fourni une valeur par "defaut" plus pertinent
151
-	return index_compose($conditionnel, $defaut);
97
+    if (!is_string($defaut)) {
98
+        $defaut = '@$Pile[0][\'' . strtolower($nom_champ) . '\']';
99
+    }
100
+
101
+    $i = 0;
102
+    if (strlen($explicite)) {
103
+        // Recherche d'un champ dans un etage superieur
104
+        while (($idb !== $explicite) && ($idb !== '')) {
105
+            #	spip_log("Cherchexpl: $nom_champ '$explicite' '$idb' '$i'");
106
+            $i++;
107
+            $idb = $boucles[$idb]->id_parent;
108
+        }
109
+    }
110
+
111
+    #	spip_log("Cherche: $nom_champ a partir de '$idb'");
112
+    $nom_champ = strtolower($nom_champ);
113
+    $conditionnel = array();
114
+    // attention: entre la boucle nommee 0, "" et le tableau vide,
115
+    // il y a incoherences qu'il vaut mieux eviter
116
+    while (isset($boucles[$idb])) {
117
+        $joker = true;
118
+        // modifie $joker si tous les champs sont autorisés.
119
+        // $t = le select pour le champ, si on l'a trouvé (ou si joker)
120
+        // $c = le nom du champ demandé
121
+        list($t, $c) = index_tables_en_pile($idb, $nom_champ, $boucles, $joker);
122
+        if ($t) {
123
+            if ($select and !in_array($t, $boucles[$idb]->select)) {
124
+                $boucles[$idb]->select[] = $t;
125
+            }
126
+            $champ = '$Pile[$SP' . ($i ? "-$i" : "") . '][\'' . $c . '\']';
127
+            if (!$joker) {
128
+                return index_compose($conditionnel, $champ);
129
+            }
130
+
131
+            // tant que l'on trouve des tables avec joker, on continue
132
+            // avec la boucle parente et on conditionne à l'exécution
133
+            // la présence du champ. Si le champ existe à l'exécution
134
+            // dans une boucle, il est pris, sinon on le cherche dans le parent...
135
+            $conditionnel[] = "isset($champ)?$champ";
136
+        }
137
+
138
+        if ($remonte_pile) {
139
+            #	spip_log("On remonte vers $i");
140
+            // Sinon on remonte d'un cran
141
+            $idb = $boucles[$idb]->id_parent;
142
+            $i++;
143
+        } else {
144
+            $idb = null;
145
+        }
146
+    }
147
+
148
+    #	spip_log("Pas vu $nom_champ");
149
+    // esperons qu'il y sera
150
+    // ou qu'on a fourni une valeur par "defaut" plus pertinent
151
+    return index_compose($conditionnel, $defaut);
152 152
 }
153 153
 
154 154
 /**
@@ -162,12 +162,12 @@  discard block
 block discarded – undo
162 162
  * @return string              Code PHP complet de recherche d'un champ
163 163
  */
164 164
 function index_compose($conditionnel, $defaut) {
165
-	while ($c = array_pop($conditionnel)) {
166
-		// si on passe defaut = '', ne pas générer d'erreur de compilation.
167
-		$defaut = "($c:(" . ($defaut ? $defaut : "''") . "))";
168
-	}
165
+    while ($c = array_pop($conditionnel)) {
166
+        // si on passe defaut = '', ne pas générer d'erreur de compilation.
167
+        $defaut = "($c:(" . ($defaut ? $defaut : "''") . "))";
168
+    }
169 169
 
170
-	return $defaut;
170
+    return $defaut;
171 171
 }
172 172
 
173 173
 /**
@@ -203,74 +203,74 @@  discard block
 block discarded – undo
203 203
  **/
204 204
 function index_tables_en_pile($idb, $nom_champ, &$boucles, &$joker) {
205 205
 
206
-	$r = $boucles[$idb]->type_requete;
207
-	// boucle recursive, c'est foutu...
208
-	if ($r == TYPE_RECURSIF) {
209
-		return array();
210
-	}
211
-	if (!$r) {
212
-		$joker = false; // indiquer a l'appelant
213
-		# continuer pour chercher l'erreur suivante
214
-		return array("'#" . $r . ':' . $nom_champ . "'", '');
215
-	}
216
-
217
-	$desc = $boucles[$idb]->show;
218
-	// le nom du champ est il une exception de la table ? un alias ?
219
-	$excep = isset($GLOBALS['exceptions_des_tables'][$r]) ? $GLOBALS['exceptions_des_tables'][$r] : '';
220
-	if ($excep) {
221
-		$excep = isset($excep[$nom_champ]) ? $excep[$nom_champ] : '';
222
-	}
223
-	if ($excep) {
224
-		$joker = false; // indiquer a l'appelant
225
-		return index_exception($boucles[$idb], $desc, $nom_champ, $excep);
226
-	} // pas d'alias. Le champ existe t'il ?
227
-	else {
228
-		// le champ est réellement présent, on le prend.
229
-		if (isset($desc['field'][$nom_champ])) {
230
-			$t = $boucles[$idb]->id_table;
231
-			$joker = false; // indiquer a l'appelant
232
-			return array("$t.$nom_champ", $nom_champ);
233
-		}
234
-		// Tous les champs sont-ils acceptés ?
235
-		// Si oui, on retourne le champ, et on lève le flag joker
236
-		// C'est le cas des itérateurs DATA qui acceptent tout
237
-		// et testent la présence du champ à l'exécution et non à la compilation
238
-		// car ils ne connaissent pas ici leurs contenus.
239
-		elseif (/*$joker AND */
240
-		isset($desc['field']['*'])
241
-		) {
242
-			$joker = true; // indiquer a l'appelant
243
-			return array($nom_champ, $nom_champ);
244
-		}
245
-		// pas d'alias, pas de champ, pas de joker...
246
-		// tenter via une jointure...
247
-		else {
248
-			$joker = false; // indiquer a l'appelant
249
-			// regarder si le champ est deja dans une jointure existante
250
-			// sinon, si il y a des joitures explicites, la construire
251
-			if (!$t = trouver_champ_exterieur($nom_champ, $boucles[$idb]->from, $boucles[$idb])) {
252
-				if ($boucles[$idb]->jointures_explicites) {
253
-					// [todo] Ne pas lancer que lorsque il y a des jointures explicites !!!!
254
-					// fonctionnel, il suffit d'utiliser $boucles[$idb]->jointures au lieu de jointures_explicites
255
-					// mais est-ce ce qu'on veut ?
256
-					$jointures = preg_split("/\s+/", $boucles[$idb]->jointures_explicites);
257
-					if ($cle = trouver_jointure_champ($nom_champ, $boucles[$idb], $jointures)) {
258
-						$t = trouver_champ_exterieur($nom_champ, $boucles[$idb]->from, $boucles[$idb]);
259
-					}
260
-				}
261
-			}
262
-			if ($t) {
263
-				// si on a trouvé une jointure possible, on fait comme
264
-				// si c'était une exception pour le champ demandé
265
-				return index_exception($boucles[$idb],
266
-					$desc,
267
-					$nom_champ,
268
-					array($t[1]['id_table'], reset($t[2])));
269
-			}
270
-
271
-			return array('', '');
272
-		}
273
-	}
206
+    $r = $boucles[$idb]->type_requete;
207
+    // boucle recursive, c'est foutu...
208
+    if ($r == TYPE_RECURSIF) {
209
+        return array();
210
+    }
211
+    if (!$r) {
212
+        $joker = false; // indiquer a l'appelant
213
+        # continuer pour chercher l'erreur suivante
214
+        return array("'#" . $r . ':' . $nom_champ . "'", '');
215
+    }
216
+
217
+    $desc = $boucles[$idb]->show;
218
+    // le nom du champ est il une exception de la table ? un alias ?
219
+    $excep = isset($GLOBALS['exceptions_des_tables'][$r]) ? $GLOBALS['exceptions_des_tables'][$r] : '';
220
+    if ($excep) {
221
+        $excep = isset($excep[$nom_champ]) ? $excep[$nom_champ] : '';
222
+    }
223
+    if ($excep) {
224
+        $joker = false; // indiquer a l'appelant
225
+        return index_exception($boucles[$idb], $desc, $nom_champ, $excep);
226
+    } // pas d'alias. Le champ existe t'il ?
227
+    else {
228
+        // le champ est réellement présent, on le prend.
229
+        if (isset($desc['field'][$nom_champ])) {
230
+            $t = $boucles[$idb]->id_table;
231
+            $joker = false; // indiquer a l'appelant
232
+            return array("$t.$nom_champ", $nom_champ);
233
+        }
234
+        // Tous les champs sont-ils acceptés ?
235
+        // Si oui, on retourne le champ, et on lève le flag joker
236
+        // C'est le cas des itérateurs DATA qui acceptent tout
237
+        // et testent la présence du champ à l'exécution et non à la compilation
238
+        // car ils ne connaissent pas ici leurs contenus.
239
+        elseif (/*$joker AND */
240
+        isset($desc['field']['*'])
241
+        ) {
242
+            $joker = true; // indiquer a l'appelant
243
+            return array($nom_champ, $nom_champ);
244
+        }
245
+        // pas d'alias, pas de champ, pas de joker...
246
+        // tenter via une jointure...
247
+        else {
248
+            $joker = false; // indiquer a l'appelant
249
+            // regarder si le champ est deja dans une jointure existante
250
+            // sinon, si il y a des joitures explicites, la construire
251
+            if (!$t = trouver_champ_exterieur($nom_champ, $boucles[$idb]->from, $boucles[$idb])) {
252
+                if ($boucles[$idb]->jointures_explicites) {
253
+                    // [todo] Ne pas lancer que lorsque il y a des jointures explicites !!!!
254
+                    // fonctionnel, il suffit d'utiliser $boucles[$idb]->jointures au lieu de jointures_explicites
255
+                    // mais est-ce ce qu'on veut ?
256
+                    $jointures = preg_split("/\s+/", $boucles[$idb]->jointures_explicites);
257
+                    if ($cle = trouver_jointure_champ($nom_champ, $boucles[$idb], $jointures)) {
258
+                        $t = trouver_champ_exterieur($nom_champ, $boucles[$idb]->from, $boucles[$idb]);
259
+                    }
260
+                }
261
+            }
262
+            if ($t) {
263
+                // si on a trouvé une jointure possible, on fait comme
264
+                // si c'était une exception pour le champ demandé
265
+                return index_exception($boucles[$idb],
266
+                    $desc,
267
+                    $nom_champ,
268
+                    array($t[1]['id_table'], reset($t[2])));
269
+            }
270
+
271
+            return array('', '');
272
+        }
273
+    }
274 274
 }
275 275
 
276 276
 
@@ -298,52 +298,52 @@  discard block
 block discarded – undo
298 298
  *     est une expression pour le SELECT de la boucle du style "mots.titre AS titre_mot"
299 299
  **/
300 300
 function index_exception(&$boucle, $desc, $nom_champ, $excep) {
301
-	static $trouver_table;
302
-	if (!$trouver_table) {
303
-		$trouver_table = charger_fonction('trouver_table', 'base');
304
-	}
305
-
306
-	if (is_array($excep)) {
307
-		// permettre aux plugins de gerer eux meme des jointures derogatoire ingerables
308
-		$t = null;
309
-		if (count($excep) == 3) {
310
-			$index_exception_derogatoire = array_pop($excep);
311
-			$t = $index_exception_derogatoire($boucle, $desc, $nom_champ, $excep);
312
-		}
313
-		if ($t == null) {
314
-			list($e, $x) = $excep;  #PHP4 affecte de gauche a droite
315
-			$excep = $x;    #PHP5 de droite a gauche !
316
-			$j = $trouver_table($e, $boucle->sql_serveur);
317
-			if (!$j) {
318
-				return array('', '');
319
-			}
320
-			$e = $j['table'];
321
-			if (!$t = array_search($e, $boucle->from)) {
322
-				$k = $j['key']['PRIMARY KEY'];
323
-				if (strpos($k, ',')) {
324
-					$l = (preg_split('/\s*,\s*/', $k));
325
-					$k = $desc['key']['PRIMARY KEY'];
326
-					if (!in_array($k, $l)) {
327
-						spip_log("jointure impossible $e " . join(',', $l));
328
-
329
-						return array('', '');
330
-					}
331
-				}
332
-				$k = array($boucle->id_table, array($e), $k);
333
-				fabrique_jointures($boucle, array($k));
334
-				$t = array_search($e, $boucle->from);
335
-			}
336
-		}
337
-	} else {
338
-		$t = $boucle->id_table;
339
-	}
340
-	// demander a SQL de gerer le synonyme
341
-	// ca permet que excep soit dynamique (Cedric, 2/3/06)
342
-	if ($excep != $nom_champ) {
343
-		$excep .= ' AS ' . $nom_champ;
344
-	}
345
-
346
-	return array("$t.$excep", $nom_champ);
301
+    static $trouver_table;
302
+    if (!$trouver_table) {
303
+        $trouver_table = charger_fonction('trouver_table', 'base');
304
+    }
305
+
306
+    if (is_array($excep)) {
307
+        // permettre aux plugins de gerer eux meme des jointures derogatoire ingerables
308
+        $t = null;
309
+        if (count($excep) == 3) {
310
+            $index_exception_derogatoire = array_pop($excep);
311
+            $t = $index_exception_derogatoire($boucle, $desc, $nom_champ, $excep);
312
+        }
313
+        if ($t == null) {
314
+            list($e, $x) = $excep;  #PHP4 affecte de gauche a droite
315
+            $excep = $x;    #PHP5 de droite a gauche !
316
+            $j = $trouver_table($e, $boucle->sql_serveur);
317
+            if (!$j) {
318
+                return array('', '');
319
+            }
320
+            $e = $j['table'];
321
+            if (!$t = array_search($e, $boucle->from)) {
322
+                $k = $j['key']['PRIMARY KEY'];
323
+                if (strpos($k, ',')) {
324
+                    $l = (preg_split('/\s*,\s*/', $k));
325
+                    $k = $desc['key']['PRIMARY KEY'];
326
+                    if (!in_array($k, $l)) {
327
+                        spip_log("jointure impossible $e " . join(',', $l));
328
+
329
+                        return array('', '');
330
+                    }
331
+                }
332
+                $k = array($boucle->id_table, array($e), $k);
333
+                fabrique_jointures($boucle, array($k));
334
+                $t = array_search($e, $boucle->from);
335
+            }
336
+        }
337
+    } else {
338
+        $t = $boucle->id_table;
339
+    }
340
+    // demander a SQL de gerer le synonyme
341
+    // ca permet que excep soit dynamique (Cedric, 2/3/06)
342
+    if ($excep != $nom_champ) {
343
+        $excep .= ' AS ' . $nom_champ;
344
+    }
345
+
346
+    return array("$t.$excep", $nom_champ);
347 347
 }
348 348
 
349 349
 /**
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
  *     Code PHP pour retrouver le champ
369 369
  */
370 370
 function champ_sql($champ, $p, $defaut = null, $remonte_pile = true) {
371
-	return index_pile($p->id_boucle, $champ, $p->boucles, $p->nom_boucle, $defaut, $remonte_pile);
371
+    return index_pile($p->id_boucle, $champ, $p->boucles, $p->nom_boucle, $defaut, $remonte_pile);
372 372
 }
373 373
 
374 374
 
@@ -388,9 +388,9 @@  discard block
 block discarded – undo
388 388
  *     Code PHP pour d'exécution de la balise et de ses filtres
389 389
  **/
390 390
 function calculer_champ($p) {
391
-	$p = calculer_balise($p->nom_champ, $p);
391
+    $p = calculer_balise($p->nom_champ, $p);
392 392
 
393
-	return applique_filtres($p);
393
+    return applique_filtres($p);
394 394
 }
395 395
 
396 396
 
@@ -427,28 +427,28 @@  discard block
 block discarded – undo
427 427
  **/
428 428
 function calculer_balise($nom, $p) {
429 429
 
430
-	// S'agit-t-il d'une balise_XXXX[_dist]() ?
431
-	if ($f = charger_fonction($nom, 'balise', true)) {
432
-		$p->balise_calculee = true;
433
-		$res = $f($p);
434
-		if ($res !== null and is_object($res)) {
435
-			return $res;
436
-		}
437
-	}
438
-
439
-	// Certaines des balises comportant un _ sont generiques
440
-	if ($f = strpos($nom, '_')
441
-		and $f = charger_fonction(substr($nom, 0, $f + 1), 'balise', true)
442
-	) {
443
-		$res = $f($p);
444
-		if ($res !== null and is_object($res)) {
445
-			return $res;
446
-		}
447
-	}
448
-
449
-	$f = charger_fonction('DEFAUT', 'calculer_balise');
450
-
451
-	return $f($nom, $p);
430
+    // S'agit-t-il d'une balise_XXXX[_dist]() ?
431
+    if ($f = charger_fonction($nom, 'balise', true)) {
432
+        $p->balise_calculee = true;
433
+        $res = $f($p);
434
+        if ($res !== null and is_object($res)) {
435
+            return $res;
436
+        }
437
+    }
438
+
439
+    // Certaines des balises comportant un _ sont generiques
440
+    if ($f = strpos($nom, '_')
441
+        and $f = charger_fonction(substr($nom, 0, $f + 1), 'balise', true)
442
+    ) {
443
+        $res = $f($p);
444
+        if ($res !== null and is_object($res)) {
445
+            return $res;
446
+        }
447
+    }
448
+
449
+    $f = charger_fonction('DEFAUT', 'calculer_balise');
450
+
451
+    return $f($nom, $p);
452 452
 }
453 453
 
454 454
 
@@ -476,36 +476,36 @@  discard block
 block discarded – undo
476 476
  **/
477 477
 function calculer_balise_DEFAUT_dist($nom, $p) {
478 478
 
479
-	// ca pourrait etre un champ SQL homonyme,
480
-	$p->code = index_pile($p->id_boucle, $nom, $p->boucles, $p->nom_boucle);
481
-
482
-	// compatibilite: depuis qu'on accepte #BALISE{ses_args} sans [(...)] autour
483
-	// il faut recracher {...} quand ce n'est finalement pas des args
484
-	if ($p->fonctions and (!$p->fonctions[0][0]) and $p->fonctions[0][1]) {
485
-		$code = addslashes($p->fonctions[0][1]);
486
-		$p->code .= " . '$code'";
487
-	}
488
-
489
-	// ne pas passer le filtre securite sur les id_xxx
490
-	if (strpos($nom, 'ID_') === 0) {
491
-		$p->interdire_scripts = false;
492
-	}
493
-
494
-	// Compatibilite ascendante avec les couleurs html (#FEFEFE) :
495
-	// SI le champ SQL n'est pas trouve
496
-	// ET si la balise a une forme de couleur
497
-	// ET s'il n'y a ni filtre ni etoile
498
-	// ALORS retourner la couleur.
499
-	// Ca permet si l'on veut vraiment de recuperer [(#ACCEDE*)]
500
-	if (preg_match("/^[A-F]{1,6}$/i", $nom)
501
-		and !$p->etoile
502
-		and !$p->fonctions
503
-	) {
504
-		$p->code = "'#$nom'";
505
-		$p->interdire_scripts = false;
506
-	}
507
-
508
-	return $p;
479
+    // ca pourrait etre un champ SQL homonyme,
480
+    $p->code = index_pile($p->id_boucle, $nom, $p->boucles, $p->nom_boucle);
481
+
482
+    // compatibilite: depuis qu'on accepte #BALISE{ses_args} sans [(...)] autour
483
+    // il faut recracher {...} quand ce n'est finalement pas des args
484
+    if ($p->fonctions and (!$p->fonctions[0][0]) and $p->fonctions[0][1]) {
485
+        $code = addslashes($p->fonctions[0][1]);
486
+        $p->code .= " . '$code'";
487
+    }
488
+
489
+    // ne pas passer le filtre securite sur les id_xxx
490
+    if (strpos($nom, 'ID_') === 0) {
491
+        $p->interdire_scripts = false;
492
+    }
493
+
494
+    // Compatibilite ascendante avec les couleurs html (#FEFEFE) :
495
+    // SI le champ SQL n'est pas trouve
496
+    // ET si la balise a une forme de couleur
497
+    // ET s'il n'y a ni filtre ni etoile
498
+    // ALORS retourner la couleur.
499
+    // Ca permet si l'on veut vraiment de recuperer [(#ACCEDE*)]
500
+    if (preg_match("/^[A-F]{1,6}$/i", $nom)
501
+        and !$p->etoile
502
+        and !$p->fonctions
503
+    ) {
504
+        $p->code = "'#$nom'";
505
+        $p->interdire_scripts = false;
506
+    }
507
+
508
+    return $p;
509 509
 }
510 510
 
511 511
 
@@ -548,36 +548,36 @@  discard block
 block discarded – undo
548 548
  **/
549 549
 function calculer_balise_dynamique($p, $nom, $l, $supp = array()) {
550 550
 
551
-	if (!balise_distante_interdite($p)) {
552
-		$p->code = "''";
553
-
554
-		return $p;
555
-	}
556
-	// compatibilite: depuis qu'on accepte #BALISE{ses_args} sans [(...)] autour
557
-	// il faut recracher {...} quand ce n'est finalement pas des args
558
-	if ($p->fonctions and (!$p->fonctions[0][0]) and $p->fonctions[0][1]) {
559
-		$p->fonctions = null;
560
-	}
561
-
562
-	if ($p->param and ($c = $p->param[0])) {
563
-		// liste d'arguments commence toujours par la chaine vide
564
-		array_shift($c);
565
-		// construire la liste d'arguments comme pour un filtre
566
-		$param = compose_filtres_args($p, $c, ',');
567
-	} else {
568
-		$param = "";
569
-	}
570
-	$collecte = collecter_balise_dynamique($l, $p, $nom);
571
-
572
-	$p->code = sprintf(CODE_EXECUTER_BALISE, $nom,
573
-		join(',', $collecte),
574
-		($collecte ? $param : substr($param, 1)), # virer la virgule
575
-		memoriser_contexte_compil($p),
576
-		(!$supp ? '' : (', ' . join(',', $supp))));
577
-
578
-	$p->interdire_scripts = false;
579
-
580
-	return $p;
551
+    if (!balise_distante_interdite($p)) {
552
+        $p->code = "''";
553
+
554
+        return $p;
555
+    }
556
+    // compatibilite: depuis qu'on accepte #BALISE{ses_args} sans [(...)] autour
557
+    // il faut recracher {...} quand ce n'est finalement pas des args
558
+    if ($p->fonctions and (!$p->fonctions[0][0]) and $p->fonctions[0][1]) {
559
+        $p->fonctions = null;
560
+    }
561
+
562
+    if ($p->param and ($c = $p->param[0])) {
563
+        // liste d'arguments commence toujours par la chaine vide
564
+        array_shift($c);
565
+        // construire la liste d'arguments comme pour un filtre
566
+        $param = compose_filtres_args($p, $c, ',');
567
+    } else {
568
+        $param = "";
569
+    }
570
+    $collecte = collecter_balise_dynamique($l, $p, $nom);
571
+
572
+    $p->code = sprintf(CODE_EXECUTER_BALISE, $nom,
573
+        join(',', $collecte),
574
+        ($collecte ? $param : substr($param, 1)), # virer la virgule
575
+        memoriser_contexte_compil($p),
576
+        (!$supp ? '' : (', ' . join(',', $supp))));
577
+
578
+    $p->interdire_scripts = false;
579
+
580
+    return $p;
581 581
 }
582 582
 
583 583
 
@@ -607,13 +607,13 @@  discard block
 block discarded – undo
607 607
  *     Liste des codes PHP d'éxecution des balises collectées
608 608
  **/
609 609
 function collecter_balise_dynamique($l, &$p, $nom) {
610
-	$args = array();
611
-	foreach ($l as $c) {
612
-		$x = calculer_balise($c, $p);
613
-		$args[] = $x->code;
614
-	}
610
+    $args = array();
611
+    foreach ($l as $c) {
612
+        $x = calculer_balise($c, $p);
613
+        $args[] = $x->code;
614
+    }
615 615
 
616
-	return $args;
616
+    return $args;
617 617
 }
618 618
 
619 619
 
@@ -628,20 +628,20 @@  discard block
 block discarded – undo
628 628
  *     Nom de la connexion
629 629
  **/
630 630
 function trouver_nom_serveur_distant($p) {
631
-	$nom = $p->id_boucle;
632
-	if ($nom
633
-		and isset($p->boucles[$nom])
634
-	) {
635
-		$s = $p->boucles[$nom]->sql_serveur;
636
-		if (strlen($s)
637
-			and strlen($serveur = strtolower($s))
638
-			and !in_array($serveur, $GLOBALS['exception_des_connect'])
639
-		) {
640
-			return $serveur;
641
-		}
642
-	}
643
-
644
-	return "";
631
+    $nom = $p->id_boucle;
632
+    if ($nom
633
+        and isset($p->boucles[$nom])
634
+    ) {
635
+        $s = $p->boucles[$nom]->sql_serveur;
636
+        if (strlen($s)
637
+            and strlen($serveur = strtolower($s))
638
+            and !in_array($serveur, $GLOBALS['exception_des_connect'])
639
+        ) {
640
+            return $serveur;
641
+        }
642
+    }
643
+
644
+    return "";
645 645
 }
646 646
 
647 647
 
@@ -665,15 +665,15 @@  discard block
 block discarded – undo
665 665
  *     - false : La balise est interdite car le serveur est distant
666 666
  **/
667 667
 function balise_distante_interdite($p) {
668
-	$nom = $p->id_boucle;
668
+    $nom = $p->id_boucle;
669 669
 
670
-	if ($nom and trouver_nom_serveur_distant($p)) {
671
-		spip_log($nom . ':' . $p->nom_champ . ' ' . _T('zbug_distant_interdit'));
670
+    if ($nom and trouver_nom_serveur_distant($p)) {
671
+        spip_log($nom . ':' . $p->nom_champ . ' ' . _T('zbug_distant_interdit'));
672 672
 
673
-		return false;
674
-	}
673
+        return false;
674
+    }
675 675
 
676
-	return true;
676
+    return true;
677 677
 }
678 678
 
679 679
 
@@ -684,67 +684,67 @@  discard block
 block discarded – undo
684 684
 // http://code.spip.net/@champs_traitements
685 685
 function champs_traitements($p) {
686 686
 
687
-	if (isset($GLOBALS['table_des_traitements'][$p->nom_champ])) {
688
-		$ps = $GLOBALS['table_des_traitements'][$p->nom_champ];
689
-	} else {
690
-		// quand on utilise un traitement catch-all *
691
-		// celui-ci ne s'applique pas sur les balises calculees qui peuvent gerer
692
-		// leur propre securite
693
-		if (!$p->balise_calculee) {
694
-			$ps = $GLOBALS['table_des_traitements']['*'];
695
-		} else {
696
-			$ps = false;
697
-		}
698
-	}
699
-
700
-	if (is_array($ps)) {
701
-		// Recuperer le type de boucle (articles, DATA) et la table SQL sur laquelle elle porte
702
-		$idb = index_boucle($p);
703
-		// mais on peut aussi etre hors boucle. Se mefier.
704
-		$type_requete = isset($p->boucles[$idb]->type_requete) ? $p->boucles[$idb]->type_requete : false;
705
-		$table_sql = isset($p->boucles[$idb]->show['table_sql']) ? $p->boucles[$idb]->show['table_sql'] : false;
706
-
707
-		// le traitement peut n'etre defini que pour une table en particulier "spip_articles"
708
-		if ($table_sql and isset($ps[$table_sql])) {
709
-			$ps = $ps[$table_sql];
710
-		} // ou pour une boucle en particulier "DATA","articles"
711
-		elseif ($type_requete and isset($ps[$type_requete])) {
712
-			$ps = $ps[$type_requete];
713
-		} // ou pour indiferrement quelle que soit la boucle
714
-		elseif (isset($ps[0])) {
715
-			$ps = $ps[0];
716
-		} else {
717
-			$ps = false;
718
-		}
719
-	}
720
-
721
-	if (!$ps) {
722
-		return $p->code;
723
-	}
724
-
725
-	// Si une boucle DOCUMENTS{doublons} est presente dans le squelette,
726
-	// ou si in INCLURE contient {doublons}
727
-	// on insere une fonction de remplissage du tableau des doublons 
728
-	// dans les filtres propre() ou typo()
729
-	// (qui traitent les raccourcis <docXX> referencant les docs)
730
-
731
-	if (isset($p->descr['documents'])
732
-		and
733
-		$p->descr['documents']
734
-		and (
735
-			(strpos($ps, 'propre') !== false)
736
-			or
737
-			(strpos($ps, 'typo') !== false)
738
-		)
739
-	) {
740
-		$ps = 'traiter_doublons_documents($doublons, ' . $ps . ')';
741
-	}
742
-
743
-	// La protection des champs par |safehtml est assuree par les extensions
744
-	// dans la declaration des traitements des champs sensibles
745
-
746
-	// Remplacer enfin le placeholder %s par le vrai code de la balise
747
-	return str_replace('%s', $p->code, $ps);
687
+    if (isset($GLOBALS['table_des_traitements'][$p->nom_champ])) {
688
+        $ps = $GLOBALS['table_des_traitements'][$p->nom_champ];
689
+    } else {
690
+        // quand on utilise un traitement catch-all *
691
+        // celui-ci ne s'applique pas sur les balises calculees qui peuvent gerer
692
+        // leur propre securite
693
+        if (!$p->balise_calculee) {
694
+            $ps = $GLOBALS['table_des_traitements']['*'];
695
+        } else {
696
+            $ps = false;
697
+        }
698
+    }
699
+
700
+    if (is_array($ps)) {
701
+        // Recuperer le type de boucle (articles, DATA) et la table SQL sur laquelle elle porte
702
+        $idb = index_boucle($p);
703
+        // mais on peut aussi etre hors boucle. Se mefier.
704
+        $type_requete = isset($p->boucles[$idb]->type_requete) ? $p->boucles[$idb]->type_requete : false;
705
+        $table_sql = isset($p->boucles[$idb]->show['table_sql']) ? $p->boucles[$idb]->show['table_sql'] : false;
706
+
707
+        // le traitement peut n'etre defini que pour une table en particulier "spip_articles"
708
+        if ($table_sql and isset($ps[$table_sql])) {
709
+            $ps = $ps[$table_sql];
710
+        } // ou pour une boucle en particulier "DATA","articles"
711
+        elseif ($type_requete and isset($ps[$type_requete])) {
712
+            $ps = $ps[$type_requete];
713
+        } // ou pour indiferrement quelle que soit la boucle
714
+        elseif (isset($ps[0])) {
715
+            $ps = $ps[0];
716
+        } else {
717
+            $ps = false;
718
+        }
719
+    }
720
+
721
+    if (!$ps) {
722
+        return $p->code;
723
+    }
724
+
725
+    // Si une boucle DOCUMENTS{doublons} est presente dans le squelette,
726
+    // ou si in INCLURE contient {doublons}
727
+    // on insere une fonction de remplissage du tableau des doublons 
728
+    // dans les filtres propre() ou typo()
729
+    // (qui traitent les raccourcis <docXX> referencant les docs)
730
+
731
+    if (isset($p->descr['documents'])
732
+        and
733
+        $p->descr['documents']
734
+        and (
735
+            (strpos($ps, 'propre') !== false)
736
+            or
737
+            (strpos($ps, 'typo') !== false)
738
+        )
739
+    ) {
740
+        $ps = 'traiter_doublons_documents($doublons, ' . $ps . ')';
741
+    }
742
+
743
+    // La protection des champs par |safehtml est assuree par les extensions
744
+    // dans la declaration des traitements des champs sensibles
745
+
746
+    // Remplacer enfin le placeholder %s par le vrai code de la balise
747
+    return str_replace('%s', $p->code, $ps);
748 748
 }
749 749
 
750 750
 
@@ -757,109 +757,109 @@  discard block
 block discarded – undo
757 757
 // http://code.spip.net/@applique_filtres
758 758
 function applique_filtres($p) {
759 759
 
760
-	// Traitements standards (cf. supra)
761
-	if ($p->etoile == '') {
762
-		$code = champs_traitements($p);
763
-	} else {
764
-		$code = $p->code;
765
-	}
760
+    // Traitements standards (cf. supra)
761
+    if ($p->etoile == '') {
762
+        $code = champs_traitements($p);
763
+    } else {
764
+        $code = $p->code;
765
+    }
766 766
 
767
-	// Appliquer les filtres perso
768
-	if ($p->param) {
769
-		$code = compose_filtres($p, $code);
770
-	}
767
+    // Appliquer les filtres perso
768
+    if ($p->param) {
769
+        $code = compose_filtres($p, $code);
770
+    }
771 771
 
772
-	// S'il y a un lien avec la session, ajouter un code qui levera
773
-	// un drapeau dans la structure d'invalidation $Cache
774
-	if (isset($p->descr['session'])) {
775
-		$code = "invalideur_session(\$Cache, $code)";
776
-	}
772
+    // S'il y a un lien avec la session, ajouter un code qui levera
773
+    // un drapeau dans la structure d'invalidation $Cache
774
+    if (isset($p->descr['session'])) {
775
+        $code = "invalideur_session(\$Cache, $code)";
776
+    }
777 777
 
778
-	$code = sandbox_composer_interdire_scripts($code, $p);
778
+    $code = sandbox_composer_interdire_scripts($code, $p);
779 779
 
780
-	return $code;
780
+    return $code;
781 781
 }
782 782
 
783 783
 // Cf. function pipeline dans ecrire/inc_utils.php
784 784
 // http://code.spip.net/@compose_filtres
785 785
 function compose_filtres(&$p, $code) {
786 786
 
787
-	$image_miette = false;
788
-	foreach ($p->param as $filtre) {
789
-		$fonc = array_shift($filtre);
790
-		if (!$fonc) {
791
-			continue;
792
-		} // normalement qu'au premier tour.
793
-		$is_filtre_image = ((substr($fonc, 0, 6) == 'image_') and $fonc != 'image_graver');
794
-		if ($image_miette and !$is_filtre_image) {
795
-			// il faut graver maintenant car apres le filtre en cours
796
-			// on est pas sur d'avoir encore le nom du fichier dans le pipe
797
-			$code = "filtrer('image_graver', $code)";
798
-			$image_miette = false;
799
-		}
800
-		// recuperer les arguments du filtre, 
801
-		// a separer par "," ou ":" dans le cas du filtre "?{a,b}"
802
-		if ($fonc !== '?') {
803
-			$sep = ',';
804
-		} else {
805
-			$sep = ':';
806
-			// |?{a,b} *doit* avoir exactement 2 arguments ; on les force
807
-			if (count($filtre) != 2) {
808
-				$filtre = array(isset($filtre[0]) ? $filtre[0] : "", isset($filtre[1]) ? $filtre[1] : "");
809
-			}
810
-		}
811
-		$arglist = compose_filtres_args($p, $filtre, $sep);
812
-		$logique = filtre_logique($fonc, $code, substr($arglist, 1));
813
-		if ($logique) {
814
-			$code = $logique;
815
-		} else {
816
-			$code = sandbox_composer_filtre($fonc, $code, $arglist, $p);
817
-			if ($is_filtre_image) {
818
-				$image_miette = true;
819
-			}
820
-		}
821
-	}
822
-	// ramasser les images intermediaires inutiles et graver l'image finale
823
-	if ($image_miette) {
824
-		$code = "filtrer('image_graver',$code)";
825
-	}
826
-
827
-	return $code;
787
+    $image_miette = false;
788
+    foreach ($p->param as $filtre) {
789
+        $fonc = array_shift($filtre);
790
+        if (!$fonc) {
791
+            continue;
792
+        } // normalement qu'au premier tour.
793
+        $is_filtre_image = ((substr($fonc, 0, 6) == 'image_') and $fonc != 'image_graver');
794
+        if ($image_miette and !$is_filtre_image) {
795
+            // il faut graver maintenant car apres le filtre en cours
796
+            // on est pas sur d'avoir encore le nom du fichier dans le pipe
797
+            $code = "filtrer('image_graver', $code)";
798
+            $image_miette = false;
799
+        }
800
+        // recuperer les arguments du filtre, 
801
+        // a separer par "," ou ":" dans le cas du filtre "?{a,b}"
802
+        if ($fonc !== '?') {
803
+            $sep = ',';
804
+        } else {
805
+            $sep = ':';
806
+            // |?{a,b} *doit* avoir exactement 2 arguments ; on les force
807
+            if (count($filtre) != 2) {
808
+                $filtre = array(isset($filtre[0]) ? $filtre[0] : "", isset($filtre[1]) ? $filtre[1] : "");
809
+            }
810
+        }
811
+        $arglist = compose_filtres_args($p, $filtre, $sep);
812
+        $logique = filtre_logique($fonc, $code, substr($arglist, 1));
813
+        if ($logique) {
814
+            $code = $logique;
815
+        } else {
816
+            $code = sandbox_composer_filtre($fonc, $code, $arglist, $p);
817
+            if ($is_filtre_image) {
818
+                $image_miette = true;
819
+            }
820
+        }
821
+    }
822
+    // ramasser les images intermediaires inutiles et graver l'image finale
823
+    if ($image_miette) {
824
+        $code = "filtrer('image_graver',$code)";
825
+    }
826
+
827
+    return $code;
828 828
 }
829 829
 
830 830
 // Filtres et,ou,oui,non,sinon,xou,xor,and,or,not,yes
831 831
 // et comparateurs
832 832
 function filtre_logique($fonc, $code, $arg) {
833 833
 
834
-	switch (true) {
835
-		case in_array($fonc, $GLOBALS['table_criteres_infixes']):
836
-			return "($code $fonc $arg)";
837
-		case ($fonc == 'and') or ($fonc == 'et'):
838
-			return "((($code) AND ($arg)) ?' ' :'')";
839
-		case ($fonc == 'or') or ($fonc == 'ou'):
840
-			return "((($code) OR ($arg)) ?' ' :'')";
841
-		case ($fonc == 'xor') or ($fonc == 'xou'):
842
-			return "((($code) XOR ($arg)) ?' ' :'')";
843
-		case ($fonc == 'sinon'):
844
-			return "(((\$a = $code) OR (is_string(\$a) AND strlen(\$a))) ? \$a : $arg)";
845
-		case ($fonc == 'not') or ($fonc == 'non'):
846
-			return "(($code) ?'' :' ')";
847
-		case ($fonc == 'yes') or ($fonc == 'oui'):
848
-			return "(($code) ?' ' :'')";
849
-	}
850
-
851
-	return '';
834
+    switch (true) {
835
+        case in_array($fonc, $GLOBALS['table_criteres_infixes']):
836
+            return "($code $fonc $arg)";
837
+        case ($fonc == 'and') or ($fonc == 'et'):
838
+            return "((($code) AND ($arg)) ?' ' :'')";
839
+        case ($fonc == 'or') or ($fonc == 'ou'):
840
+            return "((($code) OR ($arg)) ?' ' :'')";
841
+        case ($fonc == 'xor') or ($fonc == 'xou'):
842
+            return "((($code) XOR ($arg)) ?' ' :'')";
843
+        case ($fonc == 'sinon'):
844
+            return "(((\$a = $code) OR (is_string(\$a) AND strlen(\$a))) ? \$a : $arg)";
845
+        case ($fonc == 'not') or ($fonc == 'non'):
846
+            return "(($code) ?'' :' ')";
847
+        case ($fonc == 'yes') or ($fonc == 'oui'):
848
+            return "(($code) ?' ' :'')";
849
+    }
850
+
851
+    return '';
852 852
 }
853 853
 
854 854
 // http://code.spip.net/@compose_filtres_args
855 855
 function compose_filtres_args($p, $args, $sep) {
856
-	$arglist = "";
857
-	foreach ($args as $arg) {
858
-		$arglist .= $sep .
859
-			calculer_liste($arg, $p->descr, $p->boucles, $p->id_boucle);
860
-	}
856
+    $arglist = "";
857
+    foreach ($args as $arg) {
858
+        $arglist .= $sep .
859
+            calculer_liste($arg, $p->descr, $p->boucles, $p->id_boucle);
860
+    }
861 861
 
862
-	return $arglist;
862
+    return $arglist;
863 863
 }
864 864
 
865 865
 
@@ -877,15 +877,15 @@  discard block
 block discarded – undo
877 877
  **/
878 878
 function calculer_argument_precedent($idb, $nom_champ, &$boucles, $defaut = null) {
879 879
 
880
-	// si recursif, forcer l'extraction du champ SQL mais ignorer le code
881
-	if ($boucles[$idb]->externe) {
882
-		index_pile($idb, $nom_champ, $boucles, '', $defaut);
883
-		// retourner $Pile[$SP] et pas $Pile[0] si recursion en 1ere boucle
884
-		// on ignore le defaut fourni dans ce cas
885
-		$defaut = "@\$Pile[\$SP]['$nom_champ']";
886
-	}
880
+    // si recursif, forcer l'extraction du champ SQL mais ignorer le code
881
+    if ($boucles[$idb]->externe) {
882
+        index_pile($idb, $nom_champ, $boucles, '', $defaut);
883
+        // retourner $Pile[$SP] et pas $Pile[0] si recursion en 1ere boucle
884
+        // on ignore le defaut fourni dans ce cas
885
+        $defaut = "@\$Pile[\$SP]['$nom_champ']";
886
+    }
887 887
 
888
-	return index_pile($boucles[$idb]->id_parent, $nom_champ, $boucles, '', $defaut);
888
+    return index_pile($boucles[$idb]->id_parent, $nom_champ, $boucles, '', $defaut);
889 889
 }
890 890
 
891 891
 //
@@ -900,28 +900,28 @@  discard block
 block discarded – undo
900 900
 
901 901
 // http://code.spip.net/@rindex_pile
902 902
 function rindex_pile($p, $champ, $motif) {
903
-	$n = 0;
904
-	$b = $p->id_boucle;
905
-	$p->code = '';
906
-	while ($b != '') {
907
-		foreach ($p->boucles[$b]->criteres as $critere) {
908
-			if ($critere->op == $motif) {
909
-				$p->code = '$Pile[$SP' . (($n == 0) ? "" : "-$n") .
910
-					"]['$champ']";
911
-				$b = '';
912
-				break 2;
913
-			}
914
-		}
915
-		$n++;
916
-		$b = $p->boucles[$b]->id_parent;
917
-	}
918
-
919
-	// si on est hors d'une boucle de {recherche}, cette balise est vide
920
-	if (!$p->code) {
921
-		$p->code = "''";
922
-	}
923
-
924
-	$p->interdire_scripts = false;
925
-
926
-	return $p;
903
+    $n = 0;
904
+    $b = $p->id_boucle;
905
+    $p->code = '';
906
+    while ($b != '') {
907
+        foreach ($p->boucles[$b]->criteres as $critere) {
908
+            if ($critere->op == $motif) {
909
+                $p->code = '$Pile[$SP' . (($n == 0) ? "" : "-$n") .
910
+                    "]['$champ']";
911
+                $b = '';
912
+                break 2;
913
+            }
914
+        }
915
+        $n++;
916
+        $b = $p->boucles[$b]->id_parent;
917
+    }
918
+
919
+    // si on est hors d'une boucle de {recherche}, cette balise est vide
920
+    if (!$p->code) {
921
+        $p->code = "''";
922
+    }
923
+
924
+    $p->interdire_scripts = false;
925
+
926
+    return $p;
927 927
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	$select = true
96 96
 ) {
97 97
 	if (!is_string($defaut)) {
98
-		$defaut = '@$Pile[0][\'' . strtolower($nom_champ) . '\']';
98
+		$defaut = '@$Pile[0][\''.strtolower($nom_champ).'\']';
99 99
 	}
100 100
 
101 101
 	$i = 0;
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 			if ($select and !in_array($t, $boucles[$idb]->select)) {
124 124
 				$boucles[$idb]->select[] = $t;
125 125
 			}
126
-			$champ = '$Pile[$SP' . ($i ? "-$i" : "") . '][\'' . $c . '\']';
126
+			$champ = '$Pile[$SP'.($i ? "-$i" : "").'][\''.$c.'\']';
127 127
 			if (!$joker) {
128 128
 				return index_compose($conditionnel, $champ);
129 129
 			}
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 function index_compose($conditionnel, $defaut) {
165 165
 	while ($c = array_pop($conditionnel)) {
166 166
 		// si on passe defaut = '', ne pas générer d'erreur de compilation.
167
-		$defaut = "($c:(" . ($defaut ? $defaut : "''") . "))";
167
+		$defaut = "($c:(".($defaut ? $defaut : "''")."))";
168 168
 	}
169 169
 
170 170
 	return $defaut;
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	if (!$r) {
212 212
 		$joker = false; // indiquer a l'appelant
213 213
 		# continuer pour chercher l'erreur suivante
214
-		return array("'#" . $r . ':' . $nom_champ . "'", '');
214
+		return array("'#".$r.':'.$nom_champ."'", '');
215 215
 	}
216 216
 
217 217
 	$desc = $boucles[$idb]->show;
@@ -311,8 +311,8 @@  discard block
 block discarded – undo
311 311
 			$t = $index_exception_derogatoire($boucle, $desc, $nom_champ, $excep);
312 312
 		}
313 313
 		if ($t == null) {
314
-			list($e, $x) = $excep;  #PHP4 affecte de gauche a droite
315
-			$excep = $x;    #PHP5 de droite a gauche !
314
+			list($e, $x) = $excep; #PHP4 affecte de gauche a droite
315
+			$excep = $x; #PHP5 de droite a gauche !
316 316
 			$j = $trouver_table($e, $boucle->sql_serveur);
317 317
 			if (!$j) {
318 318
 				return array('', '');
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 					$l = (preg_split('/\s*,\s*/', $k));
325 325
 					$k = $desc['key']['PRIMARY KEY'];
326 326
 					if (!in_array($k, $l)) {
327
-						spip_log("jointure impossible $e " . join(',', $l));
327
+						spip_log("jointure impossible $e ".join(',', $l));
328 328
 
329 329
 						return array('', '');
330 330
 					}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 	// demander a SQL de gerer le synonyme
341 341
 	// ca permet que excep soit dynamique (Cedric, 2/3/06)
342 342
 	if ($excep != $nom_champ) {
343
-		$excep .= ' AS ' . $nom_champ;
343
+		$excep .= ' AS '.$nom_champ;
344 344
 	}
345 345
 
346 346
 	return array("$t.$excep", $nom_champ);
@@ -573,7 +573,7 @@  discard block
 block discarded – undo
573 573
 		join(',', $collecte),
574 574
 		($collecte ? $param : substr($param, 1)), # virer la virgule
575 575
 		memoriser_contexte_compil($p),
576
-		(!$supp ? '' : (', ' . join(',', $supp))));
576
+		(!$supp ? '' : (', '.join(',', $supp))));
577 577
 
578 578
 	$p->interdire_scripts = false;
579 579
 
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 	$nom = $p->id_boucle;
669 669
 
670 670
 	if ($nom and trouver_nom_serveur_distant($p)) {
671
-		spip_log($nom . ':' . $p->nom_champ . ' ' . _T('zbug_distant_interdit'));
671
+		spip_log($nom.':'.$p->nom_champ.' '._T('zbug_distant_interdit'));
672 672
 
673 673
 		return false;
674 674
 	}
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
 			(strpos($ps, 'typo') !== false)
738 738
 		)
739 739
 	) {
740
-		$ps = 'traiter_doublons_documents($doublons, ' . $ps . ')';
740
+		$ps = 'traiter_doublons_documents($doublons, '.$ps.')';
741 741
 	}
742 742
 
743 743
 	// La protection des champs par |safehtml est assuree par les extensions
@@ -855,7 +855,7 @@  discard block
 block discarded – undo
855 855
 function compose_filtres_args($p, $args, $sep) {
856 856
 	$arglist = "";
857 857
 	foreach ($args as $arg) {
858
-		$arglist .= $sep .
858
+		$arglist .= $sep.
859 859
 			calculer_liste($arg, $p->descr, $p->boucles, $p->id_boucle);
860 860
 	}
861 861
 
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
 	while ($b != '') {
907 907
 		foreach ($p->boucles[$b]->criteres as $critere) {
908 908
 			if ($critere->op == $motif) {
909
-				$p->code = '$Pile[$SP' . (($n == 0) ? "" : "-$n") .
909
+				$p->code = '$Pile[$SP'.(($n == 0) ? "" : "-$n").
910 910
 					"]['$champ']";
911 911
 				$b = '';
912 912
 				break 2;
Please login to merge, or discard this patch.
ecrire/public/sandbox.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@
 block discarded – undo
158 158
  * @param string $corps
159 159
  * @param array $filtres
160 160
  *     Tableau de filtres à appliquer.
161
- * @return mixed|string
161
+ * @return string
162 162
  */
163 163
 function sandbox_filtrer_squelette($skel, $corps, $filtres) {
164 164
 	$series_filtres = func_get_args();
Please login to merge, or discard this patch.
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
  **/
24 24
 
25 25
 if (!defined('_ECRIRE_INC_VERSION')) {
26
-	return;
26
+    return;
27 27
 }
28 28
 
29 29
 /**
@@ -41,9 +41,9 @@  discard block
 block discarded – undo
41 41
  *     Texte
42 42
  */
43 43
 function sandbox_composer_texte($texte, &$p) {
44
-	$code = "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $texte) . "'";
44
+    $code = "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $texte) . "'";
45 45
 
46
-	return $code;
46
+    return $code;
47 47
 }
48 48
 
49 49
 
@@ -58,35 +58,35 @@  discard block
 block discarded – undo
58 58
  * @return string
59 59
  */
60 60
 function sandbox_composer_filtre($fonc, $code, $arglist, &$p) {
61
-	if (isset($GLOBALS['spip_matrice'][$fonc])) {
62
-		$code = "filtrer('$fonc',$code$arglist)";
63
-	}
64
-
65
-	// le filtre est defini sous forme de fonction ou de methode
66
-	// par ex. dans inc_texte, inc_filtres ou mes_fonctions
67
-	elseif ($f = chercher_filtre($fonc)) {
68
-
69
-		// cas particulier : le filtre |set doit acceder a la $Pile
70
-		// proto: filtre_set(&$Pile, $val, $args...)
71
-		if (strpbrk($f, ':')) { // Class::method
72
-			$refl = new ReflectionMethod($f);
73
-		} else {
74
-			$refl = new ReflectionFunction($f);
75
-		}
76
-		$refs = $refl->getParameters();
77
-		if (isset($refs[0]) and $refs[0]->name == 'Pile') {
78
-			$code = "$f(\$Pile,$code$arglist)";
79
-		} else {
80
-			$code = "$f($code$arglist)";
81
-		}
82
-	}
83
-	// le filtre n'existe pas,
84
-	// on le notifie
85
-	else {
86
-		erreur_squelette(array('zbug_erreur_filtre', array('filtre' => texte_script($fonc))), $p);
87
-	}
88
-
89
-	return $code;
61
+    if (isset($GLOBALS['spip_matrice'][$fonc])) {
62
+        $code = "filtrer('$fonc',$code$arglist)";
63
+    }
64
+
65
+    // le filtre est defini sous forme de fonction ou de methode
66
+    // par ex. dans inc_texte, inc_filtres ou mes_fonctions
67
+    elseif ($f = chercher_filtre($fonc)) {
68
+
69
+        // cas particulier : le filtre |set doit acceder a la $Pile
70
+        // proto: filtre_set(&$Pile, $val, $args...)
71
+        if (strpbrk($f, ':')) { // Class::method
72
+            $refl = new ReflectionMethod($f);
73
+        } else {
74
+            $refl = new ReflectionFunction($f);
75
+        }
76
+        $refs = $refl->getParameters();
77
+        if (isset($refs[0]) and $refs[0]->name == 'Pile') {
78
+            $code = "$f(\$Pile,$code$arglist)";
79
+        } else {
80
+            $code = "$f($code$arglist)";
81
+        }
82
+    }
83
+    // le filtre n'existe pas,
84
+    // on le notifie
85
+    else {
86
+        erreur_squelette(array('zbug_erreur_filtre', array('filtre' => texte_script($fonc))), $p);
87
+    }
88
+
89
+    return $code;
90 90
 }
91 91
 
92 92
 // Calculer un <INCLURE(xx.php)>
@@ -110,15 +110,15 @@  discard block
 block discarded – undo
110 110
  * @return string
111 111
  */
112 112
 function sandbox_composer_inclure_php($fichier, &$p, $_contexte) {
113
-	$compil = texte_script(memoriser_contexte_compil($p));
114
-	// si inexistant, on essaiera a l'execution
115
-	if ($path = find_in_path($fichier)) {
116
-		$path = "\"$path\"";
117
-	} else {
118
-		$path = "find_in_path(\"$fichier\")";
119
-	}
120
-
121
-	return sprintf(CODE_INCLURE_SCRIPT, $path, $fichier, $compil, $_contexte);
113
+    $compil = texte_script(memoriser_contexte_compil($p));
114
+    // si inexistant, on essaiera a l'execution
115
+    if ($path = find_in_path($fichier)) {
116
+        $path = "\"$path\"";
117
+    } else {
118
+        $path = "find_in_path(\"$fichier\")";
119
+    }
120
+
121
+    return sprintf(CODE_INCLURE_SCRIPT, $path, $fichier, $compil, $_contexte);
122 122
 }
123 123
 
124 124
 /**
@@ -130,19 +130,19 @@  discard block
 block discarded – undo
130 130
  * @return string
131 131
  */
132 132
 function sandbox_composer_interdire_scripts($code, &$p) {
133
-	// Securite
134
-	if ($p->interdire_scripts
135
-		and $p->etoile != '**'
136
-	) {
137
-		if (!preg_match("/^sinon[(](.*),'([^']*)'[)]$/", $code, $r)) {
138
-			$code = "interdire_scripts($code)";
139
-		} else {
140
-			$code = interdire_scripts($r[2]);
141
-			$code = "sinon(interdire_scripts($r[1]),'$code')";
142
-		}
143
-	}
144
-
145
-	return $code;
133
+    // Securite
134
+    if ($p->interdire_scripts
135
+        and $p->etoile != '**'
136
+    ) {
137
+        if (!preg_match("/^sinon[(](.*),'([^']*)'[)]$/", $code, $r)) {
138
+            $code = "interdire_scripts($code)";
139
+        } else {
140
+            $code = interdire_scripts($r[2]);
141
+            $code = "sinon(interdire_scripts($r[1]),'$code')";
142
+        }
143
+    }
144
+
145
+    return $code;
146 146
 }
147 147
 
148 148
 
@@ -161,30 +161,30 @@  discard block
 block discarded – undo
161 161
  * @return mixed|string
162 162
  */
163 163
 function sandbox_filtrer_squelette($skel, $corps, $filtres) {
164
-	$series_filtres = func_get_args();
165
-	array_shift($series_filtres);// skel
166
-	array_shift($series_filtres);// corps
167
-
168
-	// proteger les <INCLUDE> et tous les morceaux de php licites
169
-	if ($skel['process_ins'] == 'php') {
170
-		$corps = preg_replace_callback(',<[?](\s|php|=).*[?]>,UimsS', 'echapper_php_callback', $corps);
171
-	}
172
-
173
-	// recuperer les couples de remplacement
174
-	$replace = echapper_php_callback();
175
-
176
-	foreach ($series_filtres as $filtres) {
177
-		if (count($filtres)) {
178
-			foreach ($filtres as $filtre) {
179
-				if ($filtre and $f = chercher_filtre($filtre)) {
180
-					$corps = $f($corps);
181
-				}
182
-			}
183
-		}
184
-	}
185
-
186
-	// restaurer les echappements
187
-	return str_replace($replace[0], $replace[1], $corps);
164
+    $series_filtres = func_get_args();
165
+    array_shift($series_filtres);// skel
166
+    array_shift($series_filtres);// corps
167
+
168
+    // proteger les <INCLUDE> et tous les morceaux de php licites
169
+    if ($skel['process_ins'] == 'php') {
170
+        $corps = preg_replace_callback(',<[?](\s|php|=).*[?]>,UimsS', 'echapper_php_callback', $corps);
171
+    }
172
+
173
+    // recuperer les couples de remplacement
174
+    $replace = echapper_php_callback();
175
+
176
+    foreach ($series_filtres as $filtres) {
177
+        if (count($filtres)) {
178
+            foreach ($filtres as $filtre) {
179
+                if ($filtre and $f = chercher_filtre($filtre)) {
180
+                    $corps = $f($corps);
181
+                }
182
+            }
183
+        }
184
+    }
185
+
186
+    // restaurer les echappements
187
+    return str_replace($replace[0], $replace[1], $corps);
188 188
 }
189 189
 
190 190
 
@@ -203,21 +203,21 @@  discard block
 block discarded – undo
203 203
  *     - array : Liste( liste des codes PHP, liste des substitutions )
204 204
  **/
205 205
 function echapper_php_callback($r = null) {
206
-	static $src = array();
207
-	static $dst = array();
206
+    static $src = array();
207
+    static $dst = array();
208 208
 
209
-	// si on recoit un tableau, on est en mode echappement
210
-	// on enregistre le code a echapper dans dst, et le code echappe dans src
211
-	if (is_array($r)) {
212
-		$dst[] = $r[0];
209
+    // si on recoit un tableau, on est en mode echappement
210
+    // on enregistre le code a echapper dans dst, et le code echappe dans src
211
+    if (is_array($r)) {
212
+        $dst[] = $r[0];
213 213
 
214
-		return $src[] = '___' . md5($r[0]) . '___';
215
-	}
214
+        return $src[] = '___' . md5($r[0]) . '___';
215
+    }
216 216
 
217
-	// si on recoit pas un tableau, on renvoit les couples de substitution
218
-	// et on RAZ les remplacements
219
-	$r = array($src, $dst);
220
-	$src = $dst = array();
217
+    // si on recoit pas un tableau, on renvoit les couples de substitution
218
+    // et on RAZ les remplacements
219
+    $r = array($src, $dst);
220
+    $src = $dst = array();
221 221
 
222
-	return $r;
222
+    return $r;
223 223
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
  *     Texte
42 42
  */
43 43
 function sandbox_composer_texte($texte, &$p) {
44
-	$code = "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $texte) . "'";
44
+	$code = "'".str_replace(array("\\", "'"), array("\\\\", "\\'"), $texte)."'";
45 45
 
46 46
 	return $code;
47 47
 }
@@ -162,8 +162,8 @@  discard block
 block discarded – undo
162 162
  */
163 163
 function sandbox_filtrer_squelette($skel, $corps, $filtres) {
164 164
 	$series_filtres = func_get_args();
165
-	array_shift($series_filtres);// skel
166
-	array_shift($series_filtres);// corps
165
+	array_shift($series_filtres); // skel
166
+	array_shift($series_filtres); // corps
167 167
 
168 168
 	// proteger les <INCLUDE> et tous les morceaux de php licites
169 169
 	if ($skel['process_ins'] == 'php') {
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	if (is_array($r)) {
212 212
 		$dst[] = $r[0];
213 213
 
214
-		return $src[] = '___' . md5($r[0]) . '___';
214
+		return $src[] = '___'.md5($r[0]).'___';
215 215
 	}
216 216
 
217 217
 	// si on recoit pas un tableau, on renvoit les couples de substitution
Please login to merge, or discard this patch.
ecrire/public/styliser_par_z.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -236,7 +236,7 @@
 block discarded – undo
236 236
  * @param string $type
237 237
  * @param string $ext
238 238
  * @param bool $echafauder
239
- * @return mixed
239
+ * @return string|boolean
240 240
  */
241 241
 function z_contenu_disponible($prefix_path, $z_contenu, $type, $ext, $echafauder = true) {
242 242
 	if ($d = z_trouver_bloc($prefix_path, $z_contenu, $type, $ext)) {
Please login to merge, or discard this patch.
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
  * @package SPIP\Core\Public\Styliser
20 20
  **/
21 21
 if (!defined("_ECRIRE_INC_VERSION")) {
22
-	return;
22
+    return;
23 23
 }
24 24
 
25 25
 /**
@@ -29,181 +29,181 @@  discard block
 block discarded – undo
29 29
  * @return array Données modifiées du pipeline
30 30
  */
31 31
 function public_styliser_par_z_dist($flux) {
32
-	static $prefix_path = null;
33
-	static $prefix_length;
34
-	static $z_blocs;
35
-	static $apl_constant;
36
-	static $page;
37
-	static $disponible = array();
38
-	static $echafauder;
39
-	static $prepend = "";
40
-
41
-	if (!isset($prefix_path)) {
42
-		$z_blocs = z_blocs(test_espace_prive());
43
-		if (test_espace_prive()) {
44
-			$prefix_path = "prive/squelettes/";
45
-			$prefix_length = strlen($prefix_path);
46
-			$apl_constant = '_ECRIRE_AJAX_PARALLEL_LOAD';
47
-			$page = 'exec';
48
-			$echafauder = charger_fonction('echafauder', 'prive', true);
49
-			define('_ZCORE_EXCLURE_PATH', '');
50
-		} else {
51
-			$prefix_path = "";
52
-			$prefix_length = 0;
53
-			$apl_constant = '_Z_AJAX_PARALLEL_LOAD';
54
-			$page = _SPIP_PAGE;
55
-			$echafauder = charger_fonction('echafauder', 'public', true);
56
-			define('_ZCORE_EXCLURE_PATH', '\bprive|\bsquelettes-dist' . (defined('_DIR_PLUGIN_DIST') ? '|\b' . rtrim(_DIR_PLUGIN_DIST,
57
-						'/') : ''));
58
-		}
59
-		$prepend = (defined('_Z_PREPEND_PATH') ? _Z_PREPEND_PATH : "");
60
-	}
61
-	$z_contenu = reset($z_blocs); // contenu par defaut
62
-
63
-	$fond = $flux['args']['fond'];
64
-
65
-	if ($prepend or strncmp($fond, $prefix_path, $prefix_length) == 0) {
66
-		$fond = substr($fond, $prefix_length);
67
-		$squelette = $flux['data'];
68
-		$ext = $flux['args']['ext'];
69
-		// Ajax Parallel loading : ne pas calculer le bloc, mais renvoyer un js qui le loadera en ajax
70
-		if (defined('_Z_AJAX_PARALLEL_LOAD_OK')
71
-			and $dir = explode('/', $fond)
72
-			and count($dir) == 2 // pas un sous repertoire
73
-			and $dir = reset($dir)
74
-			and in_array($dir, $z_blocs) // verifier deja qu'on est dans un bloc Z
75
-			and defined($apl_constant)
76
-			and in_array($dir, explode(',', constant($apl_constant))) // et dans un demande en APL
77
-			and $pipe = z_trouver_bloc($prefix_path . $prepend, $dir, 'z_apl', $ext) // et qui contient le squelette APL
78
-		) {
79
-			$flux['data'] = $pipe;
80
-
81
-			return $flux;
82
-		}
83
-
84
-		// surcharger aussi les squelettes venant de squelettes-dist/
85
-		if ($squelette and !z_fond_valide($squelette)) {
86
-			$squelette = "";
87
-			$echafauder = "";
88
-		}
89
-		if ($prepend) {
90
-			$squelette = substr(find_in_path($prefix_path . $prepend . "$fond.$ext"), 0, -strlen(".$ext"));
91
-			if ($squelette) {
92
-				$flux['data'] = $squelette;
93
-			}
94
-		}
95
-
96
-		// gerer les squelettes non trouves
97
-		// -> router vers les /dist.html
98
-		// ou scaffolding ou page automatique les contenus
99
-		if (!$squelette) {
100
-
101
-			// si on est sur un ?page=XX non trouve
102
-			if ((isset($flux['args']['contexte'][$page])
103
-					and $flux['args']['contexte'][$page] == $fond)
104
-				or (isset($flux['args']['contexte']['type-page'])
105
-					and $flux['args']['contexte']['type-page'] == $fond)
106
-				or ($fond == 'sommaire'
107
-					and (!isset($flux['args']['contexte'][$page]) or !$flux['args']['contexte'][$page]))
108
-			) {
109
-
110
-				// si on est sur un ?page=XX non trouve
111
-				// se brancher sur contenu/xx si il existe
112
-				// ou si c'est un objet spip, associe a une table, utiliser le fond homonyme
113
-				if (!isset($disponible[$fond])) {
114
-					$disponible[$fond] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $fond, $ext, $echafauder);
115
-				}
116
-
117
-				if ($disponible[$fond]) {
118
-					$flux['data'] = substr(find_in_path($prefix_path . "page.$ext"), 0, -strlen(".$ext"));
119
-				}
120
-			}
121
-
122
-			// echafaudage :
123
-			// si c'est un fond de contenu d'un objet en base
124
-			// generer un fond automatique a la volee pour les webmestres
125
-			elseif (strncmp($fond, "$z_contenu/", strlen($z_contenu) + 1) == 0) {
126
-				$type = substr($fond, strlen($z_contenu) + 1);
127
-				if (($type == 'page') and isset($flux['args']['contexte'][$page])) {
128
-					$type = $flux['args']['contexte'][$page];
129
-				}
130
-				if (!isset($disponible[$type])) {
131
-					$disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
132
-				}
133
-				if (is_string($disponible[$type])) {
134
-					$flux['data'] = $disponible[$type];
135
-				} elseif ($echafauder
136
-					and include_spip('inc/autoriser')
137
-					and isset($GLOBALS['visiteur_session']['statut']) // performance
138
-					and autoriser('echafauder', $type)
139
-					and $is = $disponible[$type]
140
-					and is_array($is)
141
-				) {
142
-					$flux['data'] = $echafauder($type, $is[0], $is[1], $is[2], $ext);
143
-				} else {
144
-					$flux['data'] = ($disponible['404'] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, '404', $ext,
145
-						$echafauder));
146
-				}
147
-			}
148
-
149
-			// sinon, si on demande un fond non trouve dans un des autres blocs
150
-			// et si il y a bien un contenu correspondant ou echafaudable
151
-			// se rabbatre sur le dist.html du bloc concerne
152
-			else {
153
-				if ($dir = explode('/', $fond)
154
-					and $dir = reset($dir)
155
-					and $dir !== $z_contenu
156
-					and in_array($dir, $z_blocs)
157
-				) {
158
-					$type = substr($fond, strlen("$dir/"));
159
-					if (($type == 'page') and isset($flux['args']['contexte'][$page])) {
160
-						$type = $flux['args']['contexte'][$page];
161
-					}
162
-					if ($type !== 'page' and !isset($disponible[$type])) {
163
-						$disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
164
-					}
165
-					if ($type == 'page' or $disponible[$type]) {
166
-						$flux['data'] = z_trouver_bloc($prefix_path . $prepend, $dir, 'dist', $ext);
167
-					}
168
-				}
169
-			}
170
-			$squelette = $flux['data'];
171
-		}
172
-		// layout specifiques par type et compositions :
173
-		// body-article.html
174
-		// body-sommaire.html
175
-		// pour des raisons de perfo, les declinaisons doivent etre dans le
176
-		// meme dossier que body.html
177
-		if ($fond == 'body' and substr($squelette, -strlen($fond)) == $fond) {
178
-			if (isset($flux['args']['contexte']['type-page'])
179
-				and (
180
-					(isset($flux['args']['contexte']['composition'])
181
-						and file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page'] . "-" . $flux['args']['contexte']['composition']) . ".$ext"))
182
-					or
183
-					file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page']) . ".$ext")
184
-				)
185
-			) {
186
-				$flux['data'] = $f;
187
-			}
188
-		} elseif ($fond == 'structure'
189
-			and z_sanitize_var_zajax()
190
-			and $f = find_in_path($prefix_path . $prepend . 'ajax' . ".$ext")
191
-		) {
192
-			$flux['data'] = substr($f, 0, -strlen(".$ext"));
193
-		} // chercher le fond correspondant a la composition
194
-		elseif (isset($flux['args']['contexte']['composition'])
195
-			and (basename($fond) == 'page' or ($squelette and substr($squelette, -strlen($fond)) == $fond))
196
-			and $dir = substr($fond, $prefix_length)
197
-			and $dir = explode('/', $dir)
198
-			and $dir = reset($dir)
199
-			and in_array($dir, $z_blocs)
200
-			and $f = find_in_path($prefix_path . $prepend . $fond . "-" . $flux['args']['contexte']['composition'] . ".$ext")
201
-		) {
202
-			$flux['data'] = substr($f, 0, -strlen(".$ext"));
203
-		}
204
-	}
205
-
206
-	return $flux;
32
+    static $prefix_path = null;
33
+    static $prefix_length;
34
+    static $z_blocs;
35
+    static $apl_constant;
36
+    static $page;
37
+    static $disponible = array();
38
+    static $echafauder;
39
+    static $prepend = "";
40
+
41
+    if (!isset($prefix_path)) {
42
+        $z_blocs = z_blocs(test_espace_prive());
43
+        if (test_espace_prive()) {
44
+            $prefix_path = "prive/squelettes/";
45
+            $prefix_length = strlen($prefix_path);
46
+            $apl_constant = '_ECRIRE_AJAX_PARALLEL_LOAD';
47
+            $page = 'exec';
48
+            $echafauder = charger_fonction('echafauder', 'prive', true);
49
+            define('_ZCORE_EXCLURE_PATH', '');
50
+        } else {
51
+            $prefix_path = "";
52
+            $prefix_length = 0;
53
+            $apl_constant = '_Z_AJAX_PARALLEL_LOAD';
54
+            $page = _SPIP_PAGE;
55
+            $echafauder = charger_fonction('echafauder', 'public', true);
56
+            define('_ZCORE_EXCLURE_PATH', '\bprive|\bsquelettes-dist' . (defined('_DIR_PLUGIN_DIST') ? '|\b' . rtrim(_DIR_PLUGIN_DIST,
57
+                        '/') : ''));
58
+        }
59
+        $prepend = (defined('_Z_PREPEND_PATH') ? _Z_PREPEND_PATH : "");
60
+    }
61
+    $z_contenu = reset($z_blocs); // contenu par defaut
62
+
63
+    $fond = $flux['args']['fond'];
64
+
65
+    if ($prepend or strncmp($fond, $prefix_path, $prefix_length) == 0) {
66
+        $fond = substr($fond, $prefix_length);
67
+        $squelette = $flux['data'];
68
+        $ext = $flux['args']['ext'];
69
+        // Ajax Parallel loading : ne pas calculer le bloc, mais renvoyer un js qui le loadera en ajax
70
+        if (defined('_Z_AJAX_PARALLEL_LOAD_OK')
71
+            and $dir = explode('/', $fond)
72
+            and count($dir) == 2 // pas un sous repertoire
73
+            and $dir = reset($dir)
74
+            and in_array($dir, $z_blocs) // verifier deja qu'on est dans un bloc Z
75
+            and defined($apl_constant)
76
+            and in_array($dir, explode(',', constant($apl_constant))) // et dans un demande en APL
77
+            and $pipe = z_trouver_bloc($prefix_path . $prepend, $dir, 'z_apl', $ext) // et qui contient le squelette APL
78
+        ) {
79
+            $flux['data'] = $pipe;
80
+
81
+            return $flux;
82
+        }
83
+
84
+        // surcharger aussi les squelettes venant de squelettes-dist/
85
+        if ($squelette and !z_fond_valide($squelette)) {
86
+            $squelette = "";
87
+            $echafauder = "";
88
+        }
89
+        if ($prepend) {
90
+            $squelette = substr(find_in_path($prefix_path . $prepend . "$fond.$ext"), 0, -strlen(".$ext"));
91
+            if ($squelette) {
92
+                $flux['data'] = $squelette;
93
+            }
94
+        }
95
+
96
+        // gerer les squelettes non trouves
97
+        // -> router vers les /dist.html
98
+        // ou scaffolding ou page automatique les contenus
99
+        if (!$squelette) {
100
+
101
+            // si on est sur un ?page=XX non trouve
102
+            if ((isset($flux['args']['contexte'][$page])
103
+                    and $flux['args']['contexte'][$page] == $fond)
104
+                or (isset($flux['args']['contexte']['type-page'])
105
+                    and $flux['args']['contexte']['type-page'] == $fond)
106
+                or ($fond == 'sommaire'
107
+                    and (!isset($flux['args']['contexte'][$page]) or !$flux['args']['contexte'][$page]))
108
+            ) {
109
+
110
+                // si on est sur un ?page=XX non trouve
111
+                // se brancher sur contenu/xx si il existe
112
+                // ou si c'est un objet spip, associe a une table, utiliser le fond homonyme
113
+                if (!isset($disponible[$fond])) {
114
+                    $disponible[$fond] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $fond, $ext, $echafauder);
115
+                }
116
+
117
+                if ($disponible[$fond]) {
118
+                    $flux['data'] = substr(find_in_path($prefix_path . "page.$ext"), 0, -strlen(".$ext"));
119
+                }
120
+            }
121
+
122
+            // echafaudage :
123
+            // si c'est un fond de contenu d'un objet en base
124
+            // generer un fond automatique a la volee pour les webmestres
125
+            elseif (strncmp($fond, "$z_contenu/", strlen($z_contenu) + 1) == 0) {
126
+                $type = substr($fond, strlen($z_contenu) + 1);
127
+                if (($type == 'page') and isset($flux['args']['contexte'][$page])) {
128
+                    $type = $flux['args']['contexte'][$page];
129
+                }
130
+                if (!isset($disponible[$type])) {
131
+                    $disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
132
+                }
133
+                if (is_string($disponible[$type])) {
134
+                    $flux['data'] = $disponible[$type];
135
+                } elseif ($echafauder
136
+                    and include_spip('inc/autoriser')
137
+                    and isset($GLOBALS['visiteur_session']['statut']) // performance
138
+                    and autoriser('echafauder', $type)
139
+                    and $is = $disponible[$type]
140
+                    and is_array($is)
141
+                ) {
142
+                    $flux['data'] = $echafauder($type, $is[0], $is[1], $is[2], $ext);
143
+                } else {
144
+                    $flux['data'] = ($disponible['404'] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, '404', $ext,
145
+                        $echafauder));
146
+                }
147
+            }
148
+
149
+            // sinon, si on demande un fond non trouve dans un des autres blocs
150
+            // et si il y a bien un contenu correspondant ou echafaudable
151
+            // se rabbatre sur le dist.html du bloc concerne
152
+            else {
153
+                if ($dir = explode('/', $fond)
154
+                    and $dir = reset($dir)
155
+                    and $dir !== $z_contenu
156
+                    and in_array($dir, $z_blocs)
157
+                ) {
158
+                    $type = substr($fond, strlen("$dir/"));
159
+                    if (($type == 'page') and isset($flux['args']['contexte'][$page])) {
160
+                        $type = $flux['args']['contexte'][$page];
161
+                    }
162
+                    if ($type !== 'page' and !isset($disponible[$type])) {
163
+                        $disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
164
+                    }
165
+                    if ($type == 'page' or $disponible[$type]) {
166
+                        $flux['data'] = z_trouver_bloc($prefix_path . $prepend, $dir, 'dist', $ext);
167
+                    }
168
+                }
169
+            }
170
+            $squelette = $flux['data'];
171
+        }
172
+        // layout specifiques par type et compositions :
173
+        // body-article.html
174
+        // body-sommaire.html
175
+        // pour des raisons de perfo, les declinaisons doivent etre dans le
176
+        // meme dossier que body.html
177
+        if ($fond == 'body' and substr($squelette, -strlen($fond)) == $fond) {
178
+            if (isset($flux['args']['contexte']['type-page'])
179
+                and (
180
+                    (isset($flux['args']['contexte']['composition'])
181
+                        and file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page'] . "-" . $flux['args']['contexte']['composition']) . ".$ext"))
182
+                    or
183
+                    file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page']) . ".$ext")
184
+                )
185
+            ) {
186
+                $flux['data'] = $f;
187
+            }
188
+        } elseif ($fond == 'structure'
189
+            and z_sanitize_var_zajax()
190
+            and $f = find_in_path($prefix_path . $prepend . 'ajax' . ".$ext")
191
+        ) {
192
+            $flux['data'] = substr($f, 0, -strlen(".$ext"));
193
+        } // chercher le fond correspondant a la composition
194
+        elseif (isset($flux['args']['contexte']['composition'])
195
+            and (basename($fond) == 'page' or ($squelette and substr($squelette, -strlen($fond)) == $fond))
196
+            and $dir = substr($fond, $prefix_length)
197
+            and $dir = explode('/', $dir)
198
+            and $dir = reset($dir)
199
+            and in_array($dir, $z_blocs)
200
+            and $f = find_in_path($prefix_path . $prepend . $fond . "-" . $flux['args']['contexte']['composition'] . ".$ext")
201
+        ) {
202
+            $flux['data'] = substr($f, 0, -strlen(".$ext"));
203
+        }
204
+    }
205
+
206
+    return $flux;
207 207
 }
208 208
 
209 209
 /**
@@ -213,18 +213,18 @@  discard block
 block discarded – undo
213 213
  * @return array
214 214
  */
215 215
 function z_blocs($espace_prive = false) {
216
-	if ($espace_prive) {
217
-		return (isset($GLOBALS['z_blocs_ecrire']) ? $GLOBALS['z_blocs_ecrire'] : array(
218
-			'contenu',
219
-			'navigation',
220
-			'extra',
221
-			'head',
222
-			'hierarchie',
223
-			'top'
224
-		));
225
-	}
226
-
227
-	return (isset($GLOBALS['z_blocs']) ? $GLOBALS['z_blocs'] : array('contenu'));
216
+    if ($espace_prive) {
217
+        return (isset($GLOBALS['z_blocs_ecrire']) ? $GLOBALS['z_blocs_ecrire'] : array(
218
+            'contenu',
219
+            'navigation',
220
+            'extra',
221
+            'head',
222
+            'hierarchie',
223
+            'top'
224
+        ));
225
+    }
226
+
227
+    return (isset($GLOBALS['z_blocs']) ? $GLOBALS['z_blocs'] : array('contenu'));
228 228
 }
229 229
 
230 230
 /**
@@ -239,11 +239,11 @@  discard block
 block discarded – undo
239 239
  * @return mixed
240 240
  */
241 241
 function z_contenu_disponible($prefix_path, $z_contenu, $type, $ext, $echafauder = true) {
242
-	if ($d = z_trouver_bloc($prefix_path, $z_contenu, $type, $ext)) {
243
-		return $d;
244
-	}
242
+    if ($d = z_trouver_bloc($prefix_path, $z_contenu, $type, $ext)) {
243
+        return $d;
244
+    }
245 245
 
246
-	return $echafauder ? z_echafaudable($type) : false;
246
+    return $echafauder ? z_echafaudable($type) : false;
247 247
 }
248 248
 
249 249
 /**
@@ -257,13 +257,13 @@  discard block
 block discarded – undo
257 257
  *   `true` si on peut l'utiliser, `false` sinon.
258 258
  **/
259 259
 function z_fond_valide($squelette) {
260
-	if (!_ZCORE_EXCLURE_PATH
261
-		or !preg_match(',(' . _ZCORE_EXCLURE_PATH . ')/,', $squelette)
262
-	) {
263
-		return true;
264
-	}
260
+    if (!_ZCORE_EXCLURE_PATH
261
+        or !preg_match(',(' . _ZCORE_EXCLURE_PATH . ')/,', $squelette)
262
+    ) {
263
+        return true;
264
+    }
265 265
 
266
-	return false;
266
+    return false;
267 267
 }
268 268
 
269 269
 /**
@@ -281,14 +281,14 @@  discard block
 block discarded – undo
281 281
  * @return string
282 282
  */
283 283
 function z_trouver_bloc($prefix_path, $bloc, $fond, $ext) {
284
-	if (
285
-		(defined('_ZCORE_BLOC_PREFIX_SKEL') and $f = find_in_path("$prefix_path$bloc/$bloc.$fond.$ext") and z_fond_valide($f))
286
-		or ($f = find_in_path("$prefix_path$bloc/$fond.$ext") and z_fond_valide($f))
287
-	) {
288
-		return substr($f, 0, -strlen(".$ext"));
289
-	}
290
-
291
-	return "";
284
+    if (
285
+        (defined('_ZCORE_BLOC_PREFIX_SKEL') and $f = find_in_path("$prefix_path$bloc/$bloc.$fond.$ext") and z_fond_valide($f))
286
+        or ($f = find_in_path("$prefix_path$bloc/$fond.$ext") and z_fond_valide($f))
287
+    ) {
288
+        return substr($f, 0, -strlen(".$ext"));
289
+    }
290
+
291
+    return "";
292 292
 }
293 293
 
294 294
 /**
@@ -300,51 +300,51 @@  discard block
 block discarded – undo
300 300
  * @return bool
301 301
  */
302 302
 function z_echafaudable($type) {
303
-	static $pages = null;
304
-	static $echafaudable = array();
305
-	if (isset($echafaudable[$type])) {
306
-		return $echafaudable[$type];
307
-	}
308
-	if (preg_match(',[^\w],', $type)) {
309
-		return $echafaudable[$type] = false;
310
-	}
311
-
312
-	if (test_espace_prive()) {
313
-		if (!function_exists('trouver_objet_exec')) {
314
-			include_spip('inc/pipelines_ecrire');
315
-		}
316
-		if ($e = trouver_objet_exec($type)) {
317
-			return $echafaudable[$type] = array($e['table'], $e['table_objet_sql'], $e);
318
-		} else {
319
-			// peut etre c'est un exec=types qui liste tous les objets "type"
320
-			if (($t = objet_type($type, false)) !== $type
321
-				and $e = trouver_objet_exec($t)
322
-			) {
323
-				return $echafaudable[$type] = array($e['table'], $e['table_objet_sql'], $t);
324
-			}
325
-		}
326
-	} else {
327
-		if (is_null($pages)) {
328
-			$pages = array();
329
-			$liste = lister_tables_objets_sql();
330
-			foreach ($liste as $t => $d) {
331
-				if ($d['page']) {
332
-					$pages[$d['page']] = array($d['table_objet'], $t);
333
-				}
334
-			}
335
-		}
336
-		if (!isset($pages[$type])) {
337
-			return $echafaudable[$type] = false;
338
-		}
339
-		if (count($pages[$type]) == 2) {
340
-			$trouver_table = charger_fonction('trouver_table', 'base');
341
-			$pages[$type][] = $trouver_table(reset($pages[$type]));
342
-		}
343
-
344
-		return $echafaudable[$type] = $pages[$type];
345
-	}
346
-
347
-	return $echafaudable[$type] = false;
303
+    static $pages = null;
304
+    static $echafaudable = array();
305
+    if (isset($echafaudable[$type])) {
306
+        return $echafaudable[$type];
307
+    }
308
+    if (preg_match(',[^\w],', $type)) {
309
+        return $echafaudable[$type] = false;
310
+    }
311
+
312
+    if (test_espace_prive()) {
313
+        if (!function_exists('trouver_objet_exec')) {
314
+            include_spip('inc/pipelines_ecrire');
315
+        }
316
+        if ($e = trouver_objet_exec($type)) {
317
+            return $echafaudable[$type] = array($e['table'], $e['table_objet_sql'], $e);
318
+        } else {
319
+            // peut etre c'est un exec=types qui liste tous les objets "type"
320
+            if (($t = objet_type($type, false)) !== $type
321
+                and $e = trouver_objet_exec($t)
322
+            ) {
323
+                return $echafaudable[$type] = array($e['table'], $e['table_objet_sql'], $t);
324
+            }
325
+        }
326
+    } else {
327
+        if (is_null($pages)) {
328
+            $pages = array();
329
+            $liste = lister_tables_objets_sql();
330
+            foreach ($liste as $t => $d) {
331
+                if ($d['page']) {
332
+                    $pages[$d['page']] = array($d['table_objet'], $t);
333
+                }
334
+            }
335
+        }
336
+        if (!isset($pages[$type])) {
337
+            return $echafaudable[$type] = false;
338
+        }
339
+        if (count($pages[$type]) == 2) {
340
+            $trouver_table = charger_fonction('trouver_table', 'base');
341
+            $pages[$type][] = $trouver_table(reset($pages[$type]));
342
+        }
343
+
344
+        return $echafaudable[$type] = $pages[$type];
345
+    }
346
+
347
+    return $echafaudable[$type] = false;
348 348
 }
349 349
 
350 350
 
@@ -361,46 +361,46 @@  discard block
 block discarded – undo
361 361
  * @return string
362 362
  */
363 363
 function prive_echafauder_dist($exec, $table, $table_sql, $desc_exec, $ext) {
364
-	$scaffold = "";
365
-
366
-	// page objet ou objet_edit
367
-	if (is_array($desc_exec)) {
368
-		$type = $desc_exec['type'];
369
-		$primary = $desc_exec['id_table_objet'];
370
-
371
-		if ($desc_exec['edition'] === false) {
372
-			$fond = "objet";
373
-		} else {
374
-			$trouver_table = charger_fonction('trouver_table', 'base');
375
-			$desc = $trouver_table($table_sql);
376
-			if (isset($desc['field']['id_rubrique'])) {
377
-				$fond = 'objet_edit';
378
-			} else {
379
-				$fond = 'objet_edit.sans_rubrique';
380
-			}
381
-		}
382
-		$dir = z_blocs(test_espace_prive());
383
-		$dir = reset($dir);
384
-		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/" . $fond . ",objet=" . $type . ",id_objet=#" . strtoupper($primary) . ",env}>";
385
-	} // page objets
386
-	elseif ($type = $desc_exec and strpos($type, "/") === false) {
387
-		$dir = z_blocs(test_espace_prive());
388
-		$dir = reset($dir);
389
-		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/objets,objet=" . $type . ",env} />";
390
-	}
391
-	// morceau d'objet : on fournit le fond de sibstitution dans $desc_exec
392
-	// et objet et tire de $table
393
-	elseif ($fond = $desc_exec) {
394
-		$dir = md5(dirname($fond));
395
-		$scaffold = "<INCLURE{fond=$fond,objet=" . objet_type($table) . ",env} />";
396
-	}
397
-
398
-	$base_dir = sous_repertoire(_DIR_CACHE, "scaffold", false);
399
-	$base_dir = sous_repertoire($base_dir, $dir, false);
400
-	$f = $base_dir . "$exec";
401
-	ecrire_fichier("$f.$ext", $scaffold);
402
-
403
-	return $f;
364
+    $scaffold = "";
365
+
366
+    // page objet ou objet_edit
367
+    if (is_array($desc_exec)) {
368
+        $type = $desc_exec['type'];
369
+        $primary = $desc_exec['id_table_objet'];
370
+
371
+        if ($desc_exec['edition'] === false) {
372
+            $fond = "objet";
373
+        } else {
374
+            $trouver_table = charger_fonction('trouver_table', 'base');
375
+            $desc = $trouver_table($table_sql);
376
+            if (isset($desc['field']['id_rubrique'])) {
377
+                $fond = 'objet_edit';
378
+            } else {
379
+                $fond = 'objet_edit.sans_rubrique';
380
+            }
381
+        }
382
+        $dir = z_blocs(test_espace_prive());
383
+        $dir = reset($dir);
384
+        $scaffold = "<INCLURE{fond=prive/echafaudage/$dir/" . $fond . ",objet=" . $type . ",id_objet=#" . strtoupper($primary) . ",env}>";
385
+    } // page objets
386
+    elseif ($type = $desc_exec and strpos($type, "/") === false) {
387
+        $dir = z_blocs(test_espace_prive());
388
+        $dir = reset($dir);
389
+        $scaffold = "<INCLURE{fond=prive/echafaudage/$dir/objets,objet=" . $type . ",env} />";
390
+    }
391
+    // morceau d'objet : on fournit le fond de sibstitution dans $desc_exec
392
+    // et objet et tire de $table
393
+    elseif ($fond = $desc_exec) {
394
+        $dir = md5(dirname($fond));
395
+        $scaffold = "<INCLURE{fond=$fond,objet=" . objet_type($table) . ",env} />";
396
+    }
397
+
398
+    $base_dir = sous_repertoire(_DIR_CACHE, "scaffold", false);
399
+    $base_dir = sous_repertoire($base_dir, $dir, false);
400
+    $f = $base_dir . "$exec";
401
+    ecrire_fichier("$f.$ext", $scaffold);
402
+
403
+    return $f;
404 404
 }
405 405
 
406 406
 /**
@@ -409,16 +409,16 @@  discard block
 block discarded – undo
409 409
  * @return bool|string
410 410
  */
411 411
 function z_sanitize_var_zajax() {
412
-	$z_ajax = _request('var_zajax');
413
-	if (!$z_ajax) {
414
-		return false;
415
-	}
416
-	if (!$z_blocs = z_blocs(test_espace_prive())
417
-		or !in_array($z_ajax, $z_blocs)
418
-	) {
419
-		set_request('var_zajax'); // enlever cette demande incongrue
420
-		$z_ajax = false;
421
-	}
422
-
423
-	return $z_ajax;
412
+    $z_ajax = _request('var_zajax');
413
+    if (!$z_ajax) {
414
+        return false;
415
+    }
416
+    if (!$z_blocs = z_blocs(test_espace_prive())
417
+        or !in_array($z_ajax, $z_blocs)
418
+    ) {
419
+        set_request('var_zajax'); // enlever cette demande incongrue
420
+        $z_ajax = false;
421
+    }
422
+
423
+    return $z_ajax;
424 424
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 			$apl_constant = '_Z_AJAX_PARALLEL_LOAD';
54 54
 			$page = _SPIP_PAGE;
55 55
 			$echafauder = charger_fonction('echafauder', 'public', true);
56
-			define('_ZCORE_EXCLURE_PATH', '\bprive|\bsquelettes-dist' . (defined('_DIR_PLUGIN_DIST') ? '|\b' . rtrim(_DIR_PLUGIN_DIST,
56
+			define('_ZCORE_EXCLURE_PATH', '\bprive|\bsquelettes-dist'.(defined('_DIR_PLUGIN_DIST') ? '|\b'.rtrim(_DIR_PLUGIN_DIST,
57 57
 						'/') : ''));
58 58
 		}
59 59
 		$prepend = (defined('_Z_PREPEND_PATH') ? _Z_PREPEND_PATH : "");
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 			and in_array($dir, $z_blocs) // verifier deja qu'on est dans un bloc Z
75 75
 			and defined($apl_constant)
76 76
 			and in_array($dir, explode(',', constant($apl_constant))) // et dans un demande en APL
77
-			and $pipe = z_trouver_bloc($prefix_path . $prepend, $dir, 'z_apl', $ext) // et qui contient le squelette APL
77
+			and $pipe = z_trouver_bloc($prefix_path.$prepend, $dir, 'z_apl', $ext) // et qui contient le squelette APL
78 78
 		) {
79 79
 			$flux['data'] = $pipe;
80 80
 
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 			$echafauder = "";
88 88
 		}
89 89
 		if ($prepend) {
90
-			$squelette = substr(find_in_path($prefix_path . $prepend . "$fond.$ext"), 0, -strlen(".$ext"));
90
+			$squelette = substr(find_in_path($prefix_path.$prepend."$fond.$ext"), 0, -strlen(".$ext"));
91 91
 			if ($squelette) {
92 92
 				$flux['data'] = $squelette;
93 93
 			}
@@ -111,11 +111,11 @@  discard block
 block discarded – undo
111 111
 				// se brancher sur contenu/xx si il existe
112 112
 				// ou si c'est un objet spip, associe a une table, utiliser le fond homonyme
113 113
 				if (!isset($disponible[$fond])) {
114
-					$disponible[$fond] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $fond, $ext, $echafauder);
114
+					$disponible[$fond] = z_contenu_disponible($prefix_path.$prepend, $z_contenu, $fond, $ext, $echafauder);
115 115
 				}
116 116
 
117 117
 				if ($disponible[$fond]) {
118
-					$flux['data'] = substr(find_in_path($prefix_path . "page.$ext"), 0, -strlen(".$ext"));
118
+					$flux['data'] = substr(find_in_path($prefix_path."page.$ext"), 0, -strlen(".$ext"));
119 119
 				}
120 120
 			}
121 121
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 					$type = $flux['args']['contexte'][$page];
129 129
 				}
130 130
 				if (!isset($disponible[$type])) {
131
-					$disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
131
+					$disponible[$type] = z_contenu_disponible($prefix_path.$prepend, $z_contenu, $type, $ext, $echafauder);
132 132
 				}
133 133
 				if (is_string($disponible[$type])) {
134 134
 					$flux['data'] = $disponible[$type];
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 				) {
142 142
 					$flux['data'] = $echafauder($type, $is[0], $is[1], $is[2], $ext);
143 143
 				} else {
144
-					$flux['data'] = ($disponible['404'] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, '404', $ext,
144
+					$flux['data'] = ($disponible['404'] = z_contenu_disponible($prefix_path.$prepend, $z_contenu, '404', $ext,
145 145
 						$echafauder));
146 146
 				}
147 147
 			}
@@ -160,10 +160,10 @@  discard block
 block discarded – undo
160 160
 						$type = $flux['args']['contexte'][$page];
161 161
 					}
162 162
 					if ($type !== 'page' and !isset($disponible[$type])) {
163
-						$disponible[$type] = z_contenu_disponible($prefix_path . $prepend, $z_contenu, $type, $ext, $echafauder);
163
+						$disponible[$type] = z_contenu_disponible($prefix_path.$prepend, $z_contenu, $type, $ext, $echafauder);
164 164
 					}
165 165
 					if ($type == 'page' or $disponible[$type]) {
166
-						$flux['data'] = z_trouver_bloc($prefix_path . $prepend, $dir, 'dist', $ext);
166
+						$flux['data'] = z_trouver_bloc($prefix_path.$prepend, $dir, 'dist', $ext);
167 167
 					}
168 168
 				}
169 169
 			}
@@ -178,16 +178,16 @@  discard block
 block discarded – undo
178 178
 			if (isset($flux['args']['contexte']['type-page'])
179 179
 				and (
180 180
 					(isset($flux['args']['contexte']['composition'])
181
-						and file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page'] . "-" . $flux['args']['contexte']['composition']) . ".$ext"))
181
+						and file_exists(($f = $squelette."-".$flux['args']['contexte']['type-page']."-".$flux['args']['contexte']['composition']).".$ext"))
182 182
 					or
183
-					file_exists(($f = $squelette . "-" . $flux['args']['contexte']['type-page']) . ".$ext")
183
+					file_exists(($f = $squelette."-".$flux['args']['contexte']['type-page']).".$ext")
184 184
 				)
185 185
 			) {
186 186
 				$flux['data'] = $f;
187 187
 			}
188 188
 		} elseif ($fond == 'structure'
189 189
 			and z_sanitize_var_zajax()
190
-			and $f = find_in_path($prefix_path . $prepend . 'ajax' . ".$ext")
190
+			and $f = find_in_path($prefix_path.$prepend.'ajax'.".$ext")
191 191
 		) {
192 192
 			$flux['data'] = substr($f, 0, -strlen(".$ext"));
193 193
 		} // chercher le fond correspondant a la composition
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 			and $dir = explode('/', $dir)
198 198
 			and $dir = reset($dir)
199 199
 			and in_array($dir, $z_blocs)
200
-			and $f = find_in_path($prefix_path . $prepend . $fond . "-" . $flux['args']['contexte']['composition'] . ".$ext")
200
+			and $f = find_in_path($prefix_path.$prepend.$fond."-".$flux['args']['contexte']['composition'].".$ext")
201 201
 		) {
202 202
 			$flux['data'] = substr($f, 0, -strlen(".$ext"));
203 203
 		}
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
  **/
259 259
 function z_fond_valide($squelette) {
260 260
 	if (!_ZCORE_EXCLURE_PATH
261
-		or !preg_match(',(' . _ZCORE_EXCLURE_PATH . ')/,', $squelette)
261
+		or !preg_match(',('._ZCORE_EXCLURE_PATH.')/,', $squelette)
262 262
 	) {
263 263
 		return true;
264 264
 	}
@@ -381,23 +381,23 @@  discard block
 block discarded – undo
381 381
 		}
382 382
 		$dir = z_blocs(test_espace_prive());
383 383
 		$dir = reset($dir);
384
-		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/" . $fond . ",objet=" . $type . ",id_objet=#" . strtoupper($primary) . ",env}>";
384
+		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/".$fond.",objet=".$type.",id_objet=#".strtoupper($primary).",env}>";
385 385
 	} // page objets
386 386
 	elseif ($type = $desc_exec and strpos($type, "/") === false) {
387 387
 		$dir = z_blocs(test_espace_prive());
388 388
 		$dir = reset($dir);
389
-		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/objets,objet=" . $type . ",env} />";
389
+		$scaffold = "<INCLURE{fond=prive/echafaudage/$dir/objets,objet=".$type.",env} />";
390 390
 	}
391 391
 	// morceau d'objet : on fournit le fond de sibstitution dans $desc_exec
392 392
 	// et objet et tire de $table
393 393
 	elseif ($fond = $desc_exec) {
394 394
 		$dir = md5(dirname($fond));
395
-		$scaffold = "<INCLURE{fond=$fond,objet=" . objet_type($table) . ",env} />";
395
+		$scaffold = "<INCLURE{fond=$fond,objet=".objet_type($table).",env} />";
396 396
 	}
397 397
 
398 398
 	$base_dir = sous_repertoire(_DIR_CACHE, "scaffold", false);
399 399
 	$base_dir = sous_repertoire($base_dir, $dir, false);
400
-	$f = $base_dir . "$exec";
400
+	$f = $base_dir."$exec";
401 401
 	ecrire_fichier("$f.$ext", $scaffold);
402 402
 
403 403
 	return $f;
Please login to merge, or discard this patch.
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.