Completed
Push — master ( 7f6c2c...996e17 )
by cam
01:04
created
ecrire/xml/valider.php 1 patch
Indentation   +320 added lines, -320 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
 /**
@@ -23,322 +23,322 @@  discard block
 block discarded – undo
23 23
  **/
24 24
 class ValidateurXML {
25 25
 
26
-	public function validerElement($phraseur, $name, $attrs) {
27
-		if (!($p = isset($this->dtc->elements[$name]))) {
28
-			if ($p = strpos($name, ':')) {
29
-				$name = substr($name, $p + 1);
30
-				$p = isset($this->dtc->elements[$name]);
31
-			}
32
-			if (!$p) {
33
-				coordonnees_erreur($this, " <b>$name</b>&nbsp;: "
34
-					. _T('zxml_inconnu_balise'));
35
-
36
-				return;
37
-			}
38
-		}
39
-		// controler les filles illegitimes, ca suffit
40
-		$depth = $this->depth;
41
-		$ouvrant = $this->ouvrant;
42
-		#spip_log("trouve $name apres " . $ouvrant[$depth]);
43
-		if (isset($ouvrant[$depth])) {
44
-			if (preg_match('/^\s*(\w+)/', $ouvrant[$depth], $r)) {
45
-				$pere = $r[1];
46
-				#spip_log("pere $pere");
47
-				if (isset($this->dtc->elements[$pere])) {
48
-					$fils = $this->dtc->elements[$pere];
49
-					#spip_log("rejeton $name fils " . @join(',',$fils));
50
-					if (!($p = @in_array($name, $fils))) {
51
-						if ($p = strpos($name, ':')) {
52
-							$p = substr($name, $p + 1);
53
-							$p = @in_array($p, $fils);
54
-						}
55
-					}
56
-					if (!$p) {
57
-						$bons_peres = @join('</b>, <b>', $this->dtc->peres[$name]);
58
-						coordonnees_erreur($this, " <b>$name</b> "
59
-							. _T('zxml_non_fils')
60
-							. ' <b>'
61
-							. $pere
62
-							. '</b>'
63
-							. (!$bons_peres ? ''
64
-								: ('<p style="font-size: 80%"> ' . _T('zxml_mais_de') . ' <b>' . $bons_peres . '</b></p>')));
65
-					} elseif ($this->dtc->regles[$pere][0] == '/') {
66
-						$frat = substr($depth, 2);
67
-						if (!isset($this->fratrie[$frat])) {
68
-							$this->fratrie[$frat] = '';
69
-						}
70
-						$this->fratrie[$frat] .= "$name ";
71
-					}
72
-				}
73
-			}
74
-		}
75
-		// Init de la suite des balises a memoriser si regle difficile
76
-		if ($this->dtc->regles[$name] and $this->dtc->regles[$name][0] == '/') {
77
-			$this->fratrie[$depth] = '';
78
-		}
79
-		if (isset($this->dtc->attributs[$name])) {
80
-			foreach ($this->dtc->attributs[$name] as $n => $v) {
81
-				if (($v[1] == '#REQUIRED') and (!isset($attrs[$n]))) {
82
-					coordonnees_erreur($this, " <b>$n</b>"
83
-						. '&nbsp;:&nbsp;'
84
-						. _T('zxml_obligatoire_attribut')
85
-						. " <b>$name</b>");
86
-				}
87
-			}
88
-		}
89
-	}
90
-
91
-	public function validerAttribut($phraseur, $name, $val, $bal) {
92
-		// Si la balise est inconnue, eviter d'insister
93
-		if (!isset($this->dtc->attributs[$bal])) {
94
-			return;
95
-		}
96
-
97
-		$a = $this->dtc->attributs[$bal];
98
-		if (!isset($a[$name])) {
99
-			$bons = join(', ', array_keys($a));
100
-			if ($bons) {
101
-				$bons = " title=' " .
102
-					_T('zxml_connus_attributs') .
103
-					'&nbsp;: ' .
104
-					$bons .
105
-					"'";
106
-			}
107
-			$bons .= " style='font-weight: bold'";
108
-			coordonnees_erreur($this, " <b>$name</b> "
109
-				. _T('zxml_inconnu_attribut') . ' ' . _T('zxml_de')
110
-				. " <a$bons>$bal</a> ("
111
-				. _T('zxml_survoler')
112
-				. ')');
113
-		} else {
114
-			$type = $a[$name][0];
115
-			if (!preg_match('/^\w+$/', $type)) {
116
-				$this->valider_motif($phraseur, $name, $val, $bal, $type);
117
-			} else {
118
-				if (method_exists($this, $f = 'validerAttribut_' . $type)) {
119
-					$this->$f($phraseur, $name, $val, $bal);
120
-				}
121
-			}
122
-			#		else spip_log("$type type d'attribut inconnu");
123
-		}
124
-	}
125
-
126
-	public function validerAttribut_NMTOKEN($phraseur, $name, $val, $bal) {
127
-		$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKEN);
128
-	}
129
-
130
-	public function validerAttribut_NMTOKENS($phraseur, $name, $val, $bal) {
131
-		$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKENS);
132
-	}
133
-
134
-	public function validerAttribut_ID($phraseur, $name, $val, $bal) {
135
-		if (isset($this->ids[$val])) {
136
-			[$l, $c] = $this->ids[$val];
137
-			coordonnees_erreur($this, " <p><b>$val</b> "
138
-				. _T('zxml_valeur_attribut')
139
-				. " <b>$name</b> "
140
-				. _T('zxml_de')
141
-				. " <b>$bal</b> "
142
-				. _T('zxml_vu')
143
-				. " (L$l,C$c)");
144
-		} else {
145
-			$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_ID);
146
-			$this->ids[$val] = [xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
147
-		}
148
-	}
149
-
150
-	public function validerAttribut_IDREF($phraseur, $name, $val, $bal) {
151
-		$this->idrefs[] = [$val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
152
-	}
153
-
154
-	public function validerAttribut_IDREFS($phraseur, $name, $val, $bal) {
155
-		$this->idrefss[] = [$val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
156
-	}
157
-
158
-	public function valider_motif($phraseur, $name, $val, $bal, $motif) {
159
-		if (!preg_match($motif, $val)) {
160
-			coordonnees_erreur($this, "<b>$val</b> "
161
-				. _T('zxml_valeur_attribut')
162
-				. " <b>$name</b> "
163
-				. _T('zxml_de')
164
-				. " <b>$bal</b> "
165
-				. _T('zxml_non_conforme')
166
-				. '</p><p>'
167
-				. '<b>' . $motif . '</b>');
168
-		}
169
-	}
170
-
171
-	public function valider_idref($nom, $ligne, $col) {
172
-		if (!isset($this->ids[$nom])) {
173
-			$this->err[] = [" <p><b>$nom</b> " . _T('zxml_inconnu_id'), $ligne, $col];
174
-		}
175
-	}
176
-
177
-	public function valider_passe2() {
178
-		if (!$this->err) {
179
-			foreach ($this->idrefs as $idref) {
180
-				[$nom, $ligne, $col] = $idref;
181
-				$this->valider_idref($nom, $ligne, $col);
182
-			}
183
-			foreach ($this->idrefss as $idref) {
184
-				[$noms, $ligne, $col] = $idref;
185
-				foreach (preg_split('/\s+/', $noms) as $nom) {
186
-					$this->valider_idref($nom, $ligne, $col);
187
-				}
188
-			}
189
-		}
190
-	}
191
-
192
-	public function debutElement($phraseur, $name, $attrs) {
193
-		if ($this->dtc->elements) {
194
-			$this->validerElement($phraseur, $name, $attrs);
195
-		}
196
-
197
-		if ($f = $this->process['debut']) {
198
-			$f($this, $name, $attrs);
199
-		}
200
-		$depth = $this->depth;
201
-		$this->debuts[$depth] = strlen($this->res);
202
-		foreach ($attrs as $k => $v) {
203
-			$this->validerAttribut($phraseur, $k, $v, $name);
204
-		}
205
-	}
206
-
207
-	public function finElement($phraseur, $name) {
208
-		$depth = $this->depth;
209
-		$contenu = $this->contenu;
210
-
211
-		$n = strlen($this->res);
212
-		$c = strlen(trim($contenu[$depth]));
213
-		$k = $this->debuts[$depth];
214
-
215
-		$regle = $this->dtc->regles[$name] ?? false;
216
-		$vide = ($regle == 'EMPTY');
217
-		// controler que les balises devant etre vides le sont
218
-		if ($vide) {
219
-			if ($n <> ($k + $c)) {
220
-				coordonnees_erreur($this, " <p><b>$name</b> " . _T('zxml_nonvide_balise'));
221
-			}
222
-			// pour les regles PCDATA ou iteration de disjonction, tout est fait
223
-		} elseif ($regle and ($regle != '*')) {
224
-			if ($regle == '+') {
225
-				// iteration de disjonction non vide: 1 balise au -
226
-				if ($n == $k) {
227
-					coordonnees_erreur($this, "<p>\n<b>$name</b> "
228
-						. _T('zxml_vide_balise'));
229
-				}
230
-			} else {
231
-				$f = $this->fratrie[substr($depth, 2)] ?? null;
232
-				if (is_null($f) or !preg_match($regle, $f)) {
233
-					coordonnees_erreur(
234
-						$this,
235
-						" <p>\n<b>$name</b> "
236
-						. _T('zxml_succession_fils_incorrecte')
237
-						. '&nbsp;: <b>'
238
-						. $f
239
-						. '</b>'
240
-					);
241
-				}
242
-			}
243
-		}
244
-		if ($f = $this->process['fin']) {
245
-			$f($this, $name, $vide);
246
-		}
247
-	}
248
-
249
-	public function textElement($phraseur, $data) {
250
-		if (trim($data)) {
251
-			$d = $this->depth;
252
-			$d = $this->ouvrant[$d];
253
-			preg_match('/^\s*(\S+)/', $d, $m);
254
-			if (isset($this->dtc->pcdata[$m[1]]) and ($this->dtc->pcdata[$m[1]])) {
255
-				coordonnees_erreur($this, ' <p><b>' . $m[1] . '</b> '
256
-					. _T('zxml_nonvide_balise')); // message a affiner
257
-			}
258
-		}
259
-		if ($f = $this->process['text']) {
260
-			$f($this, $data);
261
-		}
262
-	}
263
-
264
-	public function piElement($phraseur, $target, $data) {
265
-		if ($f = $this->process['pi']) {
266
-			$f($this, $target, $data);
267
-		}
268
-	}
269
-
270
-	// Denonciation des entitees XML inconnues
271
-	// Pour contourner le bug de conception de SAX qui ne signale pas si elles
272
-	// sont dans un attribut, les  entites les plus frequentes ont ete
273
-	// transcodees au prealable  (sauf & < > " que SAX traite correctement).
274
-	// On ne les verra donc pas passer a cette etape, contrairement a ce que
275
-	// le source de la page laisse legitimement supposer.
276
-
277
-	public function defaultElement($phraseur, $data) {
278
-		if (
279
-			!preg_match('/^<!--/', $data)
280
-			and (preg_match_all('/&([^;]*)?/', $data, $r, PREG_SET_ORDER))
281
-		) {
282
-			foreach ($r as $m) {
283
-				[$t, $e] = $m;
284
-				if (!isset($this->dtc->entites[$e])) {
285
-					coordonnees_erreur($this, " <b>$e</b> "
286
-						. _T('zxml_inconnu_entite')
287
-						. ' ');
288
-				}
289
-			}
290
-		}
291
-		if (isset($this->process['default']) and ($f = $this->process['default'])) {
292
-			$f($this, $data);
293
-		}
294
-	}
295
-
296
-	public function phraserTout($phraseur, $data) {
297
-		xml_parsestring($this, $data);
298
-
299
-		if (!$this->dtc or preg_match(',^' . _MESSAGE_DOCTYPE . ',', $data)) {
300
-			$this->err[] = ['DOCTYPE ?', 0, 0];
301
-		} else {
302
-			$this->valider_passe2();
303
-		}
304
-	}
305
-
306
-	/**
307
-	 * Constructeur
308
-	 *
309
-	 * @param array $process ?
310
-	 **/
311
-	public function __construct($process = []) {
312
-		if (is_array($process)) {
313
-			$this->process = $process;
314
-		}
315
-	}
316
-
317
-	public $ids = [];
318
-	public $idrefs = [];
319
-	public $idrefss = [];
320
-	public $debuts = [];
321
-	public $fratrie = [];
322
-
323
-	public $dtc = null;
324
-	public $sax = null;
325
-	public $depth = '';
326
-	public $entete = '';
327
-	public $page = '';
328
-	public $res = '';
329
-	public array $err = [];
330
-	public array $contenu = [];
331
-	public array $versions = [];
332
-
333
-	public array $ouvrant = [];
334
-	public array $reperes = [];
335
-	public array $process = [
336
-		'debut' => 'xml_debutElement',
337
-		'fin' => 'xml_finElement',
338
-		'text' => 'xml_textElement',
339
-		'pi' => 'xml_piElement',
340
-		'default' => 'xml_defaultElement'
341
-	];
26
+    public function validerElement($phraseur, $name, $attrs) {
27
+        if (!($p = isset($this->dtc->elements[$name]))) {
28
+            if ($p = strpos($name, ':')) {
29
+                $name = substr($name, $p + 1);
30
+                $p = isset($this->dtc->elements[$name]);
31
+            }
32
+            if (!$p) {
33
+                coordonnees_erreur($this, " <b>$name</b>&nbsp;: "
34
+                    . _T('zxml_inconnu_balise'));
35
+
36
+                return;
37
+            }
38
+        }
39
+        // controler les filles illegitimes, ca suffit
40
+        $depth = $this->depth;
41
+        $ouvrant = $this->ouvrant;
42
+        #spip_log("trouve $name apres " . $ouvrant[$depth]);
43
+        if (isset($ouvrant[$depth])) {
44
+            if (preg_match('/^\s*(\w+)/', $ouvrant[$depth], $r)) {
45
+                $pere = $r[1];
46
+                #spip_log("pere $pere");
47
+                if (isset($this->dtc->elements[$pere])) {
48
+                    $fils = $this->dtc->elements[$pere];
49
+                    #spip_log("rejeton $name fils " . @join(',',$fils));
50
+                    if (!($p = @in_array($name, $fils))) {
51
+                        if ($p = strpos($name, ':')) {
52
+                            $p = substr($name, $p + 1);
53
+                            $p = @in_array($p, $fils);
54
+                        }
55
+                    }
56
+                    if (!$p) {
57
+                        $bons_peres = @join('</b>, <b>', $this->dtc->peres[$name]);
58
+                        coordonnees_erreur($this, " <b>$name</b> "
59
+                            . _T('zxml_non_fils')
60
+                            . ' <b>'
61
+                            . $pere
62
+                            . '</b>'
63
+                            . (!$bons_peres ? ''
64
+                                : ('<p style="font-size: 80%"> ' . _T('zxml_mais_de') . ' <b>' . $bons_peres . '</b></p>')));
65
+                    } elseif ($this->dtc->regles[$pere][0] == '/') {
66
+                        $frat = substr($depth, 2);
67
+                        if (!isset($this->fratrie[$frat])) {
68
+                            $this->fratrie[$frat] = '';
69
+                        }
70
+                        $this->fratrie[$frat] .= "$name ";
71
+                    }
72
+                }
73
+            }
74
+        }
75
+        // Init de la suite des balises a memoriser si regle difficile
76
+        if ($this->dtc->regles[$name] and $this->dtc->regles[$name][0] == '/') {
77
+            $this->fratrie[$depth] = '';
78
+        }
79
+        if (isset($this->dtc->attributs[$name])) {
80
+            foreach ($this->dtc->attributs[$name] as $n => $v) {
81
+                if (($v[1] == '#REQUIRED') and (!isset($attrs[$n]))) {
82
+                    coordonnees_erreur($this, " <b>$n</b>"
83
+                        . '&nbsp;:&nbsp;'
84
+                        . _T('zxml_obligatoire_attribut')
85
+                        . " <b>$name</b>");
86
+                }
87
+            }
88
+        }
89
+    }
90
+
91
+    public function validerAttribut($phraseur, $name, $val, $bal) {
92
+        // Si la balise est inconnue, eviter d'insister
93
+        if (!isset($this->dtc->attributs[$bal])) {
94
+            return;
95
+        }
96
+
97
+        $a = $this->dtc->attributs[$bal];
98
+        if (!isset($a[$name])) {
99
+            $bons = join(', ', array_keys($a));
100
+            if ($bons) {
101
+                $bons = " title=' " .
102
+                    _T('zxml_connus_attributs') .
103
+                    '&nbsp;: ' .
104
+                    $bons .
105
+                    "'";
106
+            }
107
+            $bons .= " style='font-weight: bold'";
108
+            coordonnees_erreur($this, " <b>$name</b> "
109
+                . _T('zxml_inconnu_attribut') . ' ' . _T('zxml_de')
110
+                . " <a$bons>$bal</a> ("
111
+                . _T('zxml_survoler')
112
+                . ')');
113
+        } else {
114
+            $type = $a[$name][0];
115
+            if (!preg_match('/^\w+$/', $type)) {
116
+                $this->valider_motif($phraseur, $name, $val, $bal, $type);
117
+            } else {
118
+                if (method_exists($this, $f = 'validerAttribut_' . $type)) {
119
+                    $this->$f($phraseur, $name, $val, $bal);
120
+                }
121
+            }
122
+            #		else spip_log("$type type d'attribut inconnu");
123
+        }
124
+    }
125
+
126
+    public function validerAttribut_NMTOKEN($phraseur, $name, $val, $bal) {
127
+        $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKEN);
128
+    }
129
+
130
+    public function validerAttribut_NMTOKENS($phraseur, $name, $val, $bal) {
131
+        $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKENS);
132
+    }
133
+
134
+    public function validerAttribut_ID($phraseur, $name, $val, $bal) {
135
+        if (isset($this->ids[$val])) {
136
+            [$l, $c] = $this->ids[$val];
137
+            coordonnees_erreur($this, " <p><b>$val</b> "
138
+                . _T('zxml_valeur_attribut')
139
+                . " <b>$name</b> "
140
+                . _T('zxml_de')
141
+                . " <b>$bal</b> "
142
+                . _T('zxml_vu')
143
+                . " (L$l,C$c)");
144
+        } else {
145
+            $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_ID);
146
+            $this->ids[$val] = [xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
147
+        }
148
+    }
149
+
150
+    public function validerAttribut_IDREF($phraseur, $name, $val, $bal) {
151
+        $this->idrefs[] = [$val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
152
+    }
153
+
154
+    public function validerAttribut_IDREFS($phraseur, $name, $val, $bal) {
155
+        $this->idrefss[] = [$val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur)];
156
+    }
157
+
158
+    public function valider_motif($phraseur, $name, $val, $bal, $motif) {
159
+        if (!preg_match($motif, $val)) {
160
+            coordonnees_erreur($this, "<b>$val</b> "
161
+                . _T('zxml_valeur_attribut')
162
+                . " <b>$name</b> "
163
+                . _T('zxml_de')
164
+                . " <b>$bal</b> "
165
+                . _T('zxml_non_conforme')
166
+                . '</p><p>'
167
+                . '<b>' . $motif . '</b>');
168
+        }
169
+    }
170
+
171
+    public function valider_idref($nom, $ligne, $col) {
172
+        if (!isset($this->ids[$nom])) {
173
+            $this->err[] = [" <p><b>$nom</b> " . _T('zxml_inconnu_id'), $ligne, $col];
174
+        }
175
+    }
176
+
177
+    public function valider_passe2() {
178
+        if (!$this->err) {
179
+            foreach ($this->idrefs as $idref) {
180
+                [$nom, $ligne, $col] = $idref;
181
+                $this->valider_idref($nom, $ligne, $col);
182
+            }
183
+            foreach ($this->idrefss as $idref) {
184
+                [$noms, $ligne, $col] = $idref;
185
+                foreach (preg_split('/\s+/', $noms) as $nom) {
186
+                    $this->valider_idref($nom, $ligne, $col);
187
+                }
188
+            }
189
+        }
190
+    }
191
+
192
+    public function debutElement($phraseur, $name, $attrs) {
193
+        if ($this->dtc->elements) {
194
+            $this->validerElement($phraseur, $name, $attrs);
195
+        }
196
+
197
+        if ($f = $this->process['debut']) {
198
+            $f($this, $name, $attrs);
199
+        }
200
+        $depth = $this->depth;
201
+        $this->debuts[$depth] = strlen($this->res);
202
+        foreach ($attrs as $k => $v) {
203
+            $this->validerAttribut($phraseur, $k, $v, $name);
204
+        }
205
+    }
206
+
207
+    public function finElement($phraseur, $name) {
208
+        $depth = $this->depth;
209
+        $contenu = $this->contenu;
210
+
211
+        $n = strlen($this->res);
212
+        $c = strlen(trim($contenu[$depth]));
213
+        $k = $this->debuts[$depth];
214
+
215
+        $regle = $this->dtc->regles[$name] ?? false;
216
+        $vide = ($regle == 'EMPTY');
217
+        // controler que les balises devant etre vides le sont
218
+        if ($vide) {
219
+            if ($n <> ($k + $c)) {
220
+                coordonnees_erreur($this, " <p><b>$name</b> " . _T('zxml_nonvide_balise'));
221
+            }
222
+            // pour les regles PCDATA ou iteration de disjonction, tout est fait
223
+        } elseif ($regle and ($regle != '*')) {
224
+            if ($regle == '+') {
225
+                // iteration de disjonction non vide: 1 balise au -
226
+                if ($n == $k) {
227
+                    coordonnees_erreur($this, "<p>\n<b>$name</b> "
228
+                        . _T('zxml_vide_balise'));
229
+                }
230
+            } else {
231
+                $f = $this->fratrie[substr($depth, 2)] ?? null;
232
+                if (is_null($f) or !preg_match($regle, $f)) {
233
+                    coordonnees_erreur(
234
+                        $this,
235
+                        " <p>\n<b>$name</b> "
236
+                        . _T('zxml_succession_fils_incorrecte')
237
+                        . '&nbsp;: <b>'
238
+                        . $f
239
+                        . '</b>'
240
+                    );
241
+                }
242
+            }
243
+        }
244
+        if ($f = $this->process['fin']) {
245
+            $f($this, $name, $vide);
246
+        }
247
+    }
248
+
249
+    public function textElement($phraseur, $data) {
250
+        if (trim($data)) {
251
+            $d = $this->depth;
252
+            $d = $this->ouvrant[$d];
253
+            preg_match('/^\s*(\S+)/', $d, $m);
254
+            if (isset($this->dtc->pcdata[$m[1]]) and ($this->dtc->pcdata[$m[1]])) {
255
+                coordonnees_erreur($this, ' <p><b>' . $m[1] . '</b> '
256
+                    . _T('zxml_nonvide_balise')); // message a affiner
257
+            }
258
+        }
259
+        if ($f = $this->process['text']) {
260
+            $f($this, $data);
261
+        }
262
+    }
263
+
264
+    public function piElement($phraseur, $target, $data) {
265
+        if ($f = $this->process['pi']) {
266
+            $f($this, $target, $data);
267
+        }
268
+    }
269
+
270
+    // Denonciation des entitees XML inconnues
271
+    // Pour contourner le bug de conception de SAX qui ne signale pas si elles
272
+    // sont dans un attribut, les  entites les plus frequentes ont ete
273
+    // transcodees au prealable  (sauf & < > " que SAX traite correctement).
274
+    // On ne les verra donc pas passer a cette etape, contrairement a ce que
275
+    // le source de la page laisse legitimement supposer.
276
+
277
+    public function defaultElement($phraseur, $data) {
278
+        if (
279
+            !preg_match('/^<!--/', $data)
280
+            and (preg_match_all('/&([^;]*)?/', $data, $r, PREG_SET_ORDER))
281
+        ) {
282
+            foreach ($r as $m) {
283
+                [$t, $e] = $m;
284
+                if (!isset($this->dtc->entites[$e])) {
285
+                    coordonnees_erreur($this, " <b>$e</b> "
286
+                        . _T('zxml_inconnu_entite')
287
+                        . ' ');
288
+                }
289
+            }
290
+        }
291
+        if (isset($this->process['default']) and ($f = $this->process['default'])) {
292
+            $f($this, $data);
293
+        }
294
+    }
295
+
296
+    public function phraserTout($phraseur, $data) {
297
+        xml_parsestring($this, $data);
298
+
299
+        if (!$this->dtc or preg_match(',^' . _MESSAGE_DOCTYPE . ',', $data)) {
300
+            $this->err[] = ['DOCTYPE ?', 0, 0];
301
+        } else {
302
+            $this->valider_passe2();
303
+        }
304
+    }
305
+
306
+    /**
307
+     * Constructeur
308
+     *
309
+     * @param array $process ?
310
+     **/
311
+    public function __construct($process = []) {
312
+        if (is_array($process)) {
313
+            $this->process = $process;
314
+        }
315
+    }
316
+
317
+    public $ids = [];
318
+    public $idrefs = [];
319
+    public $idrefss = [];
320
+    public $debuts = [];
321
+    public $fratrie = [];
322
+
323
+    public $dtc = null;
324
+    public $sax = null;
325
+    public $depth = '';
326
+    public $entete = '';
327
+    public $page = '';
328
+    public $res = '';
329
+    public array $err = [];
330
+    public array $contenu = [];
331
+    public array $versions = [];
332
+
333
+    public array $ouvrant = [];
334
+    public array $reperes = [];
335
+    public array $process = [
336
+        'debut' => 'xml_debutElement',
337
+        'fin' => 'xml_finElement',
338
+        'text' => 'xml_textElement',
339
+        'pi' => 'xml_piElement',
340
+        'default' => 'xml_defaultElement'
341
+    ];
342 342
 }
343 343
 
344 344
 
@@ -348,8 +348,8 @@  discard block
 block discarded – undo
348 348
  *
349 349
  **/
350 350
 function xml_valider_dist($page, $apply = false, $process = false, $doctype = '', $charset = null) {
351
-	$f = new ValidateurXML($process);
352
-	$sax = charger_fonction('sax', 'xml');
351
+    $f = new ValidateurXML($process);
352
+    $sax = charger_fonction('sax', 'xml');
353 353
 
354
-	return $sax($page, $apply, $f, $doctype, $charset);
354
+    return $sax($page, $apply, $f, $doctype, $charset);
355 355
 }
Please login to merge, or discard this patch.
ecrire/base/objets.php 2 patches
Indentation   +1257 added lines, -1257 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
 /**
@@ -32,11 +32,11 @@  discard block
 block discarded – undo
32 32
  * @return void
33 33
  **/
34 34
 function array_set_merge(&$table, $index, $valeur) {
35
-	if (!isset($table[$index])) {
36
-		$table[$index] = $valeur;
37
-	} else {
38
-		$table[$index] = array_merge($table[$index], $valeur);
39
-	}
35
+    if (!isset($table[$index])) {
36
+        $table[$index] = $valeur;
37
+    } else {
38
+        $table[$index] = array_merge($table[$index], $valeur);
39
+    }
40 40
 }
41 41
 
42 42
 /**
@@ -55,441 +55,441 @@  discard block
 block discarded – undo
55 55
  *   - string (interne) si table '::md5' retourne un hash
56 56
  */
57 57
 function lister_tables_objets_sql(?string $table_sql = null, $desc = []) {
58
-	static $deja_la = false;
59
-	static $infos_tables = null;
60
-	static $md5 = null;
61
-	static $plugin_hash = null;
62
-
63
-	// plugins hash connu ? non si _CACHE_PLUGINS_OPT est pas encore chargé.
64
-	$_PLUGINS_HASH = defined('_PLUGINS_HASH') ? _PLUGINS_HASH : '!_CACHE_PLUGINS_OPT';
65
-
66
-	// prealablement recuperer les tables_principales
67
-	if (is_null($infos_tables) or $plugin_hash !== $_PLUGINS_HASH) {
68
-		// pas de reentrance (cas base/serial)
69
-		if ($deja_la) {
70
-			spip_log('Re-entrance anormale sur lister_tables_objets_sql : '
71
-				. var_export(debug_backtrace(), true), _LOG_CRITIQUE);
72
-
73
-			return ($table_sql === '::md5' ? $md5 : []);
74
-		}
75
-		$deja_la = true;
76
-		$plugin_hash = $_PLUGINS_HASH; // avant de lancer les pipelines
77
-
78
-		// recuperer les declarations explicites ancienne mode
79
-		// qui servent a completer declarer_tables_objets_sql
80
-		base_serial($GLOBALS['tables_principales']);
81
-		base_auxiliaires($GLOBALS['tables_auxiliaires']);
82
-		$infos_tables = [
83
-			'spip_articles' => [
84
-				'page' => 'article',
85
-				'texte_retour' => 'icone_retour_article',
86
-				'texte_modifier' => 'icone_modifier_article',
87
-				'texte_creer' => 'icone_ecrire_article',
88
-				'texte_objets' => 'public:articles',
89
-				'texte_objet' => 'public:article',
90
-				'texte_signale_edition' => 'texte_travail_article',
91
-				'info_aucun_objet' => 'info_aucun_article',
92
-				'info_1_objet' => 'info_1_article',
93
-				'info_nb_objets' => 'info_nb_articles',
94
-				'texte_logo_objet' => 'logo_article',
95
-				'texte_langue_objet' => 'titre_langue_article',
96
-				'texte_definir_comme_traduction_objet' => 'trad_lier',
97
-				'titre' => 'titre, lang',
98
-				'date' => 'date',
99
-				'principale' => 'oui',
100
-				'introduction_longueur' => '500',
101
-				'champs_editables' => [
102
-					'surtitre',
103
-					'titre',
104
-					'soustitre',
105
-					'descriptif',
106
-					'nom_site',
107
-					'url_site',
108
-					'chapo',
109
-					'texte',
110
-					'ps',
111
-					'virtuel'
112
-				],
113
-				'champs_versionnes' => [
114
-					'id_rubrique',
115
-					'surtitre',
116
-					'titre',
117
-					'soustitre',
118
-					'jointure_auteurs',
119
-					'descriptif',
120
-					'nom_site',
121
-					'url_site',
122
-					'chapo',
123
-					'texte',
124
-					'ps'
125
-				],
126
-				'field' => [
127
-					'id_article' => 'bigint(21) NOT NULL',
128
-					'surtitre' => "text DEFAULT '' NOT NULL",
129
-					'titre' => "text DEFAULT '' NOT NULL",
130
-					'soustitre' => "text DEFAULT '' NOT NULL",
131
-					'id_rubrique' => "bigint(21) DEFAULT '0' NOT NULL",
132
-					'descriptif' => "text DEFAULT '' NOT NULL",
133
-					'chapo' => "mediumtext DEFAULT '' NOT NULL",
134
-					'texte' => "longtext DEFAULT '' NOT NULL",
135
-					'ps' => "mediumtext DEFAULT '' NOT NULL",
136
-					'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
137
-					'statut' => "varchar(10) DEFAULT '0' NOT NULL",
138
-					'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
139
-					'maj' => 'TIMESTAMP',
140
-					'export' => "VARCHAR(10) DEFAULT 'oui'",
141
-					'date_redac' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
142
-					'visites' => "integer DEFAULT '0' NOT NULL",
143
-					'referers' => "integer DEFAULT '0' NOT NULL",
144
-					'popularite' => "DOUBLE DEFAULT '0' NOT NULL",
145
-					'accepter_forum' => "CHAR(3) DEFAULT '' NOT NULL",
146
-					'date_modif' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
147
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
148
-					'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
149
-					'id_trad' => "bigint(21) DEFAULT '0' NOT NULL",
150
-					'nom_site' => "tinytext DEFAULT '' NOT NULL",
151
-					'url_site' => "text DEFAULT '' NOT NULL",
152
-					'virtuel' => "text DEFAULT '' NOT NULL",
153
-				],
154
-				'key' => [
155
-					'PRIMARY KEY' => 'id_article',
156
-					'KEY id_rubrique' => 'id_rubrique',
157
-					'KEY id_secteur' => 'id_secteur',
158
-					'KEY id_trad' => 'id_trad',
159
-					'KEY lang' => 'lang',
160
-					'KEY statut' => 'statut, date',
161
-				],
162
-				'join' => [
163
-					'id_article' => 'id_article',
164
-					'id_rubrique' => 'id_rubrique'
165
-				],
166
-				'parent' => [
167
-					['type' => 'rubrique', 'champ' => 'id_rubrique']
168
-				],
169
-				'rechercher_champs' => [
170
-					'surtitre' => 5,
171
-					'titre' => 8,
172
-					'soustitre' => 5,
173
-					'chapo' => 3,
174
-					'texte' => 1,
175
-					'ps' => 1,
176
-					'nom_site' => 1,
177
-					'url_site' => 1,
178
-					'descriptif' => 4
179
-				],
180
-				'rechercher_jointures' => [
181
-					'auteur' => ['nom' => 10],
182
-				],
183
-				'statut' => [
184
-					[
185
-						'champ' => 'statut',
186
-						'publie' => 'publie',
187
-						'previsu' => 'publie,prop,prepa/auteur',
188
-						'post_date' => 'date',
189
-						'exception' => ['statut', 'tout']
190
-					]
191
-				],
192
-				'statut_titres' => [
193
-					'prepa' => 'info_article_redaction',
194
-					'prop' => 'info_article_propose',
195
-					'publie' => 'info_article_publie',
196
-					'refuse' => 'info_article_refuse',
197
-					'poubelle' => 'info_article_supprime'
198
-				],
199
-				'statut_textes_instituer' => [
200
-					'prepa' => 'texte_statut_en_cours_redaction',
201
-					'prop' => 'texte_statut_propose_evaluation',
202
-					'publie' => 'texte_statut_publie',
203
-					'refuse' => 'texte_statut_refuse',
204
-					'poubelle' => 'texte_statut_poubelle',
205
-				],
206
-				'texte_changer_statut' => 'texte_article_statut',
207
-				'aide_changer_statut' => 'artstatut',
208
-				'tables_jointures' => [
209
-					'profondeur' => 'rubriques',
210
-					#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
211
-				],
212
-			],
213
-			'spip_auteurs' => [
214
-				'page' => 'auteur',
215
-				'texte_retour' => 'icone_retour',
216
-				'texte_ajouter' => 'titre_ajouter_un_auteur',
217
-				'texte_modifier' => 'admin_modifier_auteur',
218
-				'texte_objets' => 'icone_auteurs',
219
-				'texte_objet' => 'public:auteur',
220
-				'info_aucun_objet' => 'info_aucun_auteur',
221
-				'info_1_objet' => 'info_1_auteur',
222
-				'info_nb_objets' => 'info_nb_auteurs',
223
-				'texte_logo_objet' => 'logo_auteur',
224
-				'texte_creer_associer' => 'creer_et_associer_un_auteur',
225
-				'titre' => "nom AS titre, '' AS lang",
226
-				'date' => 'date',
227
-				'principale' => 'oui',
228
-				'champs_editables' => ['nom', 'email', 'bio', 'nom_site', 'url_site', 'imessage', 'pgp'],
229
-				'champs_versionnes' => ['nom', 'bio', 'email', 'nom_site', 'url_site', 'login'],
230
-				'field' => [
231
-					'id_auteur' => 'bigint(21) NOT NULL',
232
-					'nom' => "text DEFAULT '' NOT NULL",
233
-					'bio' => "text DEFAULT '' NOT NULL",
234
-					'email' => "tinytext DEFAULT '' NOT NULL",
235
-					'nom_site' => "tinytext DEFAULT '' NOT NULL",
236
-					'url_site' => "text DEFAULT '' NOT NULL",
237
-					'login' => 'VARCHAR(255) BINARY',
238
-					'pass' => "tinytext DEFAULT '' NOT NULL",
239
-					'low_sec' => "tinytext DEFAULT '' NOT NULL",
240
-					'statut' => "varchar(255)  DEFAULT '0' NOT NULL",
241
-					'webmestre' => "varchar(3)  DEFAULT 'non' NOT NULL",
242
-					'maj' => 'TIMESTAMP',
243
-					'pgp' => "TEXT DEFAULT '' NOT NULL",
244
-					'htpass' => "tinytext DEFAULT '' NOT NULL",
245
-					'en_ligne' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
246
-					'alea_actuel' => 'tinytext',
247
-					'alea_futur' => 'tinytext',
248
-					'prefs' => 'text',
249
-					'cookie_oubli' => 'tinytext',
250
-					'source' => "VARCHAR(10) DEFAULT 'spip' NOT NULL",
251
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
252
-					'imessage' => "VARCHAR(3) DEFAULT '' NOT NULL",
253
-					'backup_cles' => "mediumtext DEFAULT '' NOT NULL",
254
-				],
255
-				'key' => [
256
-					'PRIMARY KEY' => 'id_auteur',
257
-					'KEY login' => 'login',
258
-					'KEY statut' => 'statut',
259
-					'KEY en_ligne' => 'en_ligne',
260
-				],
261
-				'join' => [
262
-					'id_auteur' => 'id_auteur',
263
-					'login' => 'login'
264
-				],
265
-				'rechercher_champs' => [
266
-					'nom' => 5,
267
-					'bio' => 1,
268
-					'email' => 1,
269
-					'nom_site' => 1,
270
-					'url_site' => 1,
271
-					'login' => 1
272
-				],
273
-				// 2 conditions pour les auteurs : statut!=poubelle,
274
-				// et avoir des articles publies
275
-				'statut' => [
276
-					[
277
-						'champ' => 'statut',
278
-						'publie' => '!5poubelle',
279
-						'previsu' => '!5poubelle',
280
-						'exception' => 'statut'
281
-					],
282
-					[
283
-						'champ' => [
284
-							['spip_auteurs_liens', 'id_auteur'],
285
-							[
286
-								'spip_articles',
287
-								['id_objet', 'id_article', 'objet', 'article']
288
-							],
289
-							'statut'
290
-						],
291
-						'publie' => 'publie',
292
-						'previsu' => '!',
293
-						'post_date' => 'date',
294
-						'exception' => ['statut', 'lien', 'tout']
295
-					],
296
-				],
297
-				'statut_images' => [
298
-					'auteur-6forum-16.png',
299
-					'0minirezo' => 'auteur-0minirezo-16.png',
300
-					'1comite' => 'auteur-1comite-16.png',
301
-					'6forum' => 'auteur-6forum-16.png',
302
-					'5poubelle' => 'auteur-5poubelle-16.png',
303
-					'nouveau' => ''
304
-				],
305
-				'statut_titres' => [
306
-					'titre_image_visiteur',
307
-					'0minirezo' => 'titre_image_administrateur',
308
-					'1comite' => 'titre_image_redacteur_02',
309
-					'6forum' => 'titre_image_visiteur',
310
-					'5poubelle' => 'titre_image_auteur_supprime',
311
-				],
312
-				'tables_jointures' => [#'auteurs_liens' // declaration generique plus bas
313
-				],
314
-			],
315
-			'spip_rubriques' => [
316
-				'page' => 'rubrique',
317
-				'url_voir' => 'rubrique',
318
-				'url_edit' => 'rubrique_edit',
319
-				'texte_retour' => 'icone_retour',
320
-				'texte_objets' => 'public:rubriques',
321
-				'texte_objet' => 'public:rubrique',
322
-				'texte_modifier' => 'icone_modifier_rubrique',
323
-				'texte_creer' => 'icone_creer_rubrique',
324
-				'texte_ajouter' => 'titre_ajouter_une_rubrique',
325
-				'texte_creer_associer' => 'creer_et_associer_une_rubrique',
326
-				'info_aucun_objet' => 'info_aucun_rubrique',
327
-				'info_1_objet' => 'info_1_rubrique',
328
-				'info_nb_objets' => 'info_nb_rubriques',
329
-				'texte_logo_objet' => 'logo_rubrique',
330
-				'texte_langue_objet' => 'titre_langue_rubrique',
331
-				'texte_definir_comme_traduction_objet' => 'texte_definir_comme_traduction_rubrique',
332
-				'titre' => 'titre, lang',
333
-				'date' => 'date',
334
-				'principale' => 'oui',
335
-				'introduction_longueur' => '600',
336
-				'champs_editables' => ['titre', 'texte', 'descriptif', 'extra'],
337
-				'champs_versionnes' => ['titre', 'descriptif', 'texte'],
338
-				'field' => [
339
-					'id_rubrique' => 'bigint(21) NOT NULL',
340
-					'id_parent' => "bigint(21) DEFAULT '0' NOT NULL",
341
-					'titre' => "text DEFAULT '' NOT NULL",
342
-					'descriptif' => "text DEFAULT '' NOT NULL",
343
-					'texte' => "longtext DEFAULT '' NOT NULL",
344
-					'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
345
-					'maj' => 'TIMESTAMP',
346
-					'statut' => "varchar(10) DEFAULT '0' NOT NULL",
347
-					'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
348
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
349
-					'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
350
-					'statut_tmp' => "varchar(10) DEFAULT '0' NOT NULL",
351
-					'date_tmp' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
352
-					'profondeur' => "smallint(5) DEFAULT '0' NOT NULL"
353
-				],
354
-				'key' => [
355
-					'PRIMARY KEY' => 'id_rubrique',
356
-					'KEY lang' => 'lang',
357
-					'KEY id_parent' => 'id_parent',
358
-				],
359
-				'parent' => [
360
-					['type' => 'rubrique', 'champ' => 'id_parent']
361
-				],
362
-				'rechercher_champs' => [
363
-					'titre' => 8,
364
-					'descriptif' => 5,
365
-					'texte' => 1
366
-				],
367
-				'statut' => [
368
-					[
369
-						'champ' => 'statut',
370
-						'publie' => 'publie',
371
-						'previsu' => '!',
372
-						'exception' => ['statut', 'tout']
373
-					],
374
-				],
375
-				'tables_jointures' => [#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
376
-				],
377
-			],
378
-			// toutes les tables ont le droit a une jointure sur les auteurs
379
-			['tables_jointures' => ['id_auteur' => 'auteurs_liens']]
380
-		];
381
-
382
-		// avant d'appeller les pipeline qui peuvent generer une reentrance a l'install
383
-		// initialiser la signature
384
-		$md5 = md5(serialize($infos_tables));
385
-
386
-		$GLOBALS['tables_principales'] = pipeline('declarer_tables_principales', $GLOBALS['tables_principales']);
387
-		$GLOBALS['tables_auxiliaires'] = pipeline('declarer_tables_auxiliaires', $GLOBALS['tables_auxiliaires']);
388
-		$infos_tables = pipeline('declarer_tables_objets_sql', $infos_tables);
389
-
390
-		// completer les informations manquantes ou implicites
391
-		$all = [];
392
-		foreach (array_keys($infos_tables) as $t) {
393
-			// les cles numeriques servent a declarer
394
-			// les proprietes applicables a tous les objets
395
-			// on les mets de cote
396
-			if (is_numeric($t)) {
397
-				$all = array_merge_recursive($all, $infos_tables[$t]);
398
-				unset($infos_tables[$t]);
399
-			} else {
400
-				$infos_tables[$t] = renseigner_table_objet_sql($t, $infos_tables[$t]);
401
-			}
402
-		}
403
-
404
-		// repercuter les proprietes generales communes a tous les objets
405
-		foreach (array_keys($infos_tables) as $t) {
406
-			foreach ($all as $i => $v) {
407
-				if (in_array($i, ['tables_jointures', 'champs_versionnes'])) {
408
-					$add = $all[$i];
409
-					// eviter les doublons de declaration de table jointure (ex des mots sur auteurs)
410
-					// pour les declarations generiques avec cles numeriques
411
-					if ($i == 'tables_jointures' and isset($infos_tables[$t][$i]) and is_countable($infos_tables[$t][$i]) ? count($infos_tables[$t][$i]) : 0) {
412
-						$doublons = array_intersect($infos_tables[$t][$i], $add);
413
-						foreach ($doublons as $d) {
414
-							if (
415
-								is_numeric(array_search($d, $infos_tables[$t][$i]))
416
-								and is_numeric($k = array_search($d, $add))
417
-							) {
418
-								unset($add[$k]);
419
-							}
420
-						}
421
-					}
422
-					$infos_tables[$t][$i] = array_merge($infos_tables[$t][$i] ?? [], $add);
423
-				} else {
424
-					$infos_tables[$t][$i] = array_merge_recursive(
425
-						$infos_tables[$t][$i] ?? [],
426
-						$all[$i]
427
-					);
428
-				}
429
-			}
430
-		}
431
-
432
-		// completer les tables principales et auxiliaires
433
-		// avec celles declarees uniquement dans declarer_table_objets_sql
434
-		// pour assurer la compat en transition
435
-		foreach ($infos_tables as $table => $infos) {
436
-			$principale_ou_auxiliaire = ($infos['principale'] ? 'tables_principales' : 'tables_auxiliaires');
437
-			// memoriser des champs eventuels declares par des plugins dans le pipeline tables_xxx
438
-			// qui a ete appelle avant
439
-			$mem = ($GLOBALS[$principale_ou_auxiliaire][$table] ?? []);
440
-			// l'ajouter au tableau
441
-			$GLOBALS[$principale_ou_auxiliaire][$table] = [];
442
-			if (isset($infos['field']) and isset($infos['key'])) {
443
-				foreach (['field', 'key', 'join'] as $k) {
444
-					if (isset($infos_tables[$table][$k])) {
445
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = &$infos_tables[$table][$k];
446
-					}
447
-				}
448
-			} else {
449
-				// ici on ne renvoie que les declarations, donc RIEN
450
-				// pour avoir la vrai description en base, il faut passer par trouver_table
451
-				$GLOBALS[$principale_ou_auxiliaire][$table] = [];
452
-			}
453
-			if (is_countable($mem) ? count($mem) : 0) {
454
-				foreach (array_keys($mem) as $k) {
455
-					if (isset($GLOBALS[$principale_ou_auxiliaire][$table][$k])) {
456
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = array_merge(
457
-							$GLOBALS[$principale_ou_auxiliaire][$table][$k],
458
-							$mem[$k]
459
-						);
460
-					} else {
461
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = $mem[$k];
462
-					}
463
-				}
464
-			}
465
-		}
466
-
467
-		// recuperer les interfaces (table_titre, table_date)
468
-		// on ne le fait que dans un second temps pour que table_objet soit fonctionnel
469
-		// dans le pipeline de declarer_tables_interfaces
470
-		include_spip('public/interfaces');
471
-		foreach (array_keys($infos_tables) as $t) {
472
-			$infos_tables[$t] = renseigner_table_objet_interfaces($t, $infos_tables[$t]);
473
-		}
474
-
475
-		$deja_la = false;
476
-		// signature
477
-		$md5 = md5(serialize($infos_tables));
478
-	}
479
-	if ($table_sql === '::md5') {
480
-		return $md5;
481
-	}
482
-	if ($table_sql and !isset($infos_tables[$table_sql])) {
483
-		#$desc = renseigner_table_objet_sql($table_sql,$desc);
484
-		$desc = renseigner_table_objet_interfaces($table_sql, $desc);
485
-
486
-		return $desc;
487
-	}
488
-	if ($table_sql) {
489
-		return $infos_tables[$table_sql] ?? [];
490
-	}
491
-
492
-	return $infos_tables;
58
+    static $deja_la = false;
59
+    static $infos_tables = null;
60
+    static $md5 = null;
61
+    static $plugin_hash = null;
62
+
63
+    // plugins hash connu ? non si _CACHE_PLUGINS_OPT est pas encore chargé.
64
+    $_PLUGINS_HASH = defined('_PLUGINS_HASH') ? _PLUGINS_HASH : '!_CACHE_PLUGINS_OPT';
65
+
66
+    // prealablement recuperer les tables_principales
67
+    if (is_null($infos_tables) or $plugin_hash !== $_PLUGINS_HASH) {
68
+        // pas de reentrance (cas base/serial)
69
+        if ($deja_la) {
70
+            spip_log('Re-entrance anormale sur lister_tables_objets_sql : '
71
+                . var_export(debug_backtrace(), true), _LOG_CRITIQUE);
72
+
73
+            return ($table_sql === '::md5' ? $md5 : []);
74
+        }
75
+        $deja_la = true;
76
+        $plugin_hash = $_PLUGINS_HASH; // avant de lancer les pipelines
77
+
78
+        // recuperer les declarations explicites ancienne mode
79
+        // qui servent a completer declarer_tables_objets_sql
80
+        base_serial($GLOBALS['tables_principales']);
81
+        base_auxiliaires($GLOBALS['tables_auxiliaires']);
82
+        $infos_tables = [
83
+            'spip_articles' => [
84
+                'page' => 'article',
85
+                'texte_retour' => 'icone_retour_article',
86
+                'texte_modifier' => 'icone_modifier_article',
87
+                'texte_creer' => 'icone_ecrire_article',
88
+                'texte_objets' => 'public:articles',
89
+                'texte_objet' => 'public:article',
90
+                'texte_signale_edition' => 'texte_travail_article',
91
+                'info_aucun_objet' => 'info_aucun_article',
92
+                'info_1_objet' => 'info_1_article',
93
+                'info_nb_objets' => 'info_nb_articles',
94
+                'texte_logo_objet' => 'logo_article',
95
+                'texte_langue_objet' => 'titre_langue_article',
96
+                'texte_definir_comme_traduction_objet' => 'trad_lier',
97
+                'titre' => 'titre, lang',
98
+                'date' => 'date',
99
+                'principale' => 'oui',
100
+                'introduction_longueur' => '500',
101
+                'champs_editables' => [
102
+                    'surtitre',
103
+                    'titre',
104
+                    'soustitre',
105
+                    'descriptif',
106
+                    'nom_site',
107
+                    'url_site',
108
+                    'chapo',
109
+                    'texte',
110
+                    'ps',
111
+                    'virtuel'
112
+                ],
113
+                'champs_versionnes' => [
114
+                    'id_rubrique',
115
+                    'surtitre',
116
+                    'titre',
117
+                    'soustitre',
118
+                    'jointure_auteurs',
119
+                    'descriptif',
120
+                    'nom_site',
121
+                    'url_site',
122
+                    'chapo',
123
+                    'texte',
124
+                    'ps'
125
+                ],
126
+                'field' => [
127
+                    'id_article' => 'bigint(21) NOT NULL',
128
+                    'surtitre' => "text DEFAULT '' NOT NULL",
129
+                    'titre' => "text DEFAULT '' NOT NULL",
130
+                    'soustitre' => "text DEFAULT '' NOT NULL",
131
+                    'id_rubrique' => "bigint(21) DEFAULT '0' NOT NULL",
132
+                    'descriptif' => "text DEFAULT '' NOT NULL",
133
+                    'chapo' => "mediumtext DEFAULT '' NOT NULL",
134
+                    'texte' => "longtext DEFAULT '' NOT NULL",
135
+                    'ps' => "mediumtext DEFAULT '' NOT NULL",
136
+                    'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
137
+                    'statut' => "varchar(10) DEFAULT '0' NOT NULL",
138
+                    'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
139
+                    'maj' => 'TIMESTAMP',
140
+                    'export' => "VARCHAR(10) DEFAULT 'oui'",
141
+                    'date_redac' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
142
+                    'visites' => "integer DEFAULT '0' NOT NULL",
143
+                    'referers' => "integer DEFAULT '0' NOT NULL",
144
+                    'popularite' => "DOUBLE DEFAULT '0' NOT NULL",
145
+                    'accepter_forum' => "CHAR(3) DEFAULT '' NOT NULL",
146
+                    'date_modif' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
147
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
148
+                    'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
149
+                    'id_trad' => "bigint(21) DEFAULT '0' NOT NULL",
150
+                    'nom_site' => "tinytext DEFAULT '' NOT NULL",
151
+                    'url_site' => "text DEFAULT '' NOT NULL",
152
+                    'virtuel' => "text DEFAULT '' NOT NULL",
153
+                ],
154
+                'key' => [
155
+                    'PRIMARY KEY' => 'id_article',
156
+                    'KEY id_rubrique' => 'id_rubrique',
157
+                    'KEY id_secteur' => 'id_secteur',
158
+                    'KEY id_trad' => 'id_trad',
159
+                    'KEY lang' => 'lang',
160
+                    'KEY statut' => 'statut, date',
161
+                ],
162
+                'join' => [
163
+                    'id_article' => 'id_article',
164
+                    'id_rubrique' => 'id_rubrique'
165
+                ],
166
+                'parent' => [
167
+                    ['type' => 'rubrique', 'champ' => 'id_rubrique']
168
+                ],
169
+                'rechercher_champs' => [
170
+                    'surtitre' => 5,
171
+                    'titre' => 8,
172
+                    'soustitre' => 5,
173
+                    'chapo' => 3,
174
+                    'texte' => 1,
175
+                    'ps' => 1,
176
+                    'nom_site' => 1,
177
+                    'url_site' => 1,
178
+                    'descriptif' => 4
179
+                ],
180
+                'rechercher_jointures' => [
181
+                    'auteur' => ['nom' => 10],
182
+                ],
183
+                'statut' => [
184
+                    [
185
+                        'champ' => 'statut',
186
+                        'publie' => 'publie',
187
+                        'previsu' => 'publie,prop,prepa/auteur',
188
+                        'post_date' => 'date',
189
+                        'exception' => ['statut', 'tout']
190
+                    ]
191
+                ],
192
+                'statut_titres' => [
193
+                    'prepa' => 'info_article_redaction',
194
+                    'prop' => 'info_article_propose',
195
+                    'publie' => 'info_article_publie',
196
+                    'refuse' => 'info_article_refuse',
197
+                    'poubelle' => 'info_article_supprime'
198
+                ],
199
+                'statut_textes_instituer' => [
200
+                    'prepa' => 'texte_statut_en_cours_redaction',
201
+                    'prop' => 'texte_statut_propose_evaluation',
202
+                    'publie' => 'texte_statut_publie',
203
+                    'refuse' => 'texte_statut_refuse',
204
+                    'poubelle' => 'texte_statut_poubelle',
205
+                ],
206
+                'texte_changer_statut' => 'texte_article_statut',
207
+                'aide_changer_statut' => 'artstatut',
208
+                'tables_jointures' => [
209
+                    'profondeur' => 'rubriques',
210
+                    #'id_auteur' => 'auteurs_liens' // declaration generique plus bas
211
+                ],
212
+            ],
213
+            'spip_auteurs' => [
214
+                'page' => 'auteur',
215
+                'texte_retour' => 'icone_retour',
216
+                'texte_ajouter' => 'titre_ajouter_un_auteur',
217
+                'texte_modifier' => 'admin_modifier_auteur',
218
+                'texte_objets' => 'icone_auteurs',
219
+                'texte_objet' => 'public:auteur',
220
+                'info_aucun_objet' => 'info_aucun_auteur',
221
+                'info_1_objet' => 'info_1_auteur',
222
+                'info_nb_objets' => 'info_nb_auteurs',
223
+                'texte_logo_objet' => 'logo_auteur',
224
+                'texte_creer_associer' => 'creer_et_associer_un_auteur',
225
+                'titre' => "nom AS titre, '' AS lang",
226
+                'date' => 'date',
227
+                'principale' => 'oui',
228
+                'champs_editables' => ['nom', 'email', 'bio', 'nom_site', 'url_site', 'imessage', 'pgp'],
229
+                'champs_versionnes' => ['nom', 'bio', 'email', 'nom_site', 'url_site', 'login'],
230
+                'field' => [
231
+                    'id_auteur' => 'bigint(21) NOT NULL',
232
+                    'nom' => "text DEFAULT '' NOT NULL",
233
+                    'bio' => "text DEFAULT '' NOT NULL",
234
+                    'email' => "tinytext DEFAULT '' NOT NULL",
235
+                    'nom_site' => "tinytext DEFAULT '' NOT NULL",
236
+                    'url_site' => "text DEFAULT '' NOT NULL",
237
+                    'login' => 'VARCHAR(255) BINARY',
238
+                    'pass' => "tinytext DEFAULT '' NOT NULL",
239
+                    'low_sec' => "tinytext DEFAULT '' NOT NULL",
240
+                    'statut' => "varchar(255)  DEFAULT '0' NOT NULL",
241
+                    'webmestre' => "varchar(3)  DEFAULT 'non' NOT NULL",
242
+                    'maj' => 'TIMESTAMP',
243
+                    'pgp' => "TEXT DEFAULT '' NOT NULL",
244
+                    'htpass' => "tinytext DEFAULT '' NOT NULL",
245
+                    'en_ligne' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
246
+                    'alea_actuel' => 'tinytext',
247
+                    'alea_futur' => 'tinytext',
248
+                    'prefs' => 'text',
249
+                    'cookie_oubli' => 'tinytext',
250
+                    'source' => "VARCHAR(10) DEFAULT 'spip' NOT NULL",
251
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
252
+                    'imessage' => "VARCHAR(3) DEFAULT '' NOT NULL",
253
+                    'backup_cles' => "mediumtext DEFAULT '' NOT NULL",
254
+                ],
255
+                'key' => [
256
+                    'PRIMARY KEY' => 'id_auteur',
257
+                    'KEY login' => 'login',
258
+                    'KEY statut' => 'statut',
259
+                    'KEY en_ligne' => 'en_ligne',
260
+                ],
261
+                'join' => [
262
+                    'id_auteur' => 'id_auteur',
263
+                    'login' => 'login'
264
+                ],
265
+                'rechercher_champs' => [
266
+                    'nom' => 5,
267
+                    'bio' => 1,
268
+                    'email' => 1,
269
+                    'nom_site' => 1,
270
+                    'url_site' => 1,
271
+                    'login' => 1
272
+                ],
273
+                // 2 conditions pour les auteurs : statut!=poubelle,
274
+                // et avoir des articles publies
275
+                'statut' => [
276
+                    [
277
+                        'champ' => 'statut',
278
+                        'publie' => '!5poubelle',
279
+                        'previsu' => '!5poubelle',
280
+                        'exception' => 'statut'
281
+                    ],
282
+                    [
283
+                        'champ' => [
284
+                            ['spip_auteurs_liens', 'id_auteur'],
285
+                            [
286
+                                'spip_articles',
287
+                                ['id_objet', 'id_article', 'objet', 'article']
288
+                            ],
289
+                            'statut'
290
+                        ],
291
+                        'publie' => 'publie',
292
+                        'previsu' => '!',
293
+                        'post_date' => 'date',
294
+                        'exception' => ['statut', 'lien', 'tout']
295
+                    ],
296
+                ],
297
+                'statut_images' => [
298
+                    'auteur-6forum-16.png',
299
+                    '0minirezo' => 'auteur-0minirezo-16.png',
300
+                    '1comite' => 'auteur-1comite-16.png',
301
+                    '6forum' => 'auteur-6forum-16.png',
302
+                    '5poubelle' => 'auteur-5poubelle-16.png',
303
+                    'nouveau' => ''
304
+                ],
305
+                'statut_titres' => [
306
+                    'titre_image_visiteur',
307
+                    '0minirezo' => 'titre_image_administrateur',
308
+                    '1comite' => 'titre_image_redacteur_02',
309
+                    '6forum' => 'titre_image_visiteur',
310
+                    '5poubelle' => 'titre_image_auteur_supprime',
311
+                ],
312
+                'tables_jointures' => [#'auteurs_liens' // declaration generique plus bas
313
+                ],
314
+            ],
315
+            'spip_rubriques' => [
316
+                'page' => 'rubrique',
317
+                'url_voir' => 'rubrique',
318
+                'url_edit' => 'rubrique_edit',
319
+                'texte_retour' => 'icone_retour',
320
+                'texte_objets' => 'public:rubriques',
321
+                'texte_objet' => 'public:rubrique',
322
+                'texte_modifier' => 'icone_modifier_rubrique',
323
+                'texte_creer' => 'icone_creer_rubrique',
324
+                'texte_ajouter' => 'titre_ajouter_une_rubrique',
325
+                'texte_creer_associer' => 'creer_et_associer_une_rubrique',
326
+                'info_aucun_objet' => 'info_aucun_rubrique',
327
+                'info_1_objet' => 'info_1_rubrique',
328
+                'info_nb_objets' => 'info_nb_rubriques',
329
+                'texte_logo_objet' => 'logo_rubrique',
330
+                'texte_langue_objet' => 'titre_langue_rubrique',
331
+                'texte_definir_comme_traduction_objet' => 'texte_definir_comme_traduction_rubrique',
332
+                'titre' => 'titre, lang',
333
+                'date' => 'date',
334
+                'principale' => 'oui',
335
+                'introduction_longueur' => '600',
336
+                'champs_editables' => ['titre', 'texte', 'descriptif', 'extra'],
337
+                'champs_versionnes' => ['titre', 'descriptif', 'texte'],
338
+                'field' => [
339
+                    'id_rubrique' => 'bigint(21) NOT NULL',
340
+                    'id_parent' => "bigint(21) DEFAULT '0' NOT NULL",
341
+                    'titre' => "text DEFAULT '' NOT NULL",
342
+                    'descriptif' => "text DEFAULT '' NOT NULL",
343
+                    'texte' => "longtext DEFAULT '' NOT NULL",
344
+                    'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
345
+                    'maj' => 'TIMESTAMP',
346
+                    'statut' => "varchar(10) DEFAULT '0' NOT NULL",
347
+                    'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
348
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
349
+                    'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
350
+                    'statut_tmp' => "varchar(10) DEFAULT '0' NOT NULL",
351
+                    'date_tmp' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
352
+                    'profondeur' => "smallint(5) DEFAULT '0' NOT NULL"
353
+                ],
354
+                'key' => [
355
+                    'PRIMARY KEY' => 'id_rubrique',
356
+                    'KEY lang' => 'lang',
357
+                    'KEY id_parent' => 'id_parent',
358
+                ],
359
+                'parent' => [
360
+                    ['type' => 'rubrique', 'champ' => 'id_parent']
361
+                ],
362
+                'rechercher_champs' => [
363
+                    'titre' => 8,
364
+                    'descriptif' => 5,
365
+                    'texte' => 1
366
+                ],
367
+                'statut' => [
368
+                    [
369
+                        'champ' => 'statut',
370
+                        'publie' => 'publie',
371
+                        'previsu' => '!',
372
+                        'exception' => ['statut', 'tout']
373
+                    ],
374
+                ],
375
+                'tables_jointures' => [#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
376
+                ],
377
+            ],
378
+            // toutes les tables ont le droit a une jointure sur les auteurs
379
+            ['tables_jointures' => ['id_auteur' => 'auteurs_liens']]
380
+        ];
381
+
382
+        // avant d'appeller les pipeline qui peuvent generer une reentrance a l'install
383
+        // initialiser la signature
384
+        $md5 = md5(serialize($infos_tables));
385
+
386
+        $GLOBALS['tables_principales'] = pipeline('declarer_tables_principales', $GLOBALS['tables_principales']);
387
+        $GLOBALS['tables_auxiliaires'] = pipeline('declarer_tables_auxiliaires', $GLOBALS['tables_auxiliaires']);
388
+        $infos_tables = pipeline('declarer_tables_objets_sql', $infos_tables);
389
+
390
+        // completer les informations manquantes ou implicites
391
+        $all = [];
392
+        foreach (array_keys($infos_tables) as $t) {
393
+            // les cles numeriques servent a declarer
394
+            // les proprietes applicables a tous les objets
395
+            // on les mets de cote
396
+            if (is_numeric($t)) {
397
+                $all = array_merge_recursive($all, $infos_tables[$t]);
398
+                unset($infos_tables[$t]);
399
+            } else {
400
+                $infos_tables[$t] = renseigner_table_objet_sql($t, $infos_tables[$t]);
401
+            }
402
+        }
403
+
404
+        // repercuter les proprietes generales communes a tous les objets
405
+        foreach (array_keys($infos_tables) as $t) {
406
+            foreach ($all as $i => $v) {
407
+                if (in_array($i, ['tables_jointures', 'champs_versionnes'])) {
408
+                    $add = $all[$i];
409
+                    // eviter les doublons de declaration de table jointure (ex des mots sur auteurs)
410
+                    // pour les declarations generiques avec cles numeriques
411
+                    if ($i == 'tables_jointures' and isset($infos_tables[$t][$i]) and is_countable($infos_tables[$t][$i]) ? count($infos_tables[$t][$i]) : 0) {
412
+                        $doublons = array_intersect($infos_tables[$t][$i], $add);
413
+                        foreach ($doublons as $d) {
414
+                            if (
415
+                                is_numeric(array_search($d, $infos_tables[$t][$i]))
416
+                                and is_numeric($k = array_search($d, $add))
417
+                            ) {
418
+                                unset($add[$k]);
419
+                            }
420
+                        }
421
+                    }
422
+                    $infos_tables[$t][$i] = array_merge($infos_tables[$t][$i] ?? [], $add);
423
+                } else {
424
+                    $infos_tables[$t][$i] = array_merge_recursive(
425
+                        $infos_tables[$t][$i] ?? [],
426
+                        $all[$i]
427
+                    );
428
+                }
429
+            }
430
+        }
431
+
432
+        // completer les tables principales et auxiliaires
433
+        // avec celles declarees uniquement dans declarer_table_objets_sql
434
+        // pour assurer la compat en transition
435
+        foreach ($infos_tables as $table => $infos) {
436
+            $principale_ou_auxiliaire = ($infos['principale'] ? 'tables_principales' : 'tables_auxiliaires');
437
+            // memoriser des champs eventuels declares par des plugins dans le pipeline tables_xxx
438
+            // qui a ete appelle avant
439
+            $mem = ($GLOBALS[$principale_ou_auxiliaire][$table] ?? []);
440
+            // l'ajouter au tableau
441
+            $GLOBALS[$principale_ou_auxiliaire][$table] = [];
442
+            if (isset($infos['field']) and isset($infos['key'])) {
443
+                foreach (['field', 'key', 'join'] as $k) {
444
+                    if (isset($infos_tables[$table][$k])) {
445
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = &$infos_tables[$table][$k];
446
+                    }
447
+                }
448
+            } else {
449
+                // ici on ne renvoie que les declarations, donc RIEN
450
+                // pour avoir la vrai description en base, il faut passer par trouver_table
451
+                $GLOBALS[$principale_ou_auxiliaire][$table] = [];
452
+            }
453
+            if (is_countable($mem) ? count($mem) : 0) {
454
+                foreach (array_keys($mem) as $k) {
455
+                    if (isset($GLOBALS[$principale_ou_auxiliaire][$table][$k])) {
456
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = array_merge(
457
+                            $GLOBALS[$principale_ou_auxiliaire][$table][$k],
458
+                            $mem[$k]
459
+                        );
460
+                    } else {
461
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = $mem[$k];
462
+                    }
463
+                }
464
+            }
465
+        }
466
+
467
+        // recuperer les interfaces (table_titre, table_date)
468
+        // on ne le fait que dans un second temps pour que table_objet soit fonctionnel
469
+        // dans le pipeline de declarer_tables_interfaces
470
+        include_spip('public/interfaces');
471
+        foreach (array_keys($infos_tables) as $t) {
472
+            $infos_tables[$t] = renseigner_table_objet_interfaces($t, $infos_tables[$t]);
473
+        }
474
+
475
+        $deja_la = false;
476
+        // signature
477
+        $md5 = md5(serialize($infos_tables));
478
+    }
479
+    if ($table_sql === '::md5') {
480
+        return $md5;
481
+    }
482
+    if ($table_sql and !isset($infos_tables[$table_sql])) {
483
+        #$desc = renseigner_table_objet_sql($table_sql,$desc);
484
+        $desc = renseigner_table_objet_interfaces($table_sql, $desc);
485
+
486
+        return $desc;
487
+    }
488
+    if ($table_sql) {
489
+        return $infos_tables[$table_sql] ?? [];
490
+    }
491
+
492
+    return $infos_tables;
493 493
 }
494 494
 
495 495
 
@@ -504,27 +504,27 @@  discard block
 block discarded – undo
504 504
  **/
505 505
 function base_serial(&$tables_principales) {
506 506
 
507
-	$spip_jobs = [
508
-		'id_job' => 'bigint(21) NOT NULL',
509
-		'descriptif' => "text DEFAULT '' NOT NULL",
510
-		'fonction' => 'varchar(255) NOT NULL', //nom de la fonction
511
-		'args' => "longblob DEFAULT '' NOT NULL", // arguments
512
-		'md5args' => "char(32) NOT NULL default ''", // signature des arguments
513
-		'inclure' => 'varchar(255) NOT NULL', // fichier a inclure ou path/ pour charger_fonction
514
-		'priorite' => 'smallint(6) NOT NULL default 0',
515
-		'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // date au plus tot
516
-		'status' => 'tinyint NOT NULL default 1',
517
-	];
518
-
519
-	$spip_jobs_key = [
520
-		'PRIMARY KEY' => 'id_job',
521
-		'KEY date' => 'date',
522
-		'KEY status' => 'status',
523
-	];
524
-
525
-	/// Attention: mes_fonctions peut avoir deja defini cette variable
526
-	/// il faut donc rajouter, mais pas reinitialiser
527
-	$tables_principales['spip_jobs'] = ['field' => &$spip_jobs, 'key' => &$spip_jobs_key];
507
+    $spip_jobs = [
508
+        'id_job' => 'bigint(21) NOT NULL',
509
+        'descriptif' => "text DEFAULT '' NOT NULL",
510
+        'fonction' => 'varchar(255) NOT NULL', //nom de la fonction
511
+        'args' => "longblob DEFAULT '' NOT NULL", // arguments
512
+        'md5args' => "char(32) NOT NULL default ''", // signature des arguments
513
+        'inclure' => 'varchar(255) NOT NULL', // fichier a inclure ou path/ pour charger_fonction
514
+        'priorite' => 'smallint(6) NOT NULL default 0',
515
+        'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // date au plus tot
516
+        'status' => 'tinyint NOT NULL default 1',
517
+    ];
518
+
519
+    $spip_jobs_key = [
520
+        'PRIMARY KEY' => 'id_job',
521
+        'KEY date' => 'date',
522
+        'KEY status' => 'status',
523
+    ];
524
+
525
+    /// Attention: mes_fonctions peut avoir deja defini cette variable
526
+    /// il faut donc rajouter, mais pas reinitialiser
527
+    $tables_principales['spip_jobs'] = ['field' => &$spip_jobs, 'key' => &$spip_jobs_key];
528 528
 }
529 529
 
530 530
 
@@ -536,71 +536,71 @@  discard block
 block discarded – undo
536 536
  * @return void
537 537
  **/
538 538
 function base_auxiliaires(&$tables_auxiliaires) {
539
-	$spip_resultats = [
540
-		'recherche' => "char(16) DEFAULT '' NOT NULL",
541
-		'id' => 'INT UNSIGNED NOT NULL',
542
-		'points' => "INT UNSIGNED DEFAULT '0' NOT NULL",
543
-		'table_objet' => "varchar(30) DEFAULT '' NOT NULL",
544
-		'serveur' => "char(16) DEFAULT '' NOT NULL", // hash md5 partiel du serveur de base ('' pour le serveur principal)
545
-		'maj' => 'TIMESTAMP'
546
-	];
547
-
548
-	$spip_resultats_key = [// pas de cle ni index, ca fait des insertions plus rapides et les requetes jointes utilisees en recheche ne sont pas plus lentes ...
549
-	];
550
-
551
-	$spip_auteurs_liens = [
552
-		'id_auteur' => "bigint(21) DEFAULT '0' NOT NULL",
553
-		'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
554
-		'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
555
-		'vu' => "VARCHAR(6) DEFAULT 'non' NOT NULL"
556
-	];
557
-
558
-	$spip_auteurs_liens_key = [
559
-		'PRIMARY KEY' => 'id_auteur,id_objet,objet',
560
-		'KEY id_auteur' => 'id_auteur',
561
-		'KEY id_objet' => 'id_objet',
562
-		'KEY objet' => 'objet',
563
-	];
564
-
565
-	$spip_meta = [
566
-		'nom' => 'VARCHAR (255) NOT NULL',
567
-		'valeur' => "text DEFAULT ''",
568
-		'impt' => "ENUM('non', 'oui') DEFAULT 'oui' NOT NULL",
569
-		'maj' => 'TIMESTAMP'
570
-	];
571
-
572
-	$spip_meta_key = [
573
-		'PRIMARY KEY' => 'nom'
574
-	];
575
-
576
-	$spip_jobs_liens = [
577
-		'id_job' => "bigint(21) DEFAULT '0' NOT NULL",
578
-		'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
579
-		'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
580
-	];
581
-
582
-	$spip_jobs_liens_key = [
583
-		'PRIMARY KEY' => 'id_job,id_objet,objet',
584
-		'KEY id_job' => 'id_job'
585
-	];
586
-
587
-	$tables_auxiliaires['spip_auteurs_liens'] = [
588
-		'field' => &$spip_auteurs_liens,
589
-		'key' => &$spip_auteurs_liens_key
590
-	];
591
-
592
-	$tables_auxiliaires['spip_meta'] = [
593
-		'field' => &$spip_meta,
594
-		'key' => &$spip_meta_key
595
-	];
596
-	$tables_auxiliaires['spip_resultats'] = [
597
-		'field' => &$spip_resultats,
598
-		'key' => &$spip_resultats_key
599
-	];
600
-	$tables_auxiliaires['spip_jobs_liens'] = [
601
-		'field' => &$spip_jobs_liens,
602
-		'key' => &$spip_jobs_liens_key
603
-	];
539
+    $spip_resultats = [
540
+        'recherche' => "char(16) DEFAULT '' NOT NULL",
541
+        'id' => 'INT UNSIGNED NOT NULL',
542
+        'points' => "INT UNSIGNED DEFAULT '0' NOT NULL",
543
+        'table_objet' => "varchar(30) DEFAULT '' NOT NULL",
544
+        'serveur' => "char(16) DEFAULT '' NOT NULL", // hash md5 partiel du serveur de base ('' pour le serveur principal)
545
+        'maj' => 'TIMESTAMP'
546
+    ];
547
+
548
+    $spip_resultats_key = [// pas de cle ni index, ca fait des insertions plus rapides et les requetes jointes utilisees en recheche ne sont pas plus lentes ...
549
+    ];
550
+
551
+    $spip_auteurs_liens = [
552
+        'id_auteur' => "bigint(21) DEFAULT '0' NOT NULL",
553
+        'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
554
+        'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
555
+        'vu' => "VARCHAR(6) DEFAULT 'non' NOT NULL"
556
+    ];
557
+
558
+    $spip_auteurs_liens_key = [
559
+        'PRIMARY KEY' => 'id_auteur,id_objet,objet',
560
+        'KEY id_auteur' => 'id_auteur',
561
+        'KEY id_objet' => 'id_objet',
562
+        'KEY objet' => 'objet',
563
+    ];
564
+
565
+    $spip_meta = [
566
+        'nom' => 'VARCHAR (255) NOT NULL',
567
+        'valeur' => "text DEFAULT ''",
568
+        'impt' => "ENUM('non', 'oui') DEFAULT 'oui' NOT NULL",
569
+        'maj' => 'TIMESTAMP'
570
+    ];
571
+
572
+    $spip_meta_key = [
573
+        'PRIMARY KEY' => 'nom'
574
+    ];
575
+
576
+    $spip_jobs_liens = [
577
+        'id_job' => "bigint(21) DEFAULT '0' NOT NULL",
578
+        'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
579
+        'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
580
+    ];
581
+
582
+    $spip_jobs_liens_key = [
583
+        'PRIMARY KEY' => 'id_job,id_objet,objet',
584
+        'KEY id_job' => 'id_job'
585
+    ];
586
+
587
+    $tables_auxiliaires['spip_auteurs_liens'] = [
588
+        'field' => &$spip_auteurs_liens,
589
+        'key' => &$spip_auteurs_liens_key
590
+    ];
591
+
592
+    $tables_auxiliaires['spip_meta'] = [
593
+        'field' => &$spip_meta,
594
+        'key' => &$spip_meta_key
595
+    ];
596
+    $tables_auxiliaires['spip_resultats'] = [
597
+        'field' => &$spip_resultats,
598
+        'key' => &$spip_resultats_key
599
+    ];
600
+    $tables_auxiliaires['spip_jobs_liens'] = [
601
+        'field' => &$spip_jobs_liens,
602
+        'key' => &$spip_jobs_liens_key
603
+    ];
604 604
 }
605 605
 
606 606
 
@@ -657,129 +657,129 @@  discard block
 block discarded – undo
657 657
  * @return array
658 658
  */
659 659
 function renseigner_table_objet_sql($table_sql, &$infos) {
660
-	if (!isset($infos['type'])) {
661
-		// si on arrive de base/trouver_table, on a la cle primaire :
662
-		// s'en servir pour extrapoler le type
663
-		if (isset($infos['key']['PRIMARY KEY'])) {
664
-			$primary = $infos['key']['PRIMARY KEY'];
665
-			$primary = explode(',', $primary);
666
-			$primary = reset($primary);
667
-			$infos['type'] = preg_replace(',^spip_|^id_|s$,', '', $primary);
668
-		} else {
669
-			$infos['type'] = preg_replace(',^spip_|s$,', '', $table_sql);
670
-		}
671
-	}
672
-	if (!isset($infos['type_surnoms'])) {
673
-		$infos['type_surnoms'] = [];
674
-	}
675
-
676
-	if (!isset($infos['table_objet'])) {
677
-		$infos['table_objet'] = preg_replace(',^spip_,', '', $table_sql);
678
-	}
679
-	if (!isset($infos['table_objet_surnoms'])) {
680
-		$infos['table_objet_surnoms'] = [];
681
-	}
682
-
683
-	if (!isset($infos['principale'])) {
684
-		$infos['principale'] = (isset($GLOBALS['tables_principales'][$table_sql]) ? 'oui' : false);
685
-	}
686
-
687
-	// normaliser pour pouvoir tester en php $infos['principale']?
688
-	// et dans une boucle {principale=oui}
689
-	$infos['principale'] = (($infos['principale'] and $infos['principale'] != 'non') ? 'oui' : false);
690
-
691
-	// declarer et normaliser pour pouvoir tester en php $infos['editable']?
692
-	// et dans une boucle {editable=oui}
693
-	if (!isset($infos['editable'])) {
694
-		$infos['editable'] = 'oui';
695
-	}
696
-
697
-	$infos['editable'] = (($infos['editable'] and $infos['editable'] != 'non') ? 'oui' : false);
698
-
699
-	// les urls publiques sont par defaut page=type pour les tables principales, et rien pour les autres
700
-	// seules les exceptions sont donc a declarer
701
-	if (!isset($infos['page'])) {
702
-		$infos['page'] = ($infos['principale'] ? $infos['type'] : '');
703
-	}
704
-
705
-	if (!isset($infos['url_voir'])) {
706
-		$infos['url_voir'] = $infos['type'];
707
-	}
708
-	if (!isset($infos['url_edit'])) {
709
-		$infos['url_edit'] = $infos['url_voir'] . ($infos['editable'] ? '_edit' : '');
710
-	}
711
-	if (!isset($infos['icone_objet'])) {
712
-		$infos['icone_objet'] = $infos['type'];
713
-	}
714
-
715
-	// chaines de langue
716
-	// par defaut : objet:icone_xxx_objet
717
-	if (!isset($infos['texte_retour'])) {
718
-		$infos['texte_retour'] = 'icone_retour';
719
-	}
720
-	if (!isset($infos['texte_modifier'])) {
721
-		$infos['texte_modifier'] = $infos['type'] . ':' . 'icone_modifier_' . $infos['type'];
722
-	}
723
-	if (!isset($infos['texte_creer'])) {
724
-		$infos['texte_creer'] = $infos['type'] . ':' . 'icone_creer_' . $infos['type'];
725
-	}
726
-	if (!isset($infos['texte_creer_associer'])) {
727
-		$infos['texte_creer_associer'] = $infos['type'] . ':' . 'texte_creer_associer_' . $infos['type'];
728
-	}
729
-	if (!isset($infos['texte_ajouter'])) {
730
-		// Ajouter un X
731
-		$infos['texte_ajouter'] = $infos['type'] . ':' . 'texte_ajouter_' . $infos['type'];
732
-	}
733
-	if (!isset($infos['texte_objets'])) {
734
-		$infos['texte_objets'] = $infos['type'] . ':' . 'titre_' . $infos['table_objet'];
735
-	}
736
-	if (!isset($infos['texte_objet'])) {
737
-		$infos['texte_objet'] = $infos['type'] . ':' . 'titre_' . $infos['type'];
738
-	}
739
-	if (!isset($infos['texte_logo_objet'])) {
740
-		// objet:titre_logo_objet "Logo de ce X"
741
-		$infos['texte_logo_objet'] = $infos['type'] . ':' . 'titre_logo_' . $infos['type'];
742
-	}
743
-	if (!isset($infos['texte_langue_objet'])) {
744
-		// objet:texte_langue_objet "Langue de ce X"
745
-		$infos['texte_langue_objet'] = $infos['type'] . ':' . 'titre_langue_' . $infos['type'];
746
-	}
747
-	if (!isset($infos['texte_definir_comme_traduction_objet'])) {
748
-		// "Ce X est une traduction du X numéro :"
749
-		$infos['texte_definir_comme_traduction_objet'] = $infos['type'] . ':' . 'texte_definir_comme_traduction_' . $infos['type'];
750
-	}
751
-
752
-	// objet:info_aucun_objet
753
-	if (!isset($infos['info_aucun_objet'])) {
754
-		$infos['info_aucun_objet'] = $infos['type'] . ':' . 'info_aucun_' . $infos['type'];
755
-	}
756
-	// objet:info_1_objet
757
-	if (!isset($infos['info_1_objet'])) {
758
-		$infos['info_1_objet'] = $infos['type'] . ':' . 'info_1_' . $infos['type'];
759
-	}
760
-	// objet:info_nb_objets
761
-	if (!isset($infos['info_nb_objets'])) {
762
-		$infos['info_nb_objets'] = $infos['type'] . ':' . 'info_nb_' . $infos['table_objet'];
763
-	}
764
-
765
-	if (!isset($infos['champs_editables'])) {
766
-		$infos['champs_editables'] = [];
767
-	}
768
-	if (!isset($infos['champs_versionnes'])) {
769
-		$infos['champs_versionnes'] = [];
770
-	}
771
-	if (!isset($infos['rechercher_champs'])) {
772
-		$infos['rechercher_champs'] = [];
773
-	}
774
-	if (!isset($infos['rechercher_jointures'])) {
775
-		$infos['rechercher_jointures'] = [];
776
-	}
777
-
778
-	if (!isset($infos['modeles'])) {
779
-		$infos['modeles'] = [$infos['type']];
780
-	}
781
-
782
-	return $infos;
660
+    if (!isset($infos['type'])) {
661
+        // si on arrive de base/trouver_table, on a la cle primaire :
662
+        // s'en servir pour extrapoler le type
663
+        if (isset($infos['key']['PRIMARY KEY'])) {
664
+            $primary = $infos['key']['PRIMARY KEY'];
665
+            $primary = explode(',', $primary);
666
+            $primary = reset($primary);
667
+            $infos['type'] = preg_replace(',^spip_|^id_|s$,', '', $primary);
668
+        } else {
669
+            $infos['type'] = preg_replace(',^spip_|s$,', '', $table_sql);
670
+        }
671
+    }
672
+    if (!isset($infos['type_surnoms'])) {
673
+        $infos['type_surnoms'] = [];
674
+    }
675
+
676
+    if (!isset($infos['table_objet'])) {
677
+        $infos['table_objet'] = preg_replace(',^spip_,', '', $table_sql);
678
+    }
679
+    if (!isset($infos['table_objet_surnoms'])) {
680
+        $infos['table_objet_surnoms'] = [];
681
+    }
682
+
683
+    if (!isset($infos['principale'])) {
684
+        $infos['principale'] = (isset($GLOBALS['tables_principales'][$table_sql]) ? 'oui' : false);
685
+    }
686
+
687
+    // normaliser pour pouvoir tester en php $infos['principale']?
688
+    // et dans une boucle {principale=oui}
689
+    $infos['principale'] = (($infos['principale'] and $infos['principale'] != 'non') ? 'oui' : false);
690
+
691
+    // declarer et normaliser pour pouvoir tester en php $infos['editable']?
692
+    // et dans une boucle {editable=oui}
693
+    if (!isset($infos['editable'])) {
694
+        $infos['editable'] = 'oui';
695
+    }
696
+
697
+    $infos['editable'] = (($infos['editable'] and $infos['editable'] != 'non') ? 'oui' : false);
698
+
699
+    // les urls publiques sont par defaut page=type pour les tables principales, et rien pour les autres
700
+    // seules les exceptions sont donc a declarer
701
+    if (!isset($infos['page'])) {
702
+        $infos['page'] = ($infos['principale'] ? $infos['type'] : '');
703
+    }
704
+
705
+    if (!isset($infos['url_voir'])) {
706
+        $infos['url_voir'] = $infos['type'];
707
+    }
708
+    if (!isset($infos['url_edit'])) {
709
+        $infos['url_edit'] = $infos['url_voir'] . ($infos['editable'] ? '_edit' : '');
710
+    }
711
+    if (!isset($infos['icone_objet'])) {
712
+        $infos['icone_objet'] = $infos['type'];
713
+    }
714
+
715
+    // chaines de langue
716
+    // par defaut : objet:icone_xxx_objet
717
+    if (!isset($infos['texte_retour'])) {
718
+        $infos['texte_retour'] = 'icone_retour';
719
+    }
720
+    if (!isset($infos['texte_modifier'])) {
721
+        $infos['texte_modifier'] = $infos['type'] . ':' . 'icone_modifier_' . $infos['type'];
722
+    }
723
+    if (!isset($infos['texte_creer'])) {
724
+        $infos['texte_creer'] = $infos['type'] . ':' . 'icone_creer_' . $infos['type'];
725
+    }
726
+    if (!isset($infos['texte_creer_associer'])) {
727
+        $infos['texte_creer_associer'] = $infos['type'] . ':' . 'texte_creer_associer_' . $infos['type'];
728
+    }
729
+    if (!isset($infos['texte_ajouter'])) {
730
+        // Ajouter un X
731
+        $infos['texte_ajouter'] = $infos['type'] . ':' . 'texte_ajouter_' . $infos['type'];
732
+    }
733
+    if (!isset($infos['texte_objets'])) {
734
+        $infos['texte_objets'] = $infos['type'] . ':' . 'titre_' . $infos['table_objet'];
735
+    }
736
+    if (!isset($infos['texte_objet'])) {
737
+        $infos['texte_objet'] = $infos['type'] . ':' . 'titre_' . $infos['type'];
738
+    }
739
+    if (!isset($infos['texte_logo_objet'])) {
740
+        // objet:titre_logo_objet "Logo de ce X"
741
+        $infos['texte_logo_objet'] = $infos['type'] . ':' . 'titre_logo_' . $infos['type'];
742
+    }
743
+    if (!isset($infos['texte_langue_objet'])) {
744
+        // objet:texte_langue_objet "Langue de ce X"
745
+        $infos['texte_langue_objet'] = $infos['type'] . ':' . 'titre_langue_' . $infos['type'];
746
+    }
747
+    if (!isset($infos['texte_definir_comme_traduction_objet'])) {
748
+        // "Ce X est une traduction du X numéro :"
749
+        $infos['texte_definir_comme_traduction_objet'] = $infos['type'] . ':' . 'texte_definir_comme_traduction_' . $infos['type'];
750
+    }
751
+
752
+    // objet:info_aucun_objet
753
+    if (!isset($infos['info_aucun_objet'])) {
754
+        $infos['info_aucun_objet'] = $infos['type'] . ':' . 'info_aucun_' . $infos['type'];
755
+    }
756
+    // objet:info_1_objet
757
+    if (!isset($infos['info_1_objet'])) {
758
+        $infos['info_1_objet'] = $infos['type'] . ':' . 'info_1_' . $infos['type'];
759
+    }
760
+    // objet:info_nb_objets
761
+    if (!isset($infos['info_nb_objets'])) {
762
+        $infos['info_nb_objets'] = $infos['type'] . ':' . 'info_nb_' . $infos['table_objet'];
763
+    }
764
+
765
+    if (!isset($infos['champs_editables'])) {
766
+        $infos['champs_editables'] = [];
767
+    }
768
+    if (!isset($infos['champs_versionnes'])) {
769
+        $infos['champs_versionnes'] = [];
770
+    }
771
+    if (!isset($infos['rechercher_champs'])) {
772
+        $infos['rechercher_champs'] = [];
773
+    }
774
+    if (!isset($infos['rechercher_jointures'])) {
775
+        $infos['rechercher_jointures'] = [];
776
+    }
777
+
778
+    if (!isset($infos['modeles'])) {
779
+        $infos['modeles'] = [$infos['type']];
780
+    }
781
+
782
+    return $infos;
783 783
 }
784 784
 
785 785
 /**
@@ -796,30 +796,30 @@  discard block
 block discarded – undo
796 796
  * @return array
797 797
  */
798 798
 function renseigner_table_objet_interfaces($table_sql, &$infos) {
799
-	if (!isset($infos['titre'])) {
800
-		if (isset($infos['table_objet']) and isset($GLOBALS['table_titre'][$infos['table_objet']])) {
801
-			$infos['titre'] = $GLOBALS['table_titre'][$infos['table_objet']];
802
-		} else {
803
-			$infos['titre'] = ((isset($infos['field']['titre'])) ? 'titre,' : "'' as titre,");
804
-			$infos['titre'] .= ((isset($infos['field']['lang'])) ? 'lang' : "'' as lang");
805
-		}
806
-	}
807
-	if (!isset($infos['date'])) {
808
-		if (isset($infos['table_objet']) and isset($GLOBALS['table_date'][$infos['table_objet']])) {
809
-			$infos['date'] = $GLOBALS['table_date'][$infos['table_objet']];
810
-		} else {
811
-			$infos['date'] = ((isset($infos['field']['date'])) ? 'date' : '');
812
-		}
813
-	}
814
-
815
-	$infos['statut'] ??= $GLOBALS['table_statut'][$table_sql] ?? '';
816
-	$infos['tables_jointures'] ??= [];
817
-
818
-	if (isset($GLOBALS['tables_jointures'][$table_sql])) {
819
-		$infos['tables_jointures'] = array_merge($infos['tables_jointures'], $GLOBALS['tables_jointures'][$table_sql]);
820
-	}
821
-
822
-	return $infos;
799
+    if (!isset($infos['titre'])) {
800
+        if (isset($infos['table_objet']) and isset($GLOBALS['table_titre'][$infos['table_objet']])) {
801
+            $infos['titre'] = $GLOBALS['table_titre'][$infos['table_objet']];
802
+        } else {
803
+            $infos['titre'] = ((isset($infos['field']['titre'])) ? 'titre,' : "'' as titre,");
804
+            $infos['titre'] .= ((isset($infos['field']['lang'])) ? 'lang' : "'' as lang");
805
+        }
806
+    }
807
+    if (!isset($infos['date'])) {
808
+        if (isset($infos['table_objet']) and isset($GLOBALS['table_date'][$infos['table_objet']])) {
809
+            $infos['date'] = $GLOBALS['table_date'][$infos['table_objet']];
810
+        } else {
811
+            $infos['date'] = ((isset($infos['field']['date'])) ? 'date' : '');
812
+        }
813
+    }
814
+
815
+    $infos['statut'] ??= $GLOBALS['table_statut'][$table_sql] ?? '';
816
+    $infos['tables_jointures'] ??= [];
817
+
818
+    if (isset($GLOBALS['tables_jointures'][$table_sql])) {
819
+        $infos['tables_jointures'] = array_merge($infos['tables_jointures'], $GLOBALS['tables_jointures'][$table_sql]);
820
+    }
821
+
822
+    return $infos;
823 823
 }
824 824
 
825 825
 /**
@@ -830,13 +830,13 @@  discard block
 block discarded – undo
830 830
  *     Liste et descriptions des tables principales
831 831
  **/
832 832
 function lister_tables_principales() {
833
-	static $done = false;
834
-	if (!$done or !(is_countable($GLOBALS['tables_principales']) ? count($GLOBALS['tables_principales']) : 0)) {
835
-		lister_tables_objets_sql();
836
-		$done = true;
837
-	}
833
+    static $done = false;
834
+    if (!$done or !(is_countable($GLOBALS['tables_principales']) ? count($GLOBALS['tables_principales']) : 0)) {
835
+        lister_tables_objets_sql();
836
+        $done = true;
837
+    }
838 838
 
839
-	return $GLOBALS['tables_principales'];
839
+    return $GLOBALS['tables_principales'];
840 840
 }
841 841
 
842 842
 /**
@@ -847,13 +847,13 @@  discard block
 block discarded – undo
847 847
  *     Liste et descriptions des tables auxiliaires
848 848
  **/
849 849
 function lister_tables_auxiliaires() {
850
-	static $done = false;
851
-	if (!$done or !(is_countable($GLOBALS['tables_auxiliaires']) ? count($GLOBALS['tables_auxiliaires']) : 0)) {
852
-		lister_tables_objets_sql();
853
-		$done = true;
854
-	}
850
+    static $done = false;
851
+    if (!$done or !(is_countable($GLOBALS['tables_auxiliaires']) ? count($GLOBALS['tables_auxiliaires']) : 0)) {
852
+        lister_tables_objets_sql();
853
+        $done = true;
854
+    }
855 855
 
856
-	return $GLOBALS['tables_auxiliaires'];
856
+    return $GLOBALS['tables_auxiliaires'];
857 857
 }
858 858
 
859 859
 /**
@@ -862,45 +862,45 @@  discard block
 block discarded – undo
862 862
  * @return array
863 863
  */
864 864
 function lister_tables_objets_surnoms() {
865
-	static $surnoms = null;
866
-	static $md5 = null;
867
-	if (
868
-		!$surnoms
869
-		or $md5 != lister_tables_objets_sql('::md5')
870
-	) {
871
-		// passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
872
-		// pour compatibilite, car il faut dorenavent utiliser
873
-		// declarer_table_objets_sql
874
-		$surnoms = pipeline(
875
-			'declarer_tables_objets_surnoms',
876
-			[
877
-				# pour les modeles
878
-				# a enlever ?
879
-				'doc' => 'documents',
880
-				'img' => 'documents',
881
-				'emb' => 'documents',
882
-			]
883
-		);
884
-		$infos_tables = lister_tables_objets_sql();
885
-		foreach ($infos_tables as $t => $infos) {
886
-			// cas de base type=>table
887
-			// et preg_replace(',^spip_|^id_|s$,',table)=>table
888
-			if ($infos['table_objet']) { // securite, si la fonction est appelee trop tot, c'est vide
889
-				// optimisations pour table_objet
890
-				//$surnoms[$infos['type']] = $infos['table_objet'];
891
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['table_objet'];
892
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['table_objet'];
893
-				if (is_array($infos['table_objet_surnoms']) and count($infos['table_objet_surnoms'])) {
894
-					foreach ($infos['table_objet_surnoms'] as $surnom) {
895
-						$surnoms[$surnom] = $infos['table_objet'];
896
-					}
897
-				}
898
-			}
899
-		}
900
-		$md5 = lister_tables_objets_sql('::md5');
901
-	}
902
-
903
-	return $surnoms;
865
+    static $surnoms = null;
866
+    static $md5 = null;
867
+    if (
868
+        !$surnoms
869
+        or $md5 != lister_tables_objets_sql('::md5')
870
+    ) {
871
+        // passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
872
+        // pour compatibilite, car il faut dorenavent utiliser
873
+        // declarer_table_objets_sql
874
+        $surnoms = pipeline(
875
+            'declarer_tables_objets_surnoms',
876
+            [
877
+                # pour les modeles
878
+                # a enlever ?
879
+                'doc' => 'documents',
880
+                'img' => 'documents',
881
+                'emb' => 'documents',
882
+            ]
883
+        );
884
+        $infos_tables = lister_tables_objets_sql();
885
+        foreach ($infos_tables as $t => $infos) {
886
+            // cas de base type=>table
887
+            // et preg_replace(',^spip_|^id_|s$,',table)=>table
888
+            if ($infos['table_objet']) { // securite, si la fonction est appelee trop tot, c'est vide
889
+                // optimisations pour table_objet
890
+                //$surnoms[$infos['type']] = $infos['table_objet'];
891
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['table_objet'];
892
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['table_objet'];
893
+                if (is_array($infos['table_objet_surnoms']) and count($infos['table_objet_surnoms'])) {
894
+                    foreach ($infos['table_objet_surnoms'] as $surnom) {
895
+                        $surnoms[$surnom] = $infos['table_objet'];
896
+                    }
897
+                }
898
+            }
899
+        }
900
+        $md5 = lister_tables_objets_sql('::md5');
901
+    }
902
+
903
+    return $surnoms;
904 904
 }
905 905
 
906 906
 /**
@@ -909,35 +909,35 @@  discard block
 block discarded – undo
909 909
  * @return array
910 910
  */
911 911
 function lister_types_surnoms() {
912
-	static $surnoms = null;
913
-	static $md5 = null;
914
-	if (
915
-		!$surnoms
916
-		or $md5 != lister_tables_objets_sql('::md5')
917
-	) {
918
-		// passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
919
-		// pour compatibilite, car il faut dorenavent utiliser
920
-		// declarer_table_objets_sql
921
-		$surnoms = pipeline('declarer_type_surnoms', ['racine-site' => 'site']);
922
-		$infos_tables = lister_tables_objets_sql();
923
-		foreach ($infos_tables as $t => $infos) {
924
-			if ($infos['type']) { // securite, si la fonction est appelee trop tot, c'est vide
925
-				// optimisations pour objet_type
926
-				//$surnoms[$infos['type']] = $infos['type'];
927
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['type'];
928
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['type'];
929
-				// surnoms declares
930
-				if (is_array($infos['type_surnoms']) and count($infos['type_surnoms'])) {
931
-					foreach ($infos['type_surnoms'] as $surnom) {
932
-						$surnoms[$surnom] = $infos['type'];
933
-					}
934
-				}
935
-			}
936
-		}
937
-		$md5 = lister_tables_objets_sql('::md5');
938
-	}
939
-
940
-	return $surnoms;
912
+    static $surnoms = null;
913
+    static $md5 = null;
914
+    if (
915
+        !$surnoms
916
+        or $md5 != lister_tables_objets_sql('::md5')
917
+    ) {
918
+        // passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
919
+        // pour compatibilite, car il faut dorenavent utiliser
920
+        // declarer_table_objets_sql
921
+        $surnoms = pipeline('declarer_type_surnoms', ['racine-site' => 'site']);
922
+        $infos_tables = lister_tables_objets_sql();
923
+        foreach ($infos_tables as $t => $infos) {
924
+            if ($infos['type']) { // securite, si la fonction est appelee trop tot, c'est vide
925
+                // optimisations pour objet_type
926
+                //$surnoms[$infos['type']] = $infos['type'];
927
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['type'];
928
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['type'];
929
+                // surnoms declares
930
+                if (is_array($infos['type_surnoms']) and count($infos['type_surnoms'])) {
931
+                    foreach ($infos['type_surnoms'] as $surnom) {
932
+                        $surnoms[$surnom] = $infos['type'];
933
+                    }
934
+                }
935
+            }
936
+        }
937
+        $md5 = lister_tables_objets_sql('::md5');
938
+    }
939
+
940
+    return $surnoms;
941 941
 }
942 942
 
943 943
 /**
@@ -951,22 +951,22 @@  discard block
 block discarded – undo
951 951
  *     Couples (nom de la table SQL => même nom, sans 'spip_' devant)
952 952
  **/
953 953
 function lister_tables_spip($serveur = '') {
954
-	static $tables = [];
955
-	if (!isset($tables[$serveur])) {
956
-		$tables[$serveur] = [];
957
-		if (!function_exists('sql_alltable')) {
958
-			include_spip('base/abstract_sql');
959
-		}
960
-		$ts = sql_alltable(null, $serveur); // toutes les tables "spip_" (ou prefixe perso)
961
-		$connexion = $GLOBALS['connexions'][$serveur ?: 0];
962
-		$spip = $connexion['prefixe'] . '_';
963
-		foreach ($ts as $t) {
964
-			$t = substr($t, strlen($spip));
965
-			$tables[$serveur]["spip_$t"] = $t;
966
-		}
967
-	}
968
-
969
-	return $tables[$serveur];
954
+    static $tables = [];
955
+    if (!isset($tables[$serveur])) {
956
+        $tables[$serveur] = [];
957
+        if (!function_exists('sql_alltable')) {
958
+            include_spip('base/abstract_sql');
959
+        }
960
+        $ts = sql_alltable(null, $serveur); // toutes les tables "spip_" (ou prefixe perso)
961
+        $connexion = $GLOBALS['connexions'][$serveur ?: 0];
962
+        $spip = $connexion['prefixe'] . '_';
963
+        foreach ($ts as $t) {
964
+            $t = substr($t, strlen($spip));
965
+            $tables[$serveur]["spip_$t"] = $t;
966
+        }
967
+    }
968
+
969
+    return $tables[$serveur];
970 970
 }
971 971
 
972 972
 
@@ -981,18 +981,18 @@  discard block
 block discarded – undo
981 981
  *     Couples (nom de la table SQL => même nom)
982 982
  **/
983 983
 function lister_toutes_tables($serveur) {
984
-	static $tables = [];
985
-	if (!isset($tables[$serveur])) {
986
-		$tables[$serveur] = [];
987
-		if (!function_exists('sql_alltable')) {
988
-			include_spip('base/abstract_sql');
989
-		}
990
-		$ts = sql_alltable('%', $serveur); // toutes les tables
991
-		foreach ($ts as $t) {
992
-			$tables[$serveur][$t] = $t;
993
-		}
994
-	}
995
-	return $tables[$serveur];
984
+    static $tables = [];
985
+    if (!isset($tables[$serveur])) {
986
+        $tables[$serveur] = [];
987
+        if (!function_exists('sql_alltable')) {
988
+            include_spip('base/abstract_sql');
989
+        }
990
+        $ts = sql_alltable('%', $serveur); // toutes les tables
991
+        foreach ($ts as $t) {
992
+            $tables[$serveur][$t] = $t;
993
+        }
994
+    }
995
+    return $tables[$serveur];
996 996
 }
997 997
 
998 998
 /**
@@ -1013,39 +1013,39 @@  discard block
 block discarded – undo
1013 1013
  **/
1014 1014
 function table_objet(string $type, string $serveur = ''): string {
1015 1015
 
1016
-	if ($type) {
1017
-		$type = preg_replace(',^spip_|^id_|s$,', '', $type);
1018
-	}
1019
-	if (!strlen($type)) {
1020
-		return '';
1021
-	}
1022
-
1023
-	$surnoms = lister_tables_objets_surnoms();
1024
-	if (isset($surnoms[$type])) {
1025
-		return $surnoms[$type];
1026
-	}
1027
-
1028
-	if ($serveur !== false) {
1029
-		$t = lister_tables_spip($serveur);
1030
-		$trouver_table = charger_fonction('trouver_table', 'base');
1031
-		$typetrim = rtrim($type, 's') . 's';
1032
-		if (
1033
-			(isset($t[$typetrim]) or in_array($typetrim, $t))
1034
-			and ($desc = $trouver_table(rtrim($type, 's') . 's', $serveur))
1035
-		) {
1036
-			return $desc['id_table'];
1037
-		} elseif (
1038
-			(isset($t[$type]) or in_array($type, $t))
1039
-			and ($desc = $trouver_table($type, $serveur))
1040
-		) {
1041
-			return $desc['id_table'];
1042
-		}
1043
-
1044
-		spip_log('table_objet(' . $type . ') calculee sans verification');
1045
-		#spip_log(debug_backtrace(),'db');
1046
-	}
1047
-
1048
-	return rtrim($type, 's') . 's'; # cas historique ne devant plus servir, sauf si $serveur=false
1016
+    if ($type) {
1017
+        $type = preg_replace(',^spip_|^id_|s$,', '', $type);
1018
+    }
1019
+    if (!strlen($type)) {
1020
+        return '';
1021
+    }
1022
+
1023
+    $surnoms = lister_tables_objets_surnoms();
1024
+    if (isset($surnoms[$type])) {
1025
+        return $surnoms[$type];
1026
+    }
1027
+
1028
+    if ($serveur !== false) {
1029
+        $t = lister_tables_spip($serveur);
1030
+        $trouver_table = charger_fonction('trouver_table', 'base');
1031
+        $typetrim = rtrim($type, 's') . 's';
1032
+        if (
1033
+            (isset($t[$typetrim]) or in_array($typetrim, $t))
1034
+            and ($desc = $trouver_table(rtrim($type, 's') . 's', $serveur))
1035
+        ) {
1036
+            return $desc['id_table'];
1037
+        } elseif (
1038
+            (isset($t[$type]) or in_array($type, $t))
1039
+            and ($desc = $trouver_table($type, $serveur))
1040
+        ) {
1041
+            return $desc['id_table'];
1042
+        }
1043
+
1044
+        spip_log('table_objet(' . $type . ') calculee sans verification');
1045
+        #spip_log(debug_backtrace(),'db');
1046
+    }
1047
+
1048
+    return rtrim($type, 's') . 's'; # cas historique ne devant plus servir, sauf si $serveur=false
1049 1049
 }
1050 1050
 
1051 1051
 /**
@@ -1066,33 +1066,33 @@  discard block
 block discarded – undo
1066 1066
  **/
1067 1067
 function table_objet_sql(string $type, string $serveur = ''): string {
1068 1068
 
1069
-	$nom = table_objet($type, $serveur);
1070
-	if (!strlen($nom)) {
1071
-		return '';
1072
-	}
1073
-	if (!isset($GLOBALS['table_des_tables']['articles'])) {
1074
-		// eviter de multiples inclusions
1075
-		include_spip('public/interfaces');
1076
-	}
1077
-	if (isset($GLOBALS['table_des_tables'][$nom])) {
1078
-		$nom = $GLOBALS['table_des_tables'][$nom];
1079
-		$nom = "spip_$nom";
1080
-	} else {
1081
-		$infos_tables = lister_tables_objets_sql();
1082
-		if (isset($infos_tables["spip_$nom"])) {
1083
-			$nom = "spip_$nom";
1084
-		} elseif ($serveur !== false) {
1085
-			$t = lister_tables_spip($serveur);
1086
-			if (isset($t[$nom]) or in_array($nom, $t)) {
1087
-				$trouver_table = charger_fonction('trouver_table', 'base');
1088
-				if ($desc = $trouver_table($nom, $serveur)) {
1089
-					return $desc['table_sql'];
1090
-				}
1091
-			}
1092
-		}
1093
-	}
1094
-
1095
-	return $nom;
1069
+    $nom = table_objet($type, $serveur);
1070
+    if (!strlen($nom)) {
1071
+        return '';
1072
+    }
1073
+    if (!isset($GLOBALS['table_des_tables']['articles'])) {
1074
+        // eviter de multiples inclusions
1075
+        include_spip('public/interfaces');
1076
+    }
1077
+    if (isset($GLOBALS['table_des_tables'][$nom])) {
1078
+        $nom = $GLOBALS['table_des_tables'][$nom];
1079
+        $nom = "spip_$nom";
1080
+    } else {
1081
+        $infos_tables = lister_tables_objets_sql();
1082
+        if (isset($infos_tables["spip_$nom"])) {
1083
+            $nom = "spip_$nom";
1084
+        } elseif ($serveur !== false) {
1085
+            $t = lister_tables_spip($serveur);
1086
+            if (isset($t[$nom]) or in_array($nom, $t)) {
1087
+                $trouver_table = charger_fonction('trouver_table', 'base');
1088
+                if ($desc = $trouver_table($nom, $serveur)) {
1089
+                    return $desc['table_sql'];
1090
+                }
1091
+            }
1092
+        }
1093
+    }
1094
+
1095
+    return $nom;
1096 1096
 }
1097 1097
 
1098 1098
 /**
@@ -1111,35 +1111,35 @@  discard block
 block discarded – undo
1111 1111
  *     Nom de la clé primaire
1112 1112
  **/
1113 1113
 function id_table_objet(string $type, string $serveur = ''): ?string {
1114
-	static $trouver_table = null;
1115
-	$type = objet_type($type, $serveur);
1116
-	if (!$type) {
1117
-		return null;
1118
-	}
1119
-	$t = table_objet($type);
1120
-	if (!$trouver_table) {
1121
-		$trouver_table = charger_fonction('trouver_table', 'base');
1122
-	}
1123
-
1124
-	$ts = lister_tables_spip($serveur);
1125
-	if (
1126
-		in_array($t, $ts)
1127
-		or in_array($t, lister_toutes_tables($serveur))
1128
-	) {
1129
-		$desc = $trouver_table($t, $serveur);
1130
-		if (isset($desc['key']['PRIMARY KEY'])) {
1131
-			return $desc['key']['PRIMARY KEY'];
1132
-		}
1133
-		if (!$desc or isset($desc['field']["id_$type"])) {
1134
-			return "id_$type";
1135
-		}
1136
-		// sinon renvoyer le premier champ de la table...
1137
-		$keys = array_keys($desc['field']);
1138
-
1139
-		return array_shift($keys);
1140
-	}
1141
-
1142
-	return "id_$type";
1114
+    static $trouver_table = null;
1115
+    $type = objet_type($type, $serveur);
1116
+    if (!$type) {
1117
+        return null;
1118
+    }
1119
+    $t = table_objet($type);
1120
+    if (!$trouver_table) {
1121
+        $trouver_table = charger_fonction('trouver_table', 'base');
1122
+    }
1123
+
1124
+    $ts = lister_tables_spip($serveur);
1125
+    if (
1126
+        in_array($t, $ts)
1127
+        or in_array($t, lister_toutes_tables($serveur))
1128
+    ) {
1129
+        $desc = $trouver_table($t, $serveur);
1130
+        if (isset($desc['key']['PRIMARY KEY'])) {
1131
+            return $desc['key']['PRIMARY KEY'];
1132
+        }
1133
+        if (!$desc or isset($desc['field']["id_$type"])) {
1134
+            return "id_$type";
1135
+        }
1136
+        // sinon renvoyer le premier champ de la table...
1137
+        $keys = array_keys($desc['field']);
1138
+
1139
+        return array_shift($keys);
1140
+    }
1141
+
1142
+    return "id_$type";
1143 1143
 }
1144 1144
 
1145 1145
 /**
@@ -1158,60 +1158,60 @@  discard block
 block discarded – undo
1158 1158
  *     Type de l'objet
1159 1159
  **/
1160 1160
 function objet_type(string $table_objet, string $serveur = ''): ?string {
1161
-	if (!$table_objet) {
1162
-		return null;
1163
-	}
1164
-	$surnoms = lister_types_surnoms();
1165
-
1166
-	// scenario de base
1167
-	// le type est decline a partir du nom de la table en enlevant le prefixe eventuel
1168
-	// et la marque du pluriel
1169
-	// on accepte id_xx en entree aussi
1170
-	$type = preg_replace(',^spip_|^id_|s$,', '', $table_objet);
1171
-	if (isset($surnoms[$type])) {
1172
-		return $surnoms[$type];
1173
-	}
1174
-
1175
-	// securite : eliminer les caracteres non \w
1176
-	$type = preg_replace(',[^\w-],', '', $type);
1177
-
1178
-	// si le type redonne bien la table c'est bon
1179
-	// oui si table_objet ressemblait deja a un type
1180
-	if (
1181
-		$type == $table_objet
1182
-		or (table_objet($type, $serveur) == $table_objet)
1183
-		or (table_objet_sql($type, $serveur) == $table_objet)
1184
-	) {
1185
-		return $type;
1186
-	}
1187
-
1188
-	// si on ne veut pas chercher en base
1189
-	if ($serveur === false) {
1190
-		return $type;
1191
-	}
1192
-
1193
-	// sinon on passe par la cle primaire id_xx pour trouver le type
1194
-	// car le s a la fin est incertain
1195
-	// notamment en cas de pluriel derogatoire
1196
-	// id_jeu/spip_jeux id_journal/spip_journaux qui necessitent tout deux
1197
-	// une declaration jeu => jeux, journal => journaux
1198
-	// dans le pipeline declarer_tables_objets_surnoms
1199
-	$trouver_table = charger_fonction('trouver_table', 'base');
1200
-	$ts = lister_tables_spip($serveur);
1201
-	$desc = false;
1202
-	if (in_array($table_objet, $ts)) {
1203
-		$desc = $trouver_table($table_objet);
1204
-	}
1205
-	if (!$desc and in_array($table_objet = table_objet($type, $serveur), $ts)) {
1206
-		$desc = $trouver_table($table_objet, $serveur);
1207
-	}
1208
-	// si le type est declare : bingo !
1209
-	if ($desc and isset($desc['type'])) {
1210
-		return $desc['type'];
1211
-	}
1212
-
1213
-	// on a fait ce qu'on a pu
1214
-	return $type;
1161
+    if (!$table_objet) {
1162
+        return null;
1163
+    }
1164
+    $surnoms = lister_types_surnoms();
1165
+
1166
+    // scenario de base
1167
+    // le type est decline a partir du nom de la table en enlevant le prefixe eventuel
1168
+    // et la marque du pluriel
1169
+    // on accepte id_xx en entree aussi
1170
+    $type = preg_replace(',^spip_|^id_|s$,', '', $table_objet);
1171
+    if (isset($surnoms[$type])) {
1172
+        return $surnoms[$type];
1173
+    }
1174
+
1175
+    // securite : eliminer les caracteres non \w
1176
+    $type = preg_replace(',[^\w-],', '', $type);
1177
+
1178
+    // si le type redonne bien la table c'est bon
1179
+    // oui si table_objet ressemblait deja a un type
1180
+    if (
1181
+        $type == $table_objet
1182
+        or (table_objet($type, $serveur) == $table_objet)
1183
+        or (table_objet_sql($type, $serveur) == $table_objet)
1184
+    ) {
1185
+        return $type;
1186
+    }
1187
+
1188
+    // si on ne veut pas chercher en base
1189
+    if ($serveur === false) {
1190
+        return $type;
1191
+    }
1192
+
1193
+    // sinon on passe par la cle primaire id_xx pour trouver le type
1194
+    // car le s a la fin est incertain
1195
+    // notamment en cas de pluriel derogatoire
1196
+    // id_jeu/spip_jeux id_journal/spip_journaux qui necessitent tout deux
1197
+    // une declaration jeu => jeux, journal => journaux
1198
+    // dans le pipeline declarer_tables_objets_surnoms
1199
+    $trouver_table = charger_fonction('trouver_table', 'base');
1200
+    $ts = lister_tables_spip($serveur);
1201
+    $desc = false;
1202
+    if (in_array($table_objet, $ts)) {
1203
+        $desc = $trouver_table($table_objet);
1204
+    }
1205
+    if (!$desc and in_array($table_objet = table_objet($type, $serveur), $ts)) {
1206
+        $desc = $trouver_table($table_objet, $serveur);
1207
+    }
1208
+    // si le type est declare : bingo !
1209
+    if ($desc and isset($desc['type'])) {
1210
+        return $desc['type'];
1211
+    }
1212
+
1213
+    // on a fait ce qu'on a pu
1214
+    return $type;
1215 1215
 }
1216 1216
 
1217 1217
 /**
@@ -1227,62 +1227,62 @@  discard block
 block discarded – undo
1227 1227
  * @return bool
1228 1228
  */
1229 1229
 function objet_test_si_publie($objet, $id_objet, $serveur = '') {
1230
-	// voir si une fonction est definie pour faire le boulot
1231
-	// elle a la priorite dans ce cas
1232
-	if ($f = charger_fonction($objet . '_test_si_publie', 'base', true)) {
1233
-		return $f($objet, $id_objet, $serveur);
1234
-	}
1235
-
1236
-	// sinon on se fie a la declaration de l'objet si presente
1237
-	$id_table = $table_objet = table_objet($objet);
1238
-	$id_table_objet = id_table_objet($objet, $serveur);
1239
-	$trouver_table = charger_fonction('trouver_table', 'base');
1240
-	if (
1241
-		$desc = $trouver_table($table_objet, $serveur)
1242
-		and isset($desc['statut'])
1243
-		and $desc['statut']
1244
-	) {
1245
-		$boucle = new Boucle();
1246
-		$boucle->show = $desc;
1247
-		$boucle->nom = 'objet_test_si_publie';
1248
-		$boucle->id_boucle = $id_table;
1249
-		$boucle->id_table = $id_table;
1250
-		$boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
1251
-		$boucle->sql_serveur = $serveur;
1252
-		$boucle->select[] = $id_table_objet;
1253
-		$boucle->from[$table_objet] = table_objet_sql($objet, $serveur);
1254
-		$boucle->where[] = $id_table . '.' . $id_table_objet . '=' . intval($id_objet);
1255
-
1256
-		$boucle->descr['nom'] = 'objet_test_si_publie'; // eviter notice php
1257
-		$boucle->descr['sourcefile'] = 'internal';
1258
-		$boucle->descr['gram'] = 'html';
1259
-
1260
-		include_spip('public/compiler');
1261
-		include_spip('public/composer');
1262
-		instituer_boucle($boucle, false, true);
1263
-		$res = calculer_select(
1264
-			$boucle->select,
1265
-			$boucle->from,
1266
-			$boucle->from_type,
1267
-			$boucle->where,
1268
-			$boucle->join,
1269
-			$boucle->group,
1270
-			$boucle->order,
1271
-			$boucle->limit,
1272
-			$boucle->having,
1273
-			$table_objet,
1274
-			$id_table,
1275
-			$serveur
1276
-		);
1277
-		if (sql_fetch($res)) {
1278
-			return true;
1279
-		}
1280
-
1281
-		return false;
1282
-	}
1283
-
1284
-	// si pas d'info statut ni de fonction : l'objet est publie
1285
-	return true;
1230
+    // voir si une fonction est definie pour faire le boulot
1231
+    // elle a la priorite dans ce cas
1232
+    if ($f = charger_fonction($objet . '_test_si_publie', 'base', true)) {
1233
+        return $f($objet, $id_objet, $serveur);
1234
+    }
1235
+
1236
+    // sinon on se fie a la declaration de l'objet si presente
1237
+    $id_table = $table_objet = table_objet($objet);
1238
+    $id_table_objet = id_table_objet($objet, $serveur);
1239
+    $trouver_table = charger_fonction('trouver_table', 'base');
1240
+    if (
1241
+        $desc = $trouver_table($table_objet, $serveur)
1242
+        and isset($desc['statut'])
1243
+        and $desc['statut']
1244
+    ) {
1245
+        $boucle = new Boucle();
1246
+        $boucle->show = $desc;
1247
+        $boucle->nom = 'objet_test_si_publie';
1248
+        $boucle->id_boucle = $id_table;
1249
+        $boucle->id_table = $id_table;
1250
+        $boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
1251
+        $boucle->sql_serveur = $serveur;
1252
+        $boucle->select[] = $id_table_objet;
1253
+        $boucle->from[$table_objet] = table_objet_sql($objet, $serveur);
1254
+        $boucle->where[] = $id_table . '.' . $id_table_objet . '=' . intval($id_objet);
1255
+
1256
+        $boucle->descr['nom'] = 'objet_test_si_publie'; // eviter notice php
1257
+        $boucle->descr['sourcefile'] = 'internal';
1258
+        $boucle->descr['gram'] = 'html';
1259
+
1260
+        include_spip('public/compiler');
1261
+        include_spip('public/composer');
1262
+        instituer_boucle($boucle, false, true);
1263
+        $res = calculer_select(
1264
+            $boucle->select,
1265
+            $boucle->from,
1266
+            $boucle->from_type,
1267
+            $boucle->where,
1268
+            $boucle->join,
1269
+            $boucle->group,
1270
+            $boucle->order,
1271
+            $boucle->limit,
1272
+            $boucle->having,
1273
+            $table_objet,
1274
+            $id_table,
1275
+            $serveur
1276
+        );
1277
+        if (sql_fetch($res)) {
1278
+            return true;
1279
+        }
1280
+
1281
+        return false;
1282
+    }
1283
+
1284
+    // si pas d'info statut ni de fonction : l'objet est publie
1285
+    return true;
1286 1286
 }
1287 1287
 
1288 1288
 
@@ -1317,124 +1317,124 @@  discard block
 block discarded – undo
1317 1317
  *     Retourne un tableau décrivant les parents trouvés
1318 1318
  */
1319 1319
 function objet_lister_parents($objet, $id_objet, $parent_direct_seulement = false) {
1320
-	$parents = [];
1321
-
1322
-	// Si on trouve une ou des méthodes de parent
1323
-	if ($parent_methodes = objet_type_decrire_infos_parents($objet)) {
1324
-		// On identifie les informations sur l'objet source dont on cherche le parent.
1325
-		include_spip('base/abstract_sql');
1326
-		$table_objet = table_objet_sql($objet);
1327
-		$cle_objet = id_table_objet($objet);
1328
-		$id_objet = intval($id_objet);
1329
-
1330
-		// On teste chacun méthode dans l'ordre, et dès qu'on a trouvé un parent on s'arrête
1331
-		foreach ($parent_methodes as $parent_methode) {
1332
-			// Champ identifiant le parent (id et éventuellement le type)
1333
-			// -- cette identification ne dépend pas du fait que le parent soit stocké dans une table de différente
1334
-			//    de celle de l'objet source
1335
-			$select = [];
1336
-			if (isset($parent_methode['champ'])) {
1337
-				$select[] = $parent_methode['champ'];
1338
-			}
1339
-			if (isset($parent_methode['champ_type'])) {
1340
-				$select[] = $parent_methode['champ_type'];
1341
-			}
1342
-
1343
-			// Détermination de la table du parent et des conditions sur l'objet source et le parent.
1344
-			$condition_objet_invalide = false;
1345
-			$where = [];
1346
-			if (!isset($parent_methode['table'])) {
1347
-				// Le parent est stocké dans la même table que l'objet source :
1348
-				// -- toutes les conditions s'appliquent à la table source.
1349
-				$table = $table_objet;
1350
-				$where = ["$cle_objet = $id_objet"];
1351
-				// -- Condition supplémentaire sur la détection du parent
1352
-				if (isset($parent_methode['condition'])) {
1353
-					$where[] = $parent_methode['condition'];
1354
-				}
1355
-			} elseif (!$parent_direct_seulement) {
1356
-				// Le parent est stocké dans une table différente de l'objet source.
1357
-				// -- on vérifie d'emblée si il y a une condition sur l'objet source et si celle-ci est vérifiée
1358
-				//    Si non, on peut arrêter le traitement.
1359
-				if (isset($parent_methode['condition'])) {
1360
-					$where = [
1361
-						"$cle_objet = $id_objet",
1362
-						$parent_methode['condition']
1363
-					];
1364
-					if (!sql_countsel($table_objet, $where)) {
1365
-						$condition_objet_invalide = true;
1366
-					}
1367
-				}
1368
-
1369
-				// Si pas de condition sur l'objet source ou que la condition est vérifiée, on peut construire
1370
-				// la requête sur la table qui accueille le parent.
1371
-				if (!$condition_objet_invalide) {
1372
-					$table = $parent_methode['table'];
1373
-					// On construit les conditions en fonction de l'identification de l'objet source
1374
-					$where = [];
1375
-					// -- si le champ_source de l'id n'est pas précisé c'est qu'il est déjà connu et donc que c'est
1376
-					//    le même que celui de l'objet source.
1377
-					$where[] = isset($parent_methode['source_champ'])
1378
-						? "{$parent_methode['source_champ']} = $id_objet"
1379
-						: "$cle_objet = $id_objet";
1380
-					if (isset($parent_methode['source_champ_type'])) {
1381
-						$where[] = "{$parent_methode['source_champ_type']} = " . sql_quote($objet);
1382
-					}
1383
-					// -- Condition supplémentaire sur la détection du parent
1384
-					if (isset($parent_methode['table_condition'])) {
1385
-						$where[] = $parent_methode['table_condition'];
1386
-					}
1387
-				}
1388
-			}
1389
-
1390
-			// On lance la requête de récupération du parent
1391
-			$is_table_lien = (strpos($table, '_liens') !== false and substr($table, -6) === '_liens');
1392
-			if (
1393
-				!$condition_objet_invalide
1394
-				and $where
1395
-				and ($lignes = sql_allfetsel($is_table_lien ? '*' : $select, $table, $where))
1396
-			) {
1397
-				foreach ($lignes as $ligne) {
1398
-					// Si le type est fixe
1399
-					if (isset($parent_methode['type'])) {
1400
-						$parent = [
1401
-							'objet' 	=> $parent_methode['type'],
1402
-							'id_objet'	=> intval($ligne[$parent_methode['champ']]),
1403
-							'champ' 	=> $parent_methode['champ'],
1404
-							'table'    => $table,
1405
-						];
1406
-					}
1407
-					elseif (isset($parent_methode['champ_type'])) {
1408
-						$parent = [
1409
-							'objet' 	 => $ligne[$parent_methode['champ_type']],
1410
-							'id_objet' 	 => intval($ligne[$parent_methode['champ']]),
1411
-							'champ' 	 => $parent_methode['champ'],
1412
-							'champ_type' => $parent_methode['champ_type'],
1413
-							'table'    => $table,
1414
-						];
1415
-					}
1416
-					if ($is_table_lien) {
1417
-						$parent['lien'] = $ligne;
1418
-					}
1419
-					$parents[] = $parent;
1420
-				}
1421
-			}
1422
-		}
1423
-	}
1424
-
1425
-	// On passe par un pipeline avant de retourner
1426
-	$parents = pipeline(
1427
-		'objet_lister_parents',
1428
-		[
1429
-			'args' => [
1430
-				'objet' => $objet,
1431
-				'id_objet' => $id_objet,
1432
-			],
1433
-			'data' => $parents,
1434
-		]
1435
-	);
1436
-
1437
-	return $parents;
1320
+    $parents = [];
1321
+
1322
+    // Si on trouve une ou des méthodes de parent
1323
+    if ($parent_methodes = objet_type_decrire_infos_parents($objet)) {
1324
+        // On identifie les informations sur l'objet source dont on cherche le parent.
1325
+        include_spip('base/abstract_sql');
1326
+        $table_objet = table_objet_sql($objet);
1327
+        $cle_objet = id_table_objet($objet);
1328
+        $id_objet = intval($id_objet);
1329
+
1330
+        // On teste chacun méthode dans l'ordre, et dès qu'on a trouvé un parent on s'arrête
1331
+        foreach ($parent_methodes as $parent_methode) {
1332
+            // Champ identifiant le parent (id et éventuellement le type)
1333
+            // -- cette identification ne dépend pas du fait que le parent soit stocké dans une table de différente
1334
+            //    de celle de l'objet source
1335
+            $select = [];
1336
+            if (isset($parent_methode['champ'])) {
1337
+                $select[] = $parent_methode['champ'];
1338
+            }
1339
+            if (isset($parent_methode['champ_type'])) {
1340
+                $select[] = $parent_methode['champ_type'];
1341
+            }
1342
+
1343
+            // Détermination de la table du parent et des conditions sur l'objet source et le parent.
1344
+            $condition_objet_invalide = false;
1345
+            $where = [];
1346
+            if (!isset($parent_methode['table'])) {
1347
+                // Le parent est stocké dans la même table que l'objet source :
1348
+                // -- toutes les conditions s'appliquent à la table source.
1349
+                $table = $table_objet;
1350
+                $where = ["$cle_objet = $id_objet"];
1351
+                // -- Condition supplémentaire sur la détection du parent
1352
+                if (isset($parent_methode['condition'])) {
1353
+                    $where[] = $parent_methode['condition'];
1354
+                }
1355
+            } elseif (!$parent_direct_seulement) {
1356
+                // Le parent est stocké dans une table différente de l'objet source.
1357
+                // -- on vérifie d'emblée si il y a une condition sur l'objet source et si celle-ci est vérifiée
1358
+                //    Si non, on peut arrêter le traitement.
1359
+                if (isset($parent_methode['condition'])) {
1360
+                    $where = [
1361
+                        "$cle_objet = $id_objet",
1362
+                        $parent_methode['condition']
1363
+                    ];
1364
+                    if (!sql_countsel($table_objet, $where)) {
1365
+                        $condition_objet_invalide = true;
1366
+                    }
1367
+                }
1368
+
1369
+                // Si pas de condition sur l'objet source ou que la condition est vérifiée, on peut construire
1370
+                // la requête sur la table qui accueille le parent.
1371
+                if (!$condition_objet_invalide) {
1372
+                    $table = $parent_methode['table'];
1373
+                    // On construit les conditions en fonction de l'identification de l'objet source
1374
+                    $where = [];
1375
+                    // -- si le champ_source de l'id n'est pas précisé c'est qu'il est déjà connu et donc que c'est
1376
+                    //    le même que celui de l'objet source.
1377
+                    $where[] = isset($parent_methode['source_champ'])
1378
+                        ? "{$parent_methode['source_champ']} = $id_objet"
1379
+                        : "$cle_objet = $id_objet";
1380
+                    if (isset($parent_methode['source_champ_type'])) {
1381
+                        $where[] = "{$parent_methode['source_champ_type']} = " . sql_quote($objet);
1382
+                    }
1383
+                    // -- Condition supplémentaire sur la détection du parent
1384
+                    if (isset($parent_methode['table_condition'])) {
1385
+                        $where[] = $parent_methode['table_condition'];
1386
+                    }
1387
+                }
1388
+            }
1389
+
1390
+            // On lance la requête de récupération du parent
1391
+            $is_table_lien = (strpos($table, '_liens') !== false and substr($table, -6) === '_liens');
1392
+            if (
1393
+                !$condition_objet_invalide
1394
+                and $where
1395
+                and ($lignes = sql_allfetsel($is_table_lien ? '*' : $select, $table, $where))
1396
+            ) {
1397
+                foreach ($lignes as $ligne) {
1398
+                    // Si le type est fixe
1399
+                    if (isset($parent_methode['type'])) {
1400
+                        $parent = [
1401
+                            'objet' 	=> $parent_methode['type'],
1402
+                            'id_objet'	=> intval($ligne[$parent_methode['champ']]),
1403
+                            'champ' 	=> $parent_methode['champ'],
1404
+                            'table'    => $table,
1405
+                        ];
1406
+                    }
1407
+                    elseif (isset($parent_methode['champ_type'])) {
1408
+                        $parent = [
1409
+                            'objet' 	 => $ligne[$parent_methode['champ_type']],
1410
+                            'id_objet' 	 => intval($ligne[$parent_methode['champ']]),
1411
+                            'champ' 	 => $parent_methode['champ'],
1412
+                            'champ_type' => $parent_methode['champ_type'],
1413
+                            'table'    => $table,
1414
+                        ];
1415
+                    }
1416
+                    if ($is_table_lien) {
1417
+                        $parent['lien'] = $ligne;
1418
+                    }
1419
+                    $parents[] = $parent;
1420
+                }
1421
+            }
1422
+        }
1423
+    }
1424
+
1425
+    // On passe par un pipeline avant de retourner
1426
+    $parents = pipeline(
1427
+        'objet_lister_parents',
1428
+        [
1429
+            'args' => [
1430
+                'objet' => $objet,
1431
+                'id_objet' => $id_objet,
1432
+            ],
1433
+            'data' => $parents,
1434
+        ]
1435
+    );
1436
+
1437
+    return $parents;
1438 1438
 }
1439 1439
 
1440 1440
 /**
@@ -1446,17 +1446,17 @@  discard block
 block discarded – undo
1446 1446
  * @return array
1447 1447
  */
1448 1448
 function objet_lister_parents_par_type($objet, $id_objet) {
1449
-	$parents = objet_lister_parents($objet, $id_objet);
1449
+    $parents = objet_lister_parents($objet, $id_objet);
1450 1450
 
1451
-	$parents_par_type = [];
1452
-	foreach ($parents as $parent) {
1453
-		if (!isset($parents_par_type[$parent['objet']])) {
1454
-			$parents_par_type[$parent['objet']] = [];
1455
-		}
1456
-		$parents_par_type[$parent['objet']][] = $parent['id_objet'];
1457
-	}
1451
+    $parents_par_type = [];
1452
+    foreach ($parents as $parent) {
1453
+        if (!isset($parents_par_type[$parent['objet']])) {
1454
+            $parents_par_type[$parent['objet']] = [];
1455
+        }
1456
+        $parents_par_type[$parent['objet']][] = $parent['id_objet'];
1457
+    }
1458 1458
 
1459
-	return $parents_par_type;
1459
+    return $parents_par_type;
1460 1460
 }
1461 1461
 
1462 1462
 
@@ -1489,85 +1489,85 @@  discard block
 block discarded – undo
1489 1489
  *     Retourne un tableau de tableaux, avec comme clés les types des objets, et dans chacun un tableau des identifiants trouvés
1490 1490
  */
1491 1491
 function objet_lister_enfants($objet, $id_objet) {
1492
-	$enfants = [];
1493
-
1494
-	// Si on trouve des types d'enfants et leurs méthodes
1495
-	if ($enfants_methodes = objet_type_decrire_infos_enfants($objet)) {
1496
-		include_spip('base/abstract_sql');
1497
-		$id_objet = intval($id_objet);
1498
-
1499
-		// On parcourt tous les types d'enfants trouvés
1500
-		foreach ($enfants_methodes as $objet_enfant => $_methode_parent) {
1501
-			// On construit les conditions d'identification du parent
1502
-			$where = [];
1503
-			// -- L'identifiant du parent
1504
-			if (isset($_methode_parent['champ'])) {
1505
-				$where[] = $_methode_parent['champ'] . ' = ' . $id_objet;
1506
-			}
1507
-			// -- Si le parent est variable
1508
-			if (isset($_methode_parent['champ_type'])) {
1509
-				$where[] = $_methode_parent['champ_type'] . ' = ' . sql_quote($objet);
1510
-			}
1511
-
1512
-			// On détermine la table, le champ id des enfants et on complète éventuellement les conditions
1513
-			if (!isset($_methode_parent['table'])) {
1514
-				// Les enfants sont stockés dans la même table que l'objet parent :
1515
-				$table_enfant = table_objet_sql($objet_enfant);
1516
-				$cle_objet_enfant = id_table_objet($objet_enfant);
1517
-
1518
-				// S'il y a une condition supplémentaire
1519
-				if (isset($_methode_parent['condition'])) {
1520
-					$where[] = $_methode_parent['condition'];
1521
-				}
1522
-			} else {
1523
-				// Les enfants sont stockés dans une table différente de l'objet parent.
1524
-				$table_enfant = $_methode_parent['table'];
1525
-				$cle_objet_enfant = $_methode_parent['source_champ'] ?? id_table_objet($objet_enfant);
1526
-
1527
-				// S'il y a une condition supplémentaire
1528
-				if (isset($_methode_parent['table_condition'])) {
1529
-					$where[] = $_methode_parent['table_condition'];
1530
-				}
1531
-			}
1532
-
1533
-			// On lance la requête
1534
-			$is_table_lien = (strpos($table_enfant, '_liens') !== false and substr($table_enfant, -6) === '_liens');
1535
-			if ($rows = sql_allfetsel($is_table_lien ? '*' : $cle_objet_enfant, $table_enfant, $where)) {
1536
-				$enfant = [
1537
-					'objet' => $objet_enfant,
1538
-					'id_objet' => 0,
1539
-					'table' => $table_enfant
1540
-				];
1541
-				if (isset($_methode_parent['champ'])) {
1542
-					$enfant['champ'] = $_methode_parent['champ'];
1543
-				}
1544
-				if (isset($_methode_parent['champ_type'])) {
1545
-					$enfant['champ_type'] = $_methode_parent['champ_type'];
1546
-				}
1547
-				foreach ($rows as $row) {
1548
-					$enfant['id_objet'] = intval($row[$cle_objet_enfant]);
1549
-					if ($is_table_lien) {
1550
-						$enfant['lien'] = $row;
1551
-					}
1552
-					$enfants[] = $enfant;
1553
-				}
1554
-			}
1555
-		}
1556
-	}
1557
-
1558
-	// On passe par un pipeline avant de retourner
1559
-	$enfants = pipeline(
1560
-		'objet_lister_enfants',
1561
-		[
1562
-			'args' => [
1563
-				'objet' => $objet,
1564
-				'id_objet' => $id_objet,
1565
-			],
1566
-			'data' => $enfants,
1567
-		]
1568
-	);
1569
-
1570
-	return $enfants;
1492
+    $enfants = [];
1493
+
1494
+    // Si on trouve des types d'enfants et leurs méthodes
1495
+    if ($enfants_methodes = objet_type_decrire_infos_enfants($objet)) {
1496
+        include_spip('base/abstract_sql');
1497
+        $id_objet = intval($id_objet);
1498
+
1499
+        // On parcourt tous les types d'enfants trouvés
1500
+        foreach ($enfants_methodes as $objet_enfant => $_methode_parent) {
1501
+            // On construit les conditions d'identification du parent
1502
+            $where = [];
1503
+            // -- L'identifiant du parent
1504
+            if (isset($_methode_parent['champ'])) {
1505
+                $where[] = $_methode_parent['champ'] . ' = ' . $id_objet;
1506
+            }
1507
+            // -- Si le parent est variable
1508
+            if (isset($_methode_parent['champ_type'])) {
1509
+                $where[] = $_methode_parent['champ_type'] . ' = ' . sql_quote($objet);
1510
+            }
1511
+
1512
+            // On détermine la table, le champ id des enfants et on complète éventuellement les conditions
1513
+            if (!isset($_methode_parent['table'])) {
1514
+                // Les enfants sont stockés dans la même table que l'objet parent :
1515
+                $table_enfant = table_objet_sql($objet_enfant);
1516
+                $cle_objet_enfant = id_table_objet($objet_enfant);
1517
+
1518
+                // S'il y a une condition supplémentaire
1519
+                if (isset($_methode_parent['condition'])) {
1520
+                    $where[] = $_methode_parent['condition'];
1521
+                }
1522
+            } else {
1523
+                // Les enfants sont stockés dans une table différente de l'objet parent.
1524
+                $table_enfant = $_methode_parent['table'];
1525
+                $cle_objet_enfant = $_methode_parent['source_champ'] ?? id_table_objet($objet_enfant);
1526
+
1527
+                // S'il y a une condition supplémentaire
1528
+                if (isset($_methode_parent['table_condition'])) {
1529
+                    $where[] = $_methode_parent['table_condition'];
1530
+                }
1531
+            }
1532
+
1533
+            // On lance la requête
1534
+            $is_table_lien = (strpos($table_enfant, '_liens') !== false and substr($table_enfant, -6) === '_liens');
1535
+            if ($rows = sql_allfetsel($is_table_lien ? '*' : $cle_objet_enfant, $table_enfant, $where)) {
1536
+                $enfant = [
1537
+                    'objet' => $objet_enfant,
1538
+                    'id_objet' => 0,
1539
+                    'table' => $table_enfant
1540
+                ];
1541
+                if (isset($_methode_parent['champ'])) {
1542
+                    $enfant['champ'] = $_methode_parent['champ'];
1543
+                }
1544
+                if (isset($_methode_parent['champ_type'])) {
1545
+                    $enfant['champ_type'] = $_methode_parent['champ_type'];
1546
+                }
1547
+                foreach ($rows as $row) {
1548
+                    $enfant['id_objet'] = intval($row[$cle_objet_enfant]);
1549
+                    if ($is_table_lien) {
1550
+                        $enfant['lien'] = $row;
1551
+                    }
1552
+                    $enfants[] = $enfant;
1553
+                }
1554
+            }
1555
+        }
1556
+    }
1557
+
1558
+    // On passe par un pipeline avant de retourner
1559
+    $enfants = pipeline(
1560
+        'objet_lister_enfants',
1561
+        [
1562
+            'args' => [
1563
+                'objet' => $objet,
1564
+                'id_objet' => $id_objet,
1565
+            ],
1566
+            'data' => $enfants,
1567
+        ]
1568
+    );
1569
+
1570
+    return $enfants;
1571 1571
 }
1572 1572
 
1573 1573
 /**
@@ -1579,17 +1579,17 @@  discard block
 block discarded – undo
1579 1579
  * @return array
1580 1580
  */
1581 1581
 function objet_lister_enfants_par_type($objet, $id_objet) {
1582
-	$enfants = objet_lister_enfants($objet, $id_objet);
1582
+    $enfants = objet_lister_enfants($objet, $id_objet);
1583 1583
 
1584
-	$enfants_par_type = [];
1585
-	foreach ($enfants as $enfant) {
1586
-		if (!isset($enfants_par_type[$enfant['objet']])) {
1587
-			$enfants_par_type[$enfant['objet']] = [];
1588
-		}
1589
-		$enfants_par_type[$enfant['objet']][] = $enfant['id_objet'];
1590
-	}
1584
+    $enfants_par_type = [];
1585
+    foreach ($enfants as $enfant) {
1586
+        if (!isset($enfants_par_type[$enfant['objet']])) {
1587
+            $enfants_par_type[$enfant['objet']] = [];
1588
+        }
1589
+        $enfants_par_type[$enfant['objet']][] = $enfant['id_objet'];
1590
+    }
1591 1591
 
1592
-	return $enfants_par_type;
1592
+    return $enfants_par_type;
1593 1593
 }
1594 1594
 
1595 1595
 /**
@@ -1601,35 +1601,35 @@  discard block
 block discarded – undo
1601 1601
  *     Retourne un tableau de tableau contenant les informations de type et de champ pour trouver le parent ou false sinon
1602 1602
  */
1603 1603
 function objet_type_decrire_infos_parents($objet) {
1604
-	static $parents = [];
1605
-
1606
-	// Si on ne l'a pas encore cherché pour cet objet
1607
-	if (!isset($parents[$objet])) {
1608
-		$parents[$objet] = false;
1609
-		$table = table_objet_sql($objet);
1610
-
1611
-		// Si on trouve bien la description de cet objet
1612
-		if ($infos = lister_tables_objets_sql($table)) {
1613
-			if (isset($infos['parent']) and is_array($infos['parent'])) {
1614
-				// S'il y a une description explicite de parent, c'est prioritaire
1615
-				// -- on traite les cas où il y a une ou plusieurs description mais on renvoie toujours un tableau
1616
-				//    de description
1617
-				if (!isset($infos['parent'][0])) {
1618
-					$parents[$objet] = [$infos['parent']];
1619
-				} else {
1620
-					$parents[$objet] = $infos['parent'];
1621
-				}
1622
-			} elseif (isset($infos['field']['id_rubrique'])) {
1623
-				// Sinon on cherche des cas courants connus magiquement, à commencer par id_rubrique
1624
-				$parents[$objet] = [['type' => 'rubrique', 'champ' => 'id_rubrique']];
1625
-			} elseif (isset($infos['field']['id_parent'])) {
1626
-				// Sinon on cherche un champ id_parent, ce qui signifie que l'objet est parent de lui-même
1627
-				$parents[$objet] = [['type' => $objet, 'champ' => 'id_parent']];
1628
-			}
1629
-		}
1630
-	}
1631
-
1632
-	return $parents[$objet];
1604
+    static $parents = [];
1605
+
1606
+    // Si on ne l'a pas encore cherché pour cet objet
1607
+    if (!isset($parents[$objet])) {
1608
+        $parents[$objet] = false;
1609
+        $table = table_objet_sql($objet);
1610
+
1611
+        // Si on trouve bien la description de cet objet
1612
+        if ($infos = lister_tables_objets_sql($table)) {
1613
+            if (isset($infos['parent']) and is_array($infos['parent'])) {
1614
+                // S'il y a une description explicite de parent, c'est prioritaire
1615
+                // -- on traite les cas où il y a une ou plusieurs description mais on renvoie toujours un tableau
1616
+                //    de description
1617
+                if (!isset($infos['parent'][0])) {
1618
+                    $parents[$objet] = [$infos['parent']];
1619
+                } else {
1620
+                    $parents[$objet] = $infos['parent'];
1621
+                }
1622
+            } elseif (isset($infos['field']['id_rubrique'])) {
1623
+                // Sinon on cherche des cas courants connus magiquement, à commencer par id_rubrique
1624
+                $parents[$objet] = [['type' => 'rubrique', 'champ' => 'id_rubrique']];
1625
+            } elseif (isset($infos['field']['id_parent'])) {
1626
+                // Sinon on cherche un champ id_parent, ce qui signifie que l'objet est parent de lui-même
1627
+                $parents[$objet] = [['type' => $objet, 'champ' => 'id_parent']];
1628
+            }
1629
+        }
1630
+    }
1631
+
1632
+    return $parents[$objet];
1633 1633
 }
1634 1634
 
1635 1635
 /**
@@ -1641,36 +1641,36 @@  discard block
 block discarded – undo
1641 1641
  *     Retourne un tableau de tableaux contenant chacun les informations d'un type d'enfant
1642 1642
  */
1643 1643
 function objet_type_decrire_infos_enfants($objet) {
1644
-	static $enfants = [];
1645
-
1646
-	// Si on a déjà fait la recherche pour ce type d'objet
1647
-	if (!isset($enfants[$objet])) {
1648
-		$enfants[$objet] = [];
1649
-		$tables = lister_tables_objets_sql();
1650
-
1651
-		// On parcourt toutes les tables d'objet, et on cherche si chacune peut être enfant
1652
-		foreach ($tables as $table => $infos) {
1653
-			$objet_enfant = objet_type($table);
1654
-
1655
-			// On ne va pas refaire les tests des différents cas, on réutilise
1656
-			if ($parent_methodes = objet_type_decrire_infos_parents($objet_enfant)) {
1657
-				// On parcourt les différents cas possible, si certains peuvent concerner l'objet demandé
1658
-				foreach ($parent_methodes as $parent_methode) {
1659
-					// Si la méthode qu'on teste n'exclut pas le parent demandé
1660
-					if (!isset($parent_methode['exclus']) or !in_array($objet, $parent_methode['exclus'])) {
1661
-						// Si le type du parent est fixe et directement l'objet demandé
1662
-						if (isset($parent_methode['type']) and isset($parent_methode['champ']) and $parent_methode['type'] == $objet) {
1663
-							$enfants[$objet][$objet_enfant] = $parent_methode;
1664
-						}
1665
-						// Si le type est variable, alors l'objet demandé peut forcément être parent
1666
-						elseif (isset($parent_methode['champ_type']) and isset($parent_methode['champ'])) {
1667
-							$enfants[$objet][$objet_enfant] = $parent_methode;
1668
-						}
1669
-					}
1670
-				}
1671
-			}
1672
-		}
1673
-	}
1674
-
1675
-	return $enfants[$objet];
1644
+    static $enfants = [];
1645
+
1646
+    // Si on a déjà fait la recherche pour ce type d'objet
1647
+    if (!isset($enfants[$objet])) {
1648
+        $enfants[$objet] = [];
1649
+        $tables = lister_tables_objets_sql();
1650
+
1651
+        // On parcourt toutes les tables d'objet, et on cherche si chacune peut être enfant
1652
+        foreach ($tables as $table => $infos) {
1653
+            $objet_enfant = objet_type($table);
1654
+
1655
+            // On ne va pas refaire les tests des différents cas, on réutilise
1656
+            if ($parent_methodes = objet_type_decrire_infos_parents($objet_enfant)) {
1657
+                // On parcourt les différents cas possible, si certains peuvent concerner l'objet demandé
1658
+                foreach ($parent_methodes as $parent_methode) {
1659
+                    // Si la méthode qu'on teste n'exclut pas le parent demandé
1660
+                    if (!isset($parent_methode['exclus']) or !in_array($objet, $parent_methode['exclus'])) {
1661
+                        // Si le type du parent est fixe et directement l'objet demandé
1662
+                        if (isset($parent_methode['type']) and isset($parent_methode['champ']) and $parent_methode['type'] == $objet) {
1663
+                            $enfants[$objet][$objet_enfant] = $parent_methode;
1664
+                        }
1665
+                        // Si le type est variable, alors l'objet demandé peut forcément être parent
1666
+                        elseif (isset($parent_methode['champ_type']) and isset($parent_methode['champ'])) {
1667
+                            $enfants[$objet][$objet_enfant] = $parent_methode;
1668
+                        }
1669
+                    }
1670
+                }
1671
+            }
1672
+        }
1673
+    }
1674
+
1675
+    return $enfants[$objet];
1676 1676
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 		$infos['url_voir'] = $infos['type'];
707 707
 	}
708 708
 	if (!isset($infos['url_edit'])) {
709
-		$infos['url_edit'] = $infos['url_voir'] . ($infos['editable'] ? '_edit' : '');
709
+		$infos['url_edit'] = $infos['url_voir'].($infos['editable'] ? '_edit' : '');
710 710
 	}
711 711
 	if (!isset($infos['icone_objet'])) {
712 712
 		$infos['icone_objet'] = $infos['type'];
@@ -718,48 +718,48 @@  discard block
 block discarded – undo
718 718
 		$infos['texte_retour'] = 'icone_retour';
719 719
 	}
720 720
 	if (!isset($infos['texte_modifier'])) {
721
-		$infos['texte_modifier'] = $infos['type'] . ':' . 'icone_modifier_' . $infos['type'];
721
+		$infos['texte_modifier'] = $infos['type'].':'.'icone_modifier_'.$infos['type'];
722 722
 	}
723 723
 	if (!isset($infos['texte_creer'])) {
724
-		$infos['texte_creer'] = $infos['type'] . ':' . 'icone_creer_' . $infos['type'];
724
+		$infos['texte_creer'] = $infos['type'].':'.'icone_creer_'.$infos['type'];
725 725
 	}
726 726
 	if (!isset($infos['texte_creer_associer'])) {
727
-		$infos['texte_creer_associer'] = $infos['type'] . ':' . 'texte_creer_associer_' . $infos['type'];
727
+		$infos['texte_creer_associer'] = $infos['type'].':'.'texte_creer_associer_'.$infos['type'];
728 728
 	}
729 729
 	if (!isset($infos['texte_ajouter'])) {
730 730
 		// Ajouter un X
731
-		$infos['texte_ajouter'] = $infos['type'] . ':' . 'texte_ajouter_' . $infos['type'];
731
+		$infos['texte_ajouter'] = $infos['type'].':'.'texte_ajouter_'.$infos['type'];
732 732
 	}
733 733
 	if (!isset($infos['texte_objets'])) {
734
-		$infos['texte_objets'] = $infos['type'] . ':' . 'titre_' . $infos['table_objet'];
734
+		$infos['texte_objets'] = $infos['type'].':'.'titre_'.$infos['table_objet'];
735 735
 	}
736 736
 	if (!isset($infos['texte_objet'])) {
737
-		$infos['texte_objet'] = $infos['type'] . ':' . 'titre_' . $infos['type'];
737
+		$infos['texte_objet'] = $infos['type'].':'.'titre_'.$infos['type'];
738 738
 	}
739 739
 	if (!isset($infos['texte_logo_objet'])) {
740 740
 		// objet:titre_logo_objet "Logo de ce X"
741
-		$infos['texte_logo_objet'] = $infos['type'] . ':' . 'titre_logo_' . $infos['type'];
741
+		$infos['texte_logo_objet'] = $infos['type'].':'.'titre_logo_'.$infos['type'];
742 742
 	}
743 743
 	if (!isset($infos['texte_langue_objet'])) {
744 744
 		// objet:texte_langue_objet "Langue de ce X"
745
-		$infos['texte_langue_objet'] = $infos['type'] . ':' . 'titre_langue_' . $infos['type'];
745
+		$infos['texte_langue_objet'] = $infos['type'].':'.'titre_langue_'.$infos['type'];
746 746
 	}
747 747
 	if (!isset($infos['texte_definir_comme_traduction_objet'])) {
748 748
 		// "Ce X est une traduction du X numéro :"
749
-		$infos['texte_definir_comme_traduction_objet'] = $infos['type'] . ':' . 'texte_definir_comme_traduction_' . $infos['type'];
749
+		$infos['texte_definir_comme_traduction_objet'] = $infos['type'].':'.'texte_definir_comme_traduction_'.$infos['type'];
750 750
 	}
751 751
 
752 752
 	// objet:info_aucun_objet
753 753
 	if (!isset($infos['info_aucun_objet'])) {
754
-		$infos['info_aucun_objet'] = $infos['type'] . ':' . 'info_aucun_' . $infos['type'];
754
+		$infos['info_aucun_objet'] = $infos['type'].':'.'info_aucun_'.$infos['type'];
755 755
 	}
756 756
 	// objet:info_1_objet
757 757
 	if (!isset($infos['info_1_objet'])) {
758
-		$infos['info_1_objet'] = $infos['type'] . ':' . 'info_1_' . $infos['type'];
758
+		$infos['info_1_objet'] = $infos['type'].':'.'info_1_'.$infos['type'];
759 759
 	}
760 760
 	// objet:info_nb_objets
761 761
 	if (!isset($infos['info_nb_objets'])) {
762
-		$infos['info_nb_objets'] = $infos['type'] . ':' . 'info_nb_' . $infos['table_objet'];
762
+		$infos['info_nb_objets'] = $infos['type'].':'.'info_nb_'.$infos['table_objet'];
763 763
 	}
764 764
 
765 765
 	if (!isset($infos['champs_editables'])) {
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 		}
960 960
 		$ts = sql_alltable(null, $serveur); // toutes les tables "spip_" (ou prefixe perso)
961 961
 		$connexion = $GLOBALS['connexions'][$serveur ?: 0];
962
-		$spip = $connexion['prefixe'] . '_';
962
+		$spip = $connexion['prefixe'].'_';
963 963
 		foreach ($ts as $t) {
964 964
 			$t = substr($t, strlen($spip));
965 965
 			$tables[$serveur]["spip_$t"] = $t;
@@ -1028,10 +1028,10 @@  discard block
 block discarded – undo
1028 1028
 	if ($serveur !== false) {
1029 1029
 		$t = lister_tables_spip($serveur);
1030 1030
 		$trouver_table = charger_fonction('trouver_table', 'base');
1031
-		$typetrim = rtrim($type, 's') . 's';
1031
+		$typetrim = rtrim($type, 's').'s';
1032 1032
 		if (
1033 1033
 			(isset($t[$typetrim]) or in_array($typetrim, $t))
1034
-			and ($desc = $trouver_table(rtrim($type, 's') . 's', $serveur))
1034
+			and ($desc = $trouver_table(rtrim($type, 's').'s', $serveur))
1035 1035
 		) {
1036 1036
 			return $desc['id_table'];
1037 1037
 		} elseif (
@@ -1041,11 +1041,11 @@  discard block
 block discarded – undo
1041 1041
 			return $desc['id_table'];
1042 1042
 		}
1043 1043
 
1044
-		spip_log('table_objet(' . $type . ') calculee sans verification');
1044
+		spip_log('table_objet('.$type.') calculee sans verification');
1045 1045
 		#spip_log(debug_backtrace(),'db');
1046 1046
 	}
1047 1047
 
1048
-	return rtrim($type, 's') . 's'; # cas historique ne devant plus servir, sauf si $serveur=false
1048
+	return rtrim($type, 's').'s'; # cas historique ne devant plus servir, sauf si $serveur=false
1049 1049
 }
1050 1050
 
1051 1051
 /**
@@ -1229,7 +1229,7 @@  discard block
 block discarded – undo
1229 1229
 function objet_test_si_publie($objet, $id_objet, $serveur = '') {
1230 1230
 	// voir si une fonction est definie pour faire le boulot
1231 1231
 	// elle a la priorite dans ce cas
1232
-	if ($f = charger_fonction($objet . '_test_si_publie', 'base', true)) {
1232
+	if ($f = charger_fonction($objet.'_test_si_publie', 'base', true)) {
1233 1233
 		return $f($objet, $id_objet, $serveur);
1234 1234
 	}
1235 1235
 
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
 		$boucle->sql_serveur = $serveur;
1252 1252
 		$boucle->select[] = $id_table_objet;
1253 1253
 		$boucle->from[$table_objet] = table_objet_sql($objet, $serveur);
1254
-		$boucle->where[] = $id_table . '.' . $id_table_objet . '=' . intval($id_objet);
1254
+		$boucle->where[] = $id_table.'.'.$id_table_objet.'='.intval($id_objet);
1255 1255
 
1256 1256
 		$boucle->descr['nom'] = 'objet_test_si_publie'; // eviter notice php
1257 1257
 		$boucle->descr['sourcefile'] = 'internal';
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
 						? "{$parent_methode['source_champ']} = $id_objet"
1379 1379
 						: "$cle_objet = $id_objet";
1380 1380
 					if (isset($parent_methode['source_champ_type'])) {
1381
-						$where[] = "{$parent_methode['source_champ_type']} = " . sql_quote($objet);
1381
+						$where[] = "{$parent_methode['source_champ_type']} = ".sql_quote($objet);
1382 1382
 					}
1383 1383
 					// -- Condition supplémentaire sur la détection du parent
1384 1384
 					if (isset($parent_methode['table_condition'])) {
@@ -1502,11 +1502,11 @@  discard block
 block discarded – undo
1502 1502
 			$where = [];
1503 1503
 			// -- L'identifiant du parent
1504 1504
 			if (isset($_methode_parent['champ'])) {
1505
-				$where[] = $_methode_parent['champ'] . ' = ' . $id_objet;
1505
+				$where[] = $_methode_parent['champ'].' = '.$id_objet;
1506 1506
 			}
1507 1507
 			// -- Si le parent est variable
1508 1508
 			if (isset($_methode_parent['champ_type'])) {
1509
-				$where[] = $_methode_parent['champ_type'] . ' = ' . sql_quote($objet);
1509
+				$where[] = $_methode_parent['champ_type'].' = '.sql_quote($objet);
1510 1510
 			}
1511 1511
 
1512 1512
 			// On détermine la table, le champ id des enfants et on complète éventuellement les conditions
Please login to merge, or discard this patch.
ecrire/req/sqlite_generique.php 2 patches
Indentation   +1999 added lines, -1999 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
 // TODO: get/set_caracteres ?
@@ -42,91 +42,91 @@  discard block
 block discarded – undo
42 42
  * @return array|bool
43 43
  */
44 44
 function req_sqlite_dist($addr, $port, $login, $pass, $db = '', $prefixe = '', $sqlite_version = '') {
45
-	static $last_connect = [];
46
-
47
-	// si provient de selectdb
48
-	// un code pour etre sur que l'on vient de select_db()
49
-	if (strpos($db, $code = '@selectdb@') !== false) {
50
-		foreach (['addr', 'port', 'login', 'pass', 'prefixe'] as $a) {
51
-			$$a = $last_connect[$a];
52
-		}
53
-		$db = str_replace($code, '', $db);
54
-	}
55
-
56
-	/*
45
+    static $last_connect = [];
46
+
47
+    // si provient de selectdb
48
+    // un code pour etre sur que l'on vient de select_db()
49
+    if (strpos($db, $code = '@selectdb@') !== false) {
50
+        foreach (['addr', 'port', 'login', 'pass', 'prefixe'] as $a) {
51
+            $$a = $last_connect[$a];
52
+        }
53
+        $db = str_replace($code, '', $db);
54
+    }
55
+
56
+    /*
57 57
 	 * En sqlite, seule l'adresse du fichier est importante.
58 58
 	 * Ce sera $db le nom,
59 59
 	 * le path est $addr
60 60
 	 * (_DIR_DB si $addr est vide)
61 61
 	 */
62
-	_sqlite_init();
63
-
64
-	// determiner le dossier de la base : $addr ou _DIR_DB
65
-	$f = _DIR_DB;
66
-	if ($addr and strpos($addr, '/') !== false) {
67
-		$f = rtrim($addr, '/') . '/';
68
-	}
69
-
70
-	// un nom de base demande et impossible d'obtenir la base, on s'en va :
71
-	// il faut que la base existe ou que le repertoire parent soit writable
72
-	if ($db and !is_file($f .= $db . '.sqlite') and !is_writable(dirname($f))) {
73
-		spip_log("base $f non trouvee ou droits en ecriture manquants", 'sqlite.' . _LOG_HS);
74
-
75
-		return false;
76
-	}
77
-
78
-	// charger les modules sqlite au besoin
79
-	if (!_sqlite_charger_version($sqlite_version)) {
80
-		spip_log("Impossible de trouver/charger le module SQLite ($sqlite_version)!", 'sqlite.' . _LOG_HS);
81
-
82
-		return false;
83
-	}
84
-
85
-	// chargement des constantes
86
-	// il ne faut pas definir les constantes avant d'avoir charge les modules sqlite
87
-	$define = 'spip_sqlite' . $sqlite_version . '_constantes';
88
-	$define();
89
-
90
-	$ok = false;
91
-	if (!$db) {
92
-		// si pas de db ->
93
-		// base temporaire tant qu'on ne connait pas son vrai nom
94
-		// pour tester la connexion
95
-		$db = '_sqlite' . $sqlite_version . '_install';
96
-		$tmp = _DIR_DB . $db . '.sqlite';
97
-		$ok = $link = new \PDO("sqlite:$tmp");
98
-	} else {
99
-		// Ouvrir (eventuellement creer la base)
100
-		$ok = $link = new \PDO("sqlite:$f");
101
-	}
102
-
103
-	if (!$ok) {
104
-		$e = _sqlite_last_error_from_link($link);
105
-		spip_log("Impossible d'ouvrir la base SQLite($sqlite_version) $f : $e", 'sqlite.' . _LOG_HS);
106
-
107
-		return false;
108
-	}
109
-
110
-	if ($link) {
111
-		$last_connect = [
112
-			'addr' => $addr,
113
-			'port' => $port,
114
-			'login' => $login,
115
-			'pass' => $pass,
116
-			'db' => $db,
117
-			'prefixe' => $prefixe,
118
-		];
119
-		// etre sur qu'on definit bien les fonctions a chaque nouvelle connexion
120
-		include_spip('req/sqlite_fonctions');
121
-		_sqlite_init_functions($link);
122
-	}
123
-
124
-	return [
125
-		'db' => $db,
126
-		'prefixe' => $prefixe ? $prefixe : $db,
127
-		'link' => $link,
128
-		'total_requetes' => 0,
129
-	];
62
+    _sqlite_init();
63
+
64
+    // determiner le dossier de la base : $addr ou _DIR_DB
65
+    $f = _DIR_DB;
66
+    if ($addr and strpos($addr, '/') !== false) {
67
+        $f = rtrim($addr, '/') . '/';
68
+    }
69
+
70
+    // un nom de base demande et impossible d'obtenir la base, on s'en va :
71
+    // il faut que la base existe ou que le repertoire parent soit writable
72
+    if ($db and !is_file($f .= $db . '.sqlite') and !is_writable(dirname($f))) {
73
+        spip_log("base $f non trouvee ou droits en ecriture manquants", 'sqlite.' . _LOG_HS);
74
+
75
+        return false;
76
+    }
77
+
78
+    // charger les modules sqlite au besoin
79
+    if (!_sqlite_charger_version($sqlite_version)) {
80
+        spip_log("Impossible de trouver/charger le module SQLite ($sqlite_version)!", 'sqlite.' . _LOG_HS);
81
+
82
+        return false;
83
+    }
84
+
85
+    // chargement des constantes
86
+    // il ne faut pas definir les constantes avant d'avoir charge les modules sqlite
87
+    $define = 'spip_sqlite' . $sqlite_version . '_constantes';
88
+    $define();
89
+
90
+    $ok = false;
91
+    if (!$db) {
92
+        // si pas de db ->
93
+        // base temporaire tant qu'on ne connait pas son vrai nom
94
+        // pour tester la connexion
95
+        $db = '_sqlite' . $sqlite_version . '_install';
96
+        $tmp = _DIR_DB . $db . '.sqlite';
97
+        $ok = $link = new \PDO("sqlite:$tmp");
98
+    } else {
99
+        // Ouvrir (eventuellement creer la base)
100
+        $ok = $link = new \PDO("sqlite:$f");
101
+    }
102
+
103
+    if (!$ok) {
104
+        $e = _sqlite_last_error_from_link($link);
105
+        spip_log("Impossible d'ouvrir la base SQLite($sqlite_version) $f : $e", 'sqlite.' . _LOG_HS);
106
+
107
+        return false;
108
+    }
109
+
110
+    if ($link) {
111
+        $last_connect = [
112
+            'addr' => $addr,
113
+            'port' => $port,
114
+            'login' => $login,
115
+            'pass' => $pass,
116
+            'db' => $db,
117
+            'prefixe' => $prefixe,
118
+        ];
119
+        // etre sur qu'on definit bien les fonctions a chaque nouvelle connexion
120
+        include_spip('req/sqlite_fonctions');
121
+        _sqlite_init_functions($link);
122
+    }
123
+
124
+    return [
125
+        'db' => $db,
126
+        'prefixe' => $prefixe ? $prefixe : $db,
127
+        'link' => $link,
128
+        'total_requetes' => 0,
129
+    ];
130 130
 }
131 131
 
132 132
 
@@ -145,14 +145,14 @@  discard block
 block discarded – undo
145 145
  *    Resultat de la requete
146 146
  */
147 147
 function spip_sqlite_query($query, $serveur = '', $requeter = true) {
148
-	#spip_log("spip_sqlite_query() > $query",'sqlite.'._LOG_DEBUG);
149
-	#_sqlite_init(); // fait la premiere fois dans spip_sqlite
150
-	$query = spip_sqlite::traduire_requete($query, $serveur);
151
-	if (!$requeter) {
152
-		return $query;
153
-	}
148
+    #spip_log("spip_sqlite_query() > $query",'sqlite.'._LOG_DEBUG);
149
+    #_sqlite_init(); // fait la premiere fois dans spip_sqlite
150
+    $query = spip_sqlite::traduire_requete($query, $serveur);
151
+    if (!$requeter) {
152
+        return $query;
153
+    }
154 154
 
155
-	return spip_sqlite::executer_requete($query, $serveur);
155
+    return spip_sqlite::executer_requete($query, $serveur);
156 156
 }
157 157
 
158 158
 
@@ -169,11 +169,11 @@  discard block
 block discarded – undo
169 169
  */
170 170
 function spip_sqlite_alter($query, $serveur = '', $requeter = true) {
171 171
 
172
-	$query = spip_sqlite_query("ALTER $query", $serveur, false);
173
-	// traduire la requete pour recuperer les bons noms de table
174
-	$query = spip_sqlite::traduire_requete($query, $serveur);
172
+    $query = spip_sqlite_query("ALTER $query", $serveur, false);
173
+    // traduire la requete pour recuperer les bons noms de table
174
+    $query = spip_sqlite::traduire_requete($query, $serveur);
175 175
 
176
-	/*
176
+    /*
177 177
 		 * la il faut faire les transformations
178 178
 		 * si ALTER TABLE x (DROP|CHANGE) y
179 179
 		 *
@@ -182,251 +182,251 @@  discard block
 block discarded – undo
182 182
 		 * 3) faire chaque requete independemment
183 183
 		 */
184 184
 
185
-	// 1
186
-	if (preg_match('/\s*(ALTER(\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is', $query, $regs)) {
187
-		$debut = $regs[1];
188
-		$table = $regs[3];
189
-		$suite = $regs[4];
190
-	} else {
191
-		spip_log("SQLite : Probleme de ALTER TABLE mal forme dans $query", 'sqlite.' . _LOG_ERREUR);
192
-
193
-		return false;
194
-	}
195
-
196
-	// 2
197
-	// il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
198
-	// tout en cassant "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... en deux
199
-	// ou revoir l'api de sql_alter en creant un
200
-	// sql_alter_table($table,array($actions));
201
-	$todo = explode(',', $suite);
202
-
203
-	// on remet les morceaux dechires ensembles... que c'est laid !
204
-	$todo2 = [];
205
-	$i = 0;
206
-	$ouverte = false;
207
-	while ($do = array_shift($todo)) {
208
-		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . ',' . $do : $do;
209
-		$o = (false !== strpos($do, '('));
210
-		$f = (false !== strpos($do, ')'));
211
-		if ($o and !$f) {
212
-			$ouverte = true;
213
-		} elseif ($f) {
214
-			$ouverte = false;
215
-		}
216
-		if (!$ouverte) {
217
-			$i++;
218
-		}
219
-	}
220
-
221
-	// 3
222
-	$resultats = [];
223
-	foreach ($todo2 as $do) {
224
-		$do = trim($do);
225
-		if (
226
-			!preg_match('/(DROP PRIMARY KEY|DROP KEY|DROP INDEX|DROP COLUMN|DROP'
227
-			. '|CHANGE COLUMN|CHANGE|MODIFY|RENAME TO|RENAME'
228
-			. '|ADD PRIMARY KEY|ADD KEY|ADD INDEX|ADD UNIQUE KEY|ADD UNIQUE'
229
-			. '|ADD COLUMN|ADD'
230
-			. ')\s*([^\s]*)\s*(.*)?/i', $do, $matches)
231
-		) {
232
-			spip_log(
233
-				"SQLite : Probleme de ALTER TABLE, utilisation non reconnue dans : $do \n(requete d'origine : $query)",
234
-				'sqlite.' . _LOG_ERREUR
235
-			);
236
-
237
-			return false;
238
-		}
239
-
240
-		$cle = strtoupper($matches[1]);
241
-		$colonne_origine = $matches[2];
242
-		$colonne_destination = '';
243
-
244
-		$def = $matches[3];
245
-
246
-		// eluder une eventuelle clause before|after|first inutilisable
247
-		$defr = rtrim(preg_replace('/(BEFORE|AFTER|FIRST)(.*)$/is', '', $def));
248
-		$defo = $defr; // garder la def d'origine pour certains cas
249
-		// remplacer les definitions venant de mysql
250
-		$defr = _sqlite_remplacements_definitions_table($defr);
251
-
252
-		// reinjecter dans le do
253
-		$do = str_replace($def, $defr, $do);
254
-		$def = $defr;
255
-
256
-		switch ($cle) {
257
-			// suppression d'un index
258
-			case 'DROP KEY':
259
-			case 'DROP INDEX':
260
-				$nom_index = $colonne_origine;
261
-				spip_sqlite_drop_index($nom_index, $table, $serveur);
262
-				break;
263
-
264
-			// suppression d'une pk
265
-			case 'DROP PRIMARY KEY':
266
-				if (
267
-					!_sqlite_modifier_table(
268
-						$table,
269
-						$colonne_origine,
270
-						['key' => ['PRIMARY KEY' => '']],
271
-						$serveur
272
-					)
273
-				) {
274
-					return false;
275
-				}
276
-				break;
277
-			// suppression d'une colonne
278
-			case 'DROP COLUMN':
279
-			case 'DROP':
280
-				if (
281
-					!_sqlite_modifier_table(
282
-						$table,
283
-						[$colonne_origine => ''],
284
-						[],
285
-						$serveur
286
-					)
287
-				) {
288
-					return false;
289
-				}
290
-				break;
291
-
292
-			case 'CHANGE COLUMN':
293
-			case 'CHANGE':
294
-				// recuperer le nom de la future colonne
295
-				// on reprend la def d'origine car _sqlite_modifier_table va refaire la translation
296
-				// en tenant compte de la cle primaire (ce qui est mieux)
297
-				$def = trim($defo);
298
-				$colonne_destination = substr($def, 0, strpos($def, ' '));
299
-				$def = substr($def, strlen($colonne_destination) + 1);
300
-
301
-				if (
302
-					!_sqlite_modifier_table(
303
-						$table,
304
-						[$colonne_origine => $colonne_destination],
305
-						['field' => [$colonne_destination => $def]],
306
-						$serveur
307
-					)
308
-				) {
309
-					return false;
310
-				}
311
-				break;
312
-
313
-			case 'MODIFY':
314
-				// on reprend la def d'origine car _sqlite_modifier_table va refaire la translation
315
-				// en tenant compte de la cle primaire (ce qui est mieux)
316
-				if (
317
-					!_sqlite_modifier_table(
318
-						$table,
319
-						$colonne_origine,
320
-						['field' => [$colonne_origine => $defo]],
321
-						$serveur
322
-					)
323
-				) {
324
-					return false;
325
-				}
326
-				break;
327
-
328
-			// pas geres en sqlite2
329
-			case 'RENAME':
330
-				$do = 'RENAME TO' . substr($do, 6);
331
-			case 'RENAME TO':
332
-				if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
333
-					spip_log("SQLite : Erreur ALTER TABLE / RENAME : $query", 'sqlite.' . _LOG_ERREUR);
334
-
335
-					return false;
336
-				}
337
-				break;
338
-
339
-			// ajout d'une pk
340
-			case 'ADD PRIMARY KEY':
341
-				$pk = trim(substr($do, 16));
342
-				$pk = ($pk[0] == '(') ? substr($pk, 1, -1) : $pk;
343
-				if (
344
-					!_sqlite_modifier_table(
345
-						$table,
346
-						$colonne_origine,
347
-						['key' => ['PRIMARY KEY' => $pk]],
348
-						$serveur
349
-					)
350
-				) {
351
-					return false;
352
-				}
353
-				break;
354
-			// ajout d'un index
355
-			case 'ADD UNIQUE KEY':
356
-			case 'ADD UNIQUE':
357
-				$unique = true;
358
-			case 'ADD INDEX':
359
-			case 'ADD KEY':
360
-				if (!isset($unique)) {
361
-					$unique = false;
362
-				}
363
-				// peut etre "(colonne)" ou "nom_index (colonnes)"
364
-				// bug potentiel si qqn met "(colonne, colonne)"
365
-				//
366
-				// nom_index (colonnes)
367
-				if ($def) {
368
-					$colonnes = substr($def, 1, -1);
369
-					$nom_index = $colonne_origine;
370
-				} else {
371
-					// (colonne)
372
-					if ($colonne_origine[0] == '(') {
373
-						$colonnes = substr($colonne_origine, 1, -1);
374
-						if (false !== strpos(',', $colonnes)) {
375
-							spip_log('SQLite : Erreur, impossible de creer un index sur plusieurs colonnes'
376
-								. " sans qu'il ait de nom ($table, ($colonnes))", 'sqlite.' . _LOG_ERREUR);
377
-							break;
378
-						} else {
379
-							$nom_index = $colonnes;
380
-						}
381
-					} // nom_index
382
-					else {
383
-						$nom_index = $colonnes = $colonne_origine;
384
-					}
385
-				}
386
-				spip_sqlite_create_index($nom_index, $table, $colonnes, $unique, $serveur);
387
-				break;
388
-
389
-			// pas geres en sqlite2
390
-			case 'ADD COLUMN':
391
-				$do = 'ADD' . substr($do, 10);
392
-			case 'ADD':
393
-			default:
394
-				if (!preg_match(',primary\s+key,i', $do)) {
395
-					if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
396
-						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
397
-
398
-						return false;
399
-					}
400
-					break;
401
-				}
402
-				// ou si la colonne est aussi primary key
403
-				// cas du add id_truc int primary key
404
-				// ajout d'une colonne qui passe en primary key directe
405
-				else {
406
-					$def = trim(substr($do, 3));
407
-					$colonne_ajoutee = substr($def, 0, strpos($def, ' '));
408
-					$def = substr($def, strlen($colonne_ajoutee) + 1);
409
-					$opts = [];
410
-					if (preg_match(',primary\s+key,i', $def)) {
411
-						$opts['key'] = ['PRIMARY KEY' => $colonne_ajoutee];
412
-						$def = preg_replace(',primary\s+key,i', '', $def);
413
-					}
414
-					$opts['field'] = [$colonne_ajoutee => $def];
415
-					if (!_sqlite_modifier_table($table, [$colonne_ajoutee], $opts, $serveur)) {
416
-						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
417
-
418
-						return false;
419
-					}
420
-				}
421
-				break;
422
-		}
423
-		// tout est bon, ouf !
424
-		spip_log("SQLite ($serveur) : Changements OK : $debut $do", 'sqlite.' . _LOG_INFO);
425
-	}
426
-
427
-	spip_log("SQLite ($serveur) : fin ALTER TABLE OK !", 'sqlite.' . _LOG_INFO);
428
-
429
-	return true;
185
+    // 1
186
+    if (preg_match('/\s*(ALTER(\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is', $query, $regs)) {
187
+        $debut = $regs[1];
188
+        $table = $regs[3];
189
+        $suite = $regs[4];
190
+    } else {
191
+        spip_log("SQLite : Probleme de ALTER TABLE mal forme dans $query", 'sqlite.' . _LOG_ERREUR);
192
+
193
+        return false;
194
+    }
195
+
196
+    // 2
197
+    // il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
198
+    // tout en cassant "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... en deux
199
+    // ou revoir l'api de sql_alter en creant un
200
+    // sql_alter_table($table,array($actions));
201
+    $todo = explode(',', $suite);
202
+
203
+    // on remet les morceaux dechires ensembles... que c'est laid !
204
+    $todo2 = [];
205
+    $i = 0;
206
+    $ouverte = false;
207
+    while ($do = array_shift($todo)) {
208
+        $todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . ',' . $do : $do;
209
+        $o = (false !== strpos($do, '('));
210
+        $f = (false !== strpos($do, ')'));
211
+        if ($o and !$f) {
212
+            $ouverte = true;
213
+        } elseif ($f) {
214
+            $ouverte = false;
215
+        }
216
+        if (!$ouverte) {
217
+            $i++;
218
+        }
219
+    }
220
+
221
+    // 3
222
+    $resultats = [];
223
+    foreach ($todo2 as $do) {
224
+        $do = trim($do);
225
+        if (
226
+            !preg_match('/(DROP PRIMARY KEY|DROP KEY|DROP INDEX|DROP COLUMN|DROP'
227
+            . '|CHANGE COLUMN|CHANGE|MODIFY|RENAME TO|RENAME'
228
+            . '|ADD PRIMARY KEY|ADD KEY|ADD INDEX|ADD UNIQUE KEY|ADD UNIQUE'
229
+            . '|ADD COLUMN|ADD'
230
+            . ')\s*([^\s]*)\s*(.*)?/i', $do, $matches)
231
+        ) {
232
+            spip_log(
233
+                "SQLite : Probleme de ALTER TABLE, utilisation non reconnue dans : $do \n(requete d'origine : $query)",
234
+                'sqlite.' . _LOG_ERREUR
235
+            );
236
+
237
+            return false;
238
+        }
239
+
240
+        $cle = strtoupper($matches[1]);
241
+        $colonne_origine = $matches[2];
242
+        $colonne_destination = '';
243
+
244
+        $def = $matches[3];
245
+
246
+        // eluder une eventuelle clause before|after|first inutilisable
247
+        $defr = rtrim(preg_replace('/(BEFORE|AFTER|FIRST)(.*)$/is', '', $def));
248
+        $defo = $defr; // garder la def d'origine pour certains cas
249
+        // remplacer les definitions venant de mysql
250
+        $defr = _sqlite_remplacements_definitions_table($defr);
251
+
252
+        // reinjecter dans le do
253
+        $do = str_replace($def, $defr, $do);
254
+        $def = $defr;
255
+
256
+        switch ($cle) {
257
+            // suppression d'un index
258
+            case 'DROP KEY':
259
+            case 'DROP INDEX':
260
+                $nom_index = $colonne_origine;
261
+                spip_sqlite_drop_index($nom_index, $table, $serveur);
262
+                break;
263
+
264
+            // suppression d'une pk
265
+            case 'DROP PRIMARY KEY':
266
+                if (
267
+                    !_sqlite_modifier_table(
268
+                        $table,
269
+                        $colonne_origine,
270
+                        ['key' => ['PRIMARY KEY' => '']],
271
+                        $serveur
272
+                    )
273
+                ) {
274
+                    return false;
275
+                }
276
+                break;
277
+            // suppression d'une colonne
278
+            case 'DROP COLUMN':
279
+            case 'DROP':
280
+                if (
281
+                    !_sqlite_modifier_table(
282
+                        $table,
283
+                        [$colonne_origine => ''],
284
+                        [],
285
+                        $serveur
286
+                    )
287
+                ) {
288
+                    return false;
289
+                }
290
+                break;
291
+
292
+            case 'CHANGE COLUMN':
293
+            case 'CHANGE':
294
+                // recuperer le nom de la future colonne
295
+                // on reprend la def d'origine car _sqlite_modifier_table va refaire la translation
296
+                // en tenant compte de la cle primaire (ce qui est mieux)
297
+                $def = trim($defo);
298
+                $colonne_destination = substr($def, 0, strpos($def, ' '));
299
+                $def = substr($def, strlen($colonne_destination) + 1);
300
+
301
+                if (
302
+                    !_sqlite_modifier_table(
303
+                        $table,
304
+                        [$colonne_origine => $colonne_destination],
305
+                        ['field' => [$colonne_destination => $def]],
306
+                        $serveur
307
+                    )
308
+                ) {
309
+                    return false;
310
+                }
311
+                break;
312
+
313
+            case 'MODIFY':
314
+                // on reprend la def d'origine car _sqlite_modifier_table va refaire la translation
315
+                // en tenant compte de la cle primaire (ce qui est mieux)
316
+                if (
317
+                    !_sqlite_modifier_table(
318
+                        $table,
319
+                        $colonne_origine,
320
+                        ['field' => [$colonne_origine => $defo]],
321
+                        $serveur
322
+                    )
323
+                ) {
324
+                    return false;
325
+                }
326
+                break;
327
+
328
+            // pas geres en sqlite2
329
+            case 'RENAME':
330
+                $do = 'RENAME TO' . substr($do, 6);
331
+            case 'RENAME TO':
332
+                if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
333
+                    spip_log("SQLite : Erreur ALTER TABLE / RENAME : $query", 'sqlite.' . _LOG_ERREUR);
334
+
335
+                    return false;
336
+                }
337
+                break;
338
+
339
+            // ajout d'une pk
340
+            case 'ADD PRIMARY KEY':
341
+                $pk = trim(substr($do, 16));
342
+                $pk = ($pk[0] == '(') ? substr($pk, 1, -1) : $pk;
343
+                if (
344
+                    !_sqlite_modifier_table(
345
+                        $table,
346
+                        $colonne_origine,
347
+                        ['key' => ['PRIMARY KEY' => $pk]],
348
+                        $serveur
349
+                    )
350
+                ) {
351
+                    return false;
352
+                }
353
+                break;
354
+            // ajout d'un index
355
+            case 'ADD UNIQUE KEY':
356
+            case 'ADD UNIQUE':
357
+                $unique = true;
358
+            case 'ADD INDEX':
359
+            case 'ADD KEY':
360
+                if (!isset($unique)) {
361
+                    $unique = false;
362
+                }
363
+                // peut etre "(colonne)" ou "nom_index (colonnes)"
364
+                // bug potentiel si qqn met "(colonne, colonne)"
365
+                //
366
+                // nom_index (colonnes)
367
+                if ($def) {
368
+                    $colonnes = substr($def, 1, -1);
369
+                    $nom_index = $colonne_origine;
370
+                } else {
371
+                    // (colonne)
372
+                    if ($colonne_origine[0] == '(') {
373
+                        $colonnes = substr($colonne_origine, 1, -1);
374
+                        if (false !== strpos(',', $colonnes)) {
375
+                            spip_log('SQLite : Erreur, impossible de creer un index sur plusieurs colonnes'
376
+                                . " sans qu'il ait de nom ($table, ($colonnes))", 'sqlite.' . _LOG_ERREUR);
377
+                            break;
378
+                        } else {
379
+                            $nom_index = $colonnes;
380
+                        }
381
+                    } // nom_index
382
+                    else {
383
+                        $nom_index = $colonnes = $colonne_origine;
384
+                    }
385
+                }
386
+                spip_sqlite_create_index($nom_index, $table, $colonnes, $unique, $serveur);
387
+                break;
388
+
389
+            // pas geres en sqlite2
390
+            case 'ADD COLUMN':
391
+                $do = 'ADD' . substr($do, 10);
392
+            case 'ADD':
393
+            default:
394
+                if (!preg_match(',primary\s+key,i', $do)) {
395
+                    if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
396
+                        spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
397
+
398
+                        return false;
399
+                    }
400
+                    break;
401
+                }
402
+                // ou si la colonne est aussi primary key
403
+                // cas du add id_truc int primary key
404
+                // ajout d'une colonne qui passe en primary key directe
405
+                else {
406
+                    $def = trim(substr($do, 3));
407
+                    $colonne_ajoutee = substr($def, 0, strpos($def, ' '));
408
+                    $def = substr($def, strlen($colonne_ajoutee) + 1);
409
+                    $opts = [];
410
+                    if (preg_match(',primary\s+key,i', $def)) {
411
+                        $opts['key'] = ['PRIMARY KEY' => $colonne_ajoutee];
412
+                        $def = preg_replace(',primary\s+key,i', '', $def);
413
+                    }
414
+                    $opts['field'] = [$colonne_ajoutee => $def];
415
+                    if (!_sqlite_modifier_table($table, [$colonne_ajoutee], $opts, $serveur)) {
416
+                        spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
417
+
418
+                        return false;
419
+                    }
420
+                }
421
+                break;
422
+        }
423
+        // tout est bon, ouf !
424
+        spip_log("SQLite ($serveur) : Changements OK : $debut $do", 'sqlite.' . _LOG_INFO);
425
+    }
426
+
427
+    spip_log("SQLite ($serveur) : fin ALTER TABLE OK !", 'sqlite.' . _LOG_INFO);
428
+
429
+    return true;
430 430
 }
431 431
 
432 432
 
@@ -449,38 +449,38 @@  discard block
 block discarded – undo
449 449
  *     - true si la requête réussie, false sinon.
450 450
  */
451 451
 function spip_sqlite_create(
452
-	$nom,
453
-	$champs,
454
-	$cles,
455
-	$autoinc = false,
456
-	$temporary = false,
457
-	$serveur = '',
458
-	$requeter = true
452
+    $nom,
453
+    $champs,
454
+    $cles,
455
+    $autoinc = false,
456
+    $temporary = false,
457
+    $serveur = '',
458
+    $requeter = true
459 459
 ) {
460
-	$query = _sqlite_requete_create($nom, $champs, $cles, $autoinc, $temporary, $ifnotexists = true, $serveur, $requeter);
461
-	if (!$query) {
462
-		return false;
463
-	}
464
-	$res = spip_sqlite_query($query, $serveur, $requeter);
465
-
466
-	// SQLite ne cree pas les KEY sur les requetes CREATE TABLE
467
-	// il faut donc les faire creer ensuite
468
-	if (!$requeter) {
469
-		return $res;
470
-	}
471
-
472
-	$ok = $res ? true : false;
473
-	if ($ok) {
474
-		foreach ($cles as $k => $v) {
475
-			if (preg_match(',^(UNIQUE KEY|KEY|UNIQUE)\s,i', $k, $m)) {
476
-				$index = trim(substr($k, strlen($m[1])));
477
-				$unique = (strlen($m[1]) > 3);
478
-				$ok &= spip_sqlite_create_index($index, $nom, $v, $unique, $serveur);
479
-			}
480
-		}
481
-	}
482
-
483
-	return $ok ? true : false;
460
+    $query = _sqlite_requete_create($nom, $champs, $cles, $autoinc, $temporary, $ifnotexists = true, $serveur, $requeter);
461
+    if (!$query) {
462
+        return false;
463
+    }
464
+    $res = spip_sqlite_query($query, $serveur, $requeter);
465
+
466
+    // SQLite ne cree pas les KEY sur les requetes CREATE TABLE
467
+    // il faut donc les faire creer ensuite
468
+    if (!$requeter) {
469
+        return $res;
470
+    }
471
+
472
+    $ok = $res ? true : false;
473
+    if ($ok) {
474
+        foreach ($cles as $k => $v) {
475
+            if (preg_match(',^(UNIQUE KEY|KEY|UNIQUE)\s,i', $k, $m)) {
476
+                $index = trim(substr($k, strlen($m[1])));
477
+                $unique = (strlen($m[1]) > 3);
478
+                $ok &= spip_sqlite_create_index($index, $nom, $v, $unique, $serveur);
479
+            }
480
+        }
481
+    }
482
+
483
+    return $ok ? true : false;
484 484
 }
485 485
 
486 486
 /**
@@ -493,21 +493,21 @@  discard block
 block discarded – undo
493 493
  * @return bool true si la base est créee.
494 494
  **/
495 495
 function spip_sqlite_create_base($nom, $serveur = '', $option = true) {
496
-	$f = $nom . '.sqlite';
497
-	if (strpos($nom, '/') === false) {
498
-		$f = _DIR_DB . $f;
499
-	}
496
+    $f = $nom . '.sqlite';
497
+    if (strpos($nom, '/') === false) {
498
+        $f = _DIR_DB . $f;
499
+    }
500 500
 
501
-	$ok = new \PDO("sqlite:$f");
501
+    $ok = new \PDO("sqlite:$f");
502 502
 
503
-	if ($ok) {
504
-		unset($ok);
503
+    if ($ok) {
504
+        unset($ok);
505 505
 
506
-		return true;
507
-	}
508
-	unset($ok);
506
+        return true;
507
+    }
508
+    unset($ok);
509 509
 
510
-	return false;
510
+    return false;
511 511
 }
512 512
 
513 513
 
@@ -528,22 +528,22 @@  discard block
 block discarded – undo
528 528
  *     - string texte de la requête si $requeter vaut false
529 529
  */
530 530
 function spip_sqlite_create_view($nom, $query_select, $serveur = '', $requeter = true) {
531
-	if (!$query_select) {
532
-		return false;
533
-	}
534
-	// vue deja presente
535
-	if (sql_showtable($nom, false, $serveur)) {
536
-		spip_log(
537
-			"Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)",
538
-			'sqlite.' . _LOG_ERREUR
539
-		);
531
+    if (!$query_select) {
532
+        return false;
533
+    }
534
+    // vue deja presente
535
+    if (sql_showtable($nom, false, $serveur)) {
536
+        spip_log(
537
+            "Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)",
538
+            'sqlite.' . _LOG_ERREUR
539
+        );
540 540
 
541
-		return false;
542
-	}
541
+        return false;
542
+    }
543 543
 
544
-	$query = "CREATE VIEW $nom AS " . $query_select;
544
+    $query = "CREATE VIEW $nom AS " . $query_select;
545 545
 
546
-	return spip_sqlite_query($query, $serveur, $requeter);
546
+    return spip_sqlite_query($query, $serveur, $requeter);
547 547
 }
548 548
 
549 549
 /**
@@ -565,54 +565,54 @@  discard block
 block discarded – undo
565 565
  *    string : requête, false si erreur, true sinon.
566 566
  */
567 567
 function spip_sqlite_create_index($nom, $table, $champs, $unique = '', $serveur = '', $requeter = true) {
568
-	if (!($nom or $table or $champs)) {
569
-		spip_log(
570
-			"Champ manquant pour creer un index sqlite ($nom, $table, (" . join(',', $champs) . '))',
571
-			'sqlite.' . _LOG_ERREUR
572
-		);
573
-
574
-		return false;
575
-	}
576
-
577
-	// SQLite ne differentie pas noms des index en fonction des tables
578
-	// il faut donc creer des noms uniques d'index pour une base sqlite
579
-	$nom = $table . '_' . $nom;
580
-	// enlever d'eventuelles parentheses deja presentes sur champs
581
-	if (!is_array($champs)) {
582
-		if ($champs[0] == '(') {
583
-			$champs = substr($champs, 1, -1);
584
-		}
585
-		$champs = [$champs];
586
-		// supprimer l'info de longueur d'index mysql en fin de champ
587
-		$champs = preg_replace(',\(\d+\)$,', '', $champs);
588
-	}
589
-
590
-	$ifnotexists = '';
591
-	$version = spip_sqlite_fetch(spip_sqlite_query('select sqlite_version() AS sqlite_version', $serveur), '', $serveur);
592
-	if (!function_exists('spip_version_compare')) {
593
-		include_spip('plugins/installer');
594
-	}
595
-
596
-	if ($version and spip_version_compare($version['sqlite_version'], '3.3.0', '>=')) {
597
-		$ifnotexists = ' IF NOT EXISTS';
598
-	} else {
599
-		/* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
600
-		$a = spip_sqlite_showtable($table, $serveur);
601
-		if (isset($a['key']['KEY ' . $nom])) {
602
-			return true;
603
-		}
604
-	}
605
-
606
-	$query = 'CREATE ' . ($unique ? 'UNIQUE ' : '') . "INDEX$ifnotexists $nom ON $table (" . join(',', $champs) . ')';
607
-	$res = spip_sqlite_query($query, $serveur, $requeter);
608
-	if (!$requeter) {
609
-		return $res;
610
-	}
611
-	if ($res) {
612
-		return true;
613
-	} else {
614
-		return false;
615
-	}
568
+    if (!($nom or $table or $champs)) {
569
+        spip_log(
570
+            "Champ manquant pour creer un index sqlite ($nom, $table, (" . join(',', $champs) . '))',
571
+            'sqlite.' . _LOG_ERREUR
572
+        );
573
+
574
+        return false;
575
+    }
576
+
577
+    // SQLite ne differentie pas noms des index en fonction des tables
578
+    // il faut donc creer des noms uniques d'index pour une base sqlite
579
+    $nom = $table . '_' . $nom;
580
+    // enlever d'eventuelles parentheses deja presentes sur champs
581
+    if (!is_array($champs)) {
582
+        if ($champs[0] == '(') {
583
+            $champs = substr($champs, 1, -1);
584
+        }
585
+        $champs = [$champs];
586
+        // supprimer l'info de longueur d'index mysql en fin de champ
587
+        $champs = preg_replace(',\(\d+\)$,', '', $champs);
588
+    }
589
+
590
+    $ifnotexists = '';
591
+    $version = spip_sqlite_fetch(spip_sqlite_query('select sqlite_version() AS sqlite_version', $serveur), '', $serveur);
592
+    if (!function_exists('spip_version_compare')) {
593
+        include_spip('plugins/installer');
594
+    }
595
+
596
+    if ($version and spip_version_compare($version['sqlite_version'], '3.3.0', '>=')) {
597
+        $ifnotexists = ' IF NOT EXISTS';
598
+    } else {
599
+        /* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
600
+        $a = spip_sqlite_showtable($table, $serveur);
601
+        if (isset($a['key']['KEY ' . $nom])) {
602
+            return true;
603
+        }
604
+    }
605
+
606
+    $query = 'CREATE ' . ($unique ? 'UNIQUE ' : '') . "INDEX$ifnotexists $nom ON $table (" . join(',', $champs) . ')';
607
+    $res = spip_sqlite_query($query, $serveur, $requeter);
608
+    if (!$requeter) {
609
+        return $res;
610
+    }
611
+    if ($res) {
612
+        return true;
613
+    } else {
614
+        return false;
615
+    }
616 616
 }
617 617
 
618 618
 /**
@@ -629,31 +629,31 @@  discard block
 block discarded – undo
629 629
  * @return int                 Nombre de lignes
630 630
  */
631 631
 function spip_sqlite_count($r, $serveur = '', $requeter = true) {
632
-	if (!$r) {
633
-		return 0;
634
-	}
635
-
636
-	// select ou autre (insert, update,...) ?
637
-	// (link,requete) a compter
638
-	if (is_array($r->spipSqliteRowCount)) {
639
-		list($link, $query) = $r->spipSqliteRowCount;
640
-		// amelioration possible a tester intensivement : pas de order by pour compter !
641
-		// $query = preg_replace(",ORDER BY .+(LIMIT\s|HAVING\s|GROUP BY\s|$),Uims","\\1",$query);
642
-		$query = "SELECT count(*) as zzzzsqlitecount FROM ($query)";
643
-		$l = $link->query($query);
644
-		$i = 0;
645
-		if ($l and $z = $l->fetch()) {
646
-			$i = $z['zzzzsqlitecount'];
647
-		}
648
-		$r->spipSqliteRowCount = $i;
649
-	}
650
-	if (isset($r->spipSqliteRowCount)) {
651
-		// Ce compte est faux s'il y a des limit dans la requete :(
652
-		// il retourne le nombre d'enregistrements sans le limit
653
-		return $r->spipSqliteRowCount;
654
-	} else {
655
-		return $r->rowCount();
656
-	}
632
+    if (!$r) {
633
+        return 0;
634
+    }
635
+
636
+    // select ou autre (insert, update,...) ?
637
+    // (link,requete) a compter
638
+    if (is_array($r->spipSqliteRowCount)) {
639
+        list($link, $query) = $r->spipSqliteRowCount;
640
+        // amelioration possible a tester intensivement : pas de order by pour compter !
641
+        // $query = preg_replace(",ORDER BY .+(LIMIT\s|HAVING\s|GROUP BY\s|$),Uims","\\1",$query);
642
+        $query = "SELECT count(*) as zzzzsqlitecount FROM ($query)";
643
+        $l = $link->query($query);
644
+        $i = 0;
645
+        if ($l and $z = $l->fetch()) {
646
+            $i = $z['zzzzsqlitecount'];
647
+        }
648
+        $r->spipSqliteRowCount = $i;
649
+    }
650
+    if (isset($r->spipSqliteRowCount)) {
651
+        // Ce compte est faux s'il y a des limit dans la requete :(
652
+        // il retourne le nombre d'enregistrements sans le limit
653
+        return $r->spipSqliteRowCount;
654
+    } else {
655
+        return $r->rowCount();
656
+    }
657 657
 }
658 658
 
659 659
 
@@ -672,30 +672,30 @@  discard block
 block discarded – undo
672 672
  *     - false si la requête a échouée
673 673
  **/
674 674
 function spip_sqlite_countsel(
675
-	$from = [],
676
-	$where = [],
677
-	$groupby = '',
678
-	$having = [],
679
-	$serveur = '',
680
-	$requeter = true
675
+    $from = [],
676
+    $where = [],
677
+    $groupby = '',
678
+    $having = [],
679
+    $serveur = '',
680
+    $requeter = true
681 681
 ) {
682
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
683
-	$r = spip_sqlite_select(
684
-		"COUNT($c)",
685
-		$from,
686
-		$where,
687
-		'',
688
-		'',
689
-		'',
690
-		$having,
691
-		$serveur,
692
-		$requeter
693
-	);
694
-	if ((is_resource($r) or is_object($r)) && $requeter) { // ressource : sqlite2, object : sqlite3
695
-		list($r) = spip_sqlite_fetch($r, SPIP_SQLITE3_NUM, $serveur);
696
-	}
697
-
698
-	return $r;
682
+    $c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
683
+    $r = spip_sqlite_select(
684
+        "COUNT($c)",
685
+        $from,
686
+        $where,
687
+        '',
688
+        '',
689
+        '',
690
+        $having,
691
+        $serveur,
692
+        $requeter
693
+    );
694
+    if ((is_resource($r) or is_object($r)) && $requeter) { // ressource : sqlite2, object : sqlite3
695
+        list($r) = spip_sqlite_fetch($r, SPIP_SQLITE3_NUM, $serveur);
696
+    }
697
+
698
+    return $r;
699 699
 }
700 700
 
701 701
 
@@ -712,24 +712,24 @@  discard block
 block discarded – undo
712 712
  *     - False en cas d'erreur.
713 713
  **/
714 714
 function spip_sqlite_delete($table, $where = '', $serveur = '', $requeter = true) {
715
-	$res = spip_sqlite_query(
716
-		_sqlite_calculer_expression('DELETE FROM', $table, ',')
717
-		. _sqlite_calculer_expression('WHERE', $where),
718
-		$serveur,
719
-		$requeter
720
-	);
715
+    $res = spip_sqlite_query(
716
+        _sqlite_calculer_expression('DELETE FROM', $table, ',')
717
+        . _sqlite_calculer_expression('WHERE', $where),
718
+        $serveur,
719
+        $requeter
720
+    );
721 721
 
722
-	// renvoyer la requete inerte si demandee
723
-	if (!$requeter) {
724
-		return $res;
725
-	}
722
+    // renvoyer la requete inerte si demandee
723
+    if (!$requeter) {
724
+        return $res;
725
+    }
726 726
 
727
-	if ($res) {
728
-		$link = _sqlite_link($serveur);
729
-		return $res->rowCount();
730
-	} else {
731
-		return false;
732
-	}
727
+    if ($res) {
728
+        $link = _sqlite_link($serveur);
729
+        return $res->rowCount();
730
+    } else {
731
+        return false;
732
+    }
733 733
 }
734 734
 
735 735
 
@@ -745,15 +745,15 @@  discard block
 block discarded – undo
745 745
  *     - true si la requête a réussie, false sinon
746 746
  */
747 747
 function spip_sqlite_drop_table($table, $exist = '', $serveur = '', $requeter = true) {
748
-	if ($exist) {
749
-		$exist = ' IF EXISTS';
750
-	}
748
+    if ($exist) {
749
+        $exist = ' IF EXISTS';
750
+    }
751 751
 
752
-	if (spip_sqlite_query("DROP TABLE$exist $table", $serveur, $requeter)) {
753
-		return true;
754
-	} else {
755
-		return false;
756
-	}
752
+    if (spip_sqlite_query("DROP TABLE$exist $table", $serveur, $requeter)) {
753
+        return true;
754
+    } else {
755
+        return false;
756
+    }
757 757
 }
758 758
 
759 759
 
@@ -769,11 +769,11 @@  discard block
 block discarded – undo
769 769
  *     - true si la requête a réussie, false sinon
770 770
  */
771 771
 function spip_sqlite_drop_view($view, $exist = '', $serveur = '', $requeter = true) {
772
-	if ($exist) {
773
-		$exist = ' IF EXISTS';
774
-	}
772
+    if ($exist) {
773
+        $exist = ' IF EXISTS';
774
+    }
775 775
 
776
-	return spip_sqlite_query("DROP VIEW$exist $view", $serveur, $requeter);
776
+    return spip_sqlite_query("DROP VIEW$exist $view", $serveur, $requeter);
777 777
 }
778 778
 
779 779
 /**
@@ -787,20 +787,20 @@  discard block
 block discarded – undo
787 787
  * @return bool ou requete
788 788
  */
789 789
 function spip_sqlite_drop_index($nom, $table, $serveur = '', $requeter = true) {
790
-	if (!($nom or $table)) {
791
-		spip_log("Champ manquant pour supprimer un index sqlite ($nom, $table)", 'sqlite.' . _LOG_ERREUR);
790
+    if (!($nom or $table)) {
791
+        spip_log("Champ manquant pour supprimer un index sqlite ($nom, $table)", 'sqlite.' . _LOG_ERREUR);
792 792
 
793
-		return false;
794
-	}
793
+        return false;
794
+    }
795 795
 
796
-	// SQLite ne differentie pas noms des index en fonction des tables
797
-	// il faut donc creer des noms uniques d'index pour une base sqlite
798
-	$index = $table . '_' . $nom;
799
-	$exist = ' IF EXISTS';
796
+    // SQLite ne differentie pas noms des index en fonction des tables
797
+    // il faut donc creer des noms uniques d'index pour une base sqlite
798
+    $index = $table . '_' . $nom;
799
+    $exist = ' IF EXISTS';
800 800
 
801
-	$query = "DROP INDEX$exist $index";
801
+    $query = "DROP INDEX$exist $index";
802 802
 
803
-	return spip_sqlite_query($query, $serveur, $requeter);
803
+    return spip_sqlite_query($query, $serveur, $requeter);
804 804
 }
805 805
 
806 806
 /**
@@ -816,28 +816,28 @@  discard block
 block discarded – undo
816 816
  *     Erreur eventuelle
817 817
  **/
818 818
 function spip_sqlite_error($query = '', $serveur = '') {
819
-	$link = _sqlite_link($serveur);
819
+    $link = _sqlite_link($serveur);
820 820
 
821
-	if ($link) {
822
-		$errs = $link->errorInfo();
823
-		$s = _sqlite_last_error_from_link($link);
824
-	} else {
825
-		$s = ': aucune ressource sqlite (link)';
826
-	}
827
-	if ($s) {
828
-		$trace = debug_backtrace();
829
-		if ($trace[0]['function'] != 'spip_sqlite_error') {
830
-			spip_log("$s - $query - " . sql_error_backtrace(), 'sqlite.' . _LOG_ERREUR);
831
-		}
832
-	}
821
+    if ($link) {
822
+        $errs = $link->errorInfo();
823
+        $s = _sqlite_last_error_from_link($link);
824
+    } else {
825
+        $s = ': aucune ressource sqlite (link)';
826
+    }
827
+    if ($s) {
828
+        $trace = debug_backtrace();
829
+        if ($trace[0]['function'] != 'spip_sqlite_error') {
830
+            spip_log("$s - $query - " . sql_error_backtrace(), 'sqlite.' . _LOG_ERREUR);
831
+        }
832
+    }
833 833
 
834
-	return $s;
834
+    return $s;
835 835
 }
836 836
 
837 837
 function _sqlite_last_error_from_link($link) {
838
-	if ($link) {
839
-		$errs = $link->errorInfo();
840
-		/*
838
+    if ($link) {
839
+        $errs = $link->errorInfo();
840
+        /*
841 841
 			$errs[0]
842 842
 				numero SQLState ('HY000' souvent lors d'une erreur)
843 843
 				http://www.easysoft.com/developer/interfaces/odbc/sqlstate_status_return_codes.html
@@ -847,11 +847,11 @@  discard block
 block discarded – undo
847 847
 			$errs[2]
848 848
 				Le texte du message d'erreur
849 849
 		*/
850
-		if (ltrim($errs[0], '0')) { // 00000 si pas d'erreur
851
-			return "$errs[2]";
852
-		}
853
-	}
854
-	return '';
850
+        if (ltrim($errs[0], '0')) { // 00000 si pas d'erreur
851
+            return "$errs[2]";
852
+        }
853
+    }
854
+    return '';
855 855
 }
856 856
 
857 857
 /**
@@ -868,23 +868,23 @@  discard block
 block discarded – undo
868 868
  *    'HY000/1' : numéro de l'erreur SQLState / numéro d'erreur interne SQLite (en sqlite 3)
869 869
  **/
870 870
 function spip_sqlite_errno($serveur = '') {
871
-	$link = _sqlite_link($serveur);
871
+    $link = _sqlite_link($serveur);
872 872
 
873
-	if ($link) {
874
-		$t = $link->errorInfo();
875
-		$s = ltrim($t[0], '0'); // 00000 si pas d'erreur
876
-		if ($s) {
877
-			$s .= ' / ' . $t[1];
878
-		} // ajoute l'erreur du moteur SQLite
879
-	} else {
880
-		$s = ': aucune ressource sqlite (link)';
881
-	}
873
+    if ($link) {
874
+        $t = $link->errorInfo();
875
+        $s = ltrim($t[0], '0'); // 00000 si pas d'erreur
876
+        if ($s) {
877
+            $s .= ' / ' . $t[1];
878
+        } // ajoute l'erreur du moteur SQLite
879
+    } else {
880
+        $s = ': aucune ressource sqlite (link)';
881
+    }
882 882
 
883
-	if ($s) {
884
-		spip_log("Erreur sqlite $s", 'sqlite.' . _LOG_ERREUR);
885
-	}
883
+    if ($s) {
884
+        spip_log("Erreur sqlite $s", 'sqlite.' . _LOG_ERREUR);
885
+    }
886 886
 
887
-	return $s ? $s : 0;
887
+    return $s ? $s : 0;
888 888
 }
889 889
 
890 890
 
@@ -900,19 +900,19 @@  discard block
 block discarded – undo
900 900
  *     - false si on a pas pu avoir d'explication
901 901
  */
902 902
 function spip_sqlite_explain($query, $serveur = '', $requeter = true) {
903
-	if (strpos(ltrim($query), 'SELECT') !== 0) {
904
-		return [];
905
-	}
903
+    if (strpos(ltrim($query), 'SELECT') !== 0) {
904
+        return [];
905
+    }
906 906
 
907
-	$query = spip_sqlite::traduire_requete($query, $serveur);
908
-	$query = 'EXPLAIN ' . $query;
909
-	if (!$requeter) {
910
-		return $query;
911
-	}
912
-	// on ne trace pas ces requetes, sinon on obtient un tracage sans fin...
913
-	$r = spip_sqlite::executer_requete($query, $serveur, false);
907
+    $query = spip_sqlite::traduire_requete($query, $serveur);
908
+    $query = 'EXPLAIN ' . $query;
909
+    if (!$requeter) {
910
+        return $query;
911
+    }
912
+    // on ne trace pas ces requetes, sinon on obtient un tracage sans fin...
913
+    $r = spip_sqlite::executer_requete($query, $serveur, false);
914 914
 
915
-	return $r ? spip_sqlite_fetch($r, null, $serveur) : false; // hum ? etrange ca... a verifier
915
+    return $r ? spip_sqlite_fetch($r, null, $serveur) : false; // hum ? etrange ca... a verifier
916 916
 }
917 917
 
918 918
 
@@ -932,35 +932,35 @@  discard block
 block discarded – undo
932 932
  */
933 933
 function spip_sqlite_fetch($r, $t = '', $serveur = '', $requeter = true) {
934 934
 
935
-	$link = _sqlite_link($serveur);
936
-	$t = $t ? $t : SPIP_SQLITE3_ASSOC;
935
+    $link = _sqlite_link($serveur);
936
+    $t = $t ? $t : SPIP_SQLITE3_ASSOC;
937 937
 
938
-	if (!$r) {
939
-		return false;
940
-	}
938
+    if (!$r) {
939
+        return false;
940
+    }
941 941
 
942
-	$retour = $r->fetch($t);
942
+    $retour = $r->fetch($t);
943 943
 
944
-	if (!$retour) {
945
-		if ($r->errorCode() === '00000') {
946
-			return null;
947
-		}
948
-		return false;
949
-	}
944
+    if (!$retour) {
945
+        if ($r->errorCode() === '00000') {
946
+            return null;
947
+        }
948
+        return false;
949
+    }
950 950
 
951
-	// Renvoie des 'table.titre' au lieu de 'titre' tout court ! pff !
952
-	// suppression de 'table.' pour toutes les cles (c'est un peu violent !)
953
-	// c'est couteux : on ne verifie que la premiere ligne pour voir si on le fait ou non
954
-	if (strpos(implode('', array_keys($retour)), '.') !== false) {
955
-		foreach ($retour as $cle => $val) {
956
-			if (($pos = strpos($cle, '.')) !== false) {
957
-				$retour[substr($cle, $pos + 1)] = &$retour[$cle];
958
-				unset($retour[$cle]);
959
-			}
960
-		}
961
-	}
951
+    // Renvoie des 'table.titre' au lieu de 'titre' tout court ! pff !
952
+    // suppression de 'table.' pour toutes les cles (c'est un peu violent !)
953
+    // c'est couteux : on ne verifie que la premiere ligne pour voir si on le fait ou non
954
+    if (strpos(implode('', array_keys($retour)), '.') !== false) {
955
+        foreach ($retour as $cle => $val) {
956
+            if (($pos = strpos($cle, '.')) !== false) {
957
+                $retour[substr($cle, $pos + 1)] = &$retour[$cle];
958
+                unset($retour[$cle]);
959
+            }
960
+        }
961
+    }
962 962
 
963
-	return $retour;
963
+    return $retour;
964 964
 }
965 965
 
966 966
 /**
@@ -973,8 +973,8 @@  discard block
 block discarded – undo
973 973
  * @return bool True si déplacement réussi, false sinon.
974 974
  **/
975 975
 function spip_sqlite_seek($r, $row_number, $serveur = '', $requeter = true) {
976
-	// encore un truc de bien fichu : PDO ne PEUT PAS faire de seek ou de rewind...
977
-	return false;
976
+    // encore un truc de bien fichu : PDO ne PEUT PAS faire de seek ou de rewind...
977
+    return false;
978 978
 }
979 979
 
980 980
 
@@ -990,10 +990,10 @@  discard block
 block discarded – undo
990 990
  * @return bool                True si réussi
991 991
  */
992 992
 function spip_sqlite_free(&$r, $serveur = '', $requeter = true) {
993
-	unset($r);
993
+    unset($r);
994 994
 
995
-	return true;
996
-	//return sqlite_free_result($r);
995
+    return true;
996
+    //return sqlite_free_result($r);
997 997
 }
998 998
 
999 999
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
  * @return void
1009 1009
  */
1010 1010
 function spip_sqlite_get_charset($charset = [], $serveur = '', $requeter = true) {
1011
-	//$c = !$charset ? '' : (" LIKE "._q($charset['charset']));
1012
-	//return spip_sqlite_fetch(sqlite_query(_sqlite_link($serveur), "SHOW CHARACTER SET$c"), NULL, $serveur);
1011
+    //$c = !$charset ? '' : (" LIKE "._q($charset['charset']));
1012
+    //return spip_sqlite_fetch(sqlite_query(_sqlite_link($serveur), "SHOW CHARACTER SET$c"), NULL, $serveur);
1013 1013
 }
1014 1014
 
1015 1015
 
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
  *     Valeur hexadécimale pour SQLite
1025 1025
  **/
1026 1026
 function spip_sqlite_hex($v) {
1027
-	return hexdec($v);
1027
+    return hexdec($v);
1028 1028
 }
1029 1029
 
1030 1030
 
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
  *     Expression de requête SQL
1047 1047
  **/
1048 1048
 function spip_sqlite_in($val, $valeurs, $not = '', $serveur = '', $requeter = true) {
1049
-	return "($val $not IN ($valeurs))";
1049
+    return "($val $not IN ($valeurs))";
1050 1050
 }
1051 1051
 
1052 1052
 
@@ -1074,20 +1074,20 @@  discard block
 block discarded – undo
1074 1074
  **/
1075 1075
 function spip_sqlite_insert($table, $champs, $valeurs, $desc = [], $serveur = '', $requeter = true) {
1076 1076
 
1077
-	$query = "INSERT INTO $table " . ($champs ? "$champs VALUES $valeurs" : 'DEFAULT VALUES');
1078
-	if ($r = spip_sqlite_query($query, $serveur, $requeter)) {
1079
-		if (!$requeter) {
1080
-			return $r;
1081
-		}
1082
-		$nb = spip_sqlite::last_insert_id($serveur);
1083
-	} else {
1084
-		$nb = false;
1085
-	}
1077
+    $query = "INSERT INTO $table " . ($champs ? "$champs VALUES $valeurs" : 'DEFAULT VALUES');
1078
+    if ($r = spip_sqlite_query($query, $serveur, $requeter)) {
1079
+        if (!$requeter) {
1080
+            return $r;
1081
+        }
1082
+        $nb = spip_sqlite::last_insert_id($serveur);
1083
+    } else {
1084
+        $nb = false;
1085
+    }
1086 1086
 
1087
-	$err = spip_sqlite_error($query, $serveur);
1087
+    $err = spip_sqlite_error($query, $serveur);
1088 1088
 
1089
-	// cas particulier : ne pas substituer la reponse spip_sqlite_query si on est en profilage
1090
-	return isset($_GET['var_profile']) ? $r : $nb;
1089
+    // cas particulier : ne pas substituer la reponse spip_sqlite_query si on est en profilage
1090
+    return isset($_GET['var_profile']) ? $r : $nb;
1091 1091
 }
1092 1092
 
1093 1093
 
@@ -1112,28 +1112,28 @@  discard block
 block discarded – undo
1112 1112
  *     - Tableau de description de la requête et du temps d'exécution, si var_profile activé
1113 1113
  **/
1114 1114
 function spip_sqlite_insertq($table, $couples = [], $desc = [], $serveur = '', $requeter = true) {
1115
-	if (!$desc) {
1116
-		$desc = description_table($table, $serveur);
1117
-	}
1118
-	if (!$desc) {
1119
-		die("$table insertion sans description");
1120
-	}
1121
-	$fields = isset($desc['field']) ? $desc['field'] : [];
1115
+    if (!$desc) {
1116
+        $desc = description_table($table, $serveur);
1117
+    }
1118
+    if (!$desc) {
1119
+        die("$table insertion sans description");
1120
+    }
1121
+    $fields = isset($desc['field']) ? $desc['field'] : [];
1122 1122
 
1123
-	foreach ($couples as $champ => $val) {
1124
-		$couples[$champ] = _sqlite_calculer_cite($val, $fields[$champ]);
1125
-	}
1123
+    foreach ($couples as $champ => $val) {
1124
+        $couples[$champ] = _sqlite_calculer_cite($val, $fields[$champ]);
1125
+    }
1126 1126
 
1127
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1128
-	$couples = _sqlite_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1127
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1128
+    $couples = _sqlite_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1129 1129
 
1130
-	$cles = $valeurs = '';
1131
-	if (count($couples)) {
1132
-		$cles = '(' . join(',', array_keys($couples)) . ')';
1133
-		$valeurs = '(' . join(',', $couples) . ')';
1134
-	}
1130
+    $cles = $valeurs = '';
1131
+    if (count($couples)) {
1132
+        $cles = '(' . join(',', array_keys($couples)) . ')';
1133
+        $valeurs = '(' . join(',', $couples) . ')';
1134
+    }
1135 1135
 
1136
-	return spip_sqlite_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
1136
+    return spip_sqlite_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
1137 1137
 }
1138 1138
 
1139 1139
 
@@ -1157,70 +1157,70 @@  discard block
 block discarded – undo
1157 1157
  *     - False en cas d'erreur.
1158 1158
  **/
1159 1159
 function spip_sqlite_insertq_multi($table, $tab_couples = [], $desc = [], $serveur = '', $requeter = true) {
1160
-	if (!$desc) {
1161
-		$desc = description_table($table, $serveur);
1162
-	}
1163
-	if (!$desc) {
1164
-		die("$table insertion sans description");
1165
-	}
1166
-	if (!isset($desc['field'])) {
1167
-		$desc['field'] = [];
1168
-	}
1169
-
1170
-	// recuperer les champs 'timestamp' pour mise a jour auto de ceux-ci
1171
-	$maj = _sqlite_ajouter_champs_timestamp($table, [], $desc, $serveur);
1172
-
1173
-	// seul le nom de la table est a traduire ici :
1174
-	// le faire une seule fois au debut
1175
-	$query_start = "INSERT INTO $table ";
1176
-	$query_start = spip_sqlite::traduire_requete($query_start, $serveur);
1177
-
1178
-	// ouvrir une transaction
1179
-	if ($requeter) {
1180
-		spip_sqlite::demarrer_transaction($serveur);
1181
-	}
1182
-
1183
-	while ($couples = array_shift($tab_couples)) {
1184
-		foreach ($couples as $champ => $val) {
1185
-			$couples[$champ] = _sqlite_calculer_cite($val, $desc['field'][$champ]);
1186
-		}
1187
-
1188
-		// inserer les champs timestamp par defaut
1189
-		$couples = array_merge($maj, $couples);
1190
-
1191
-		$champs = $valeurs = '';
1192
-		if (count($couples)) {
1193
-			$champs = '(' . join(',', array_keys($couples)) . ')';
1194
-			$valeurs = '(' . join(',', $couples) . ')';
1195
-			$query = $query_start . "$champs VALUES $valeurs";
1196
-		} else {
1197
-			$query = $query_start . 'DEFAULT VALUES';
1198
-		}
1199
-
1200
-		if ($requeter) {
1201
-			$retour = spip_sqlite::executer_requete($query, $serveur);
1202
-		}
1203
-
1204
-		// sur le dernier couple uniquement
1205
-		if (!count($tab_couples)) {
1206
-			$nb = 0;
1207
-			if ($requeter) {
1208
-				$nb = spip_sqlite::last_insert_id($serveur);
1209
-			} else {
1210
-				return $query;
1211
-			}
1212
-		}
1213
-
1214
-		$err = spip_sqlite_error($query, $serveur);
1215
-	}
1216
-
1217
-	if ($requeter) {
1218
-		spip_sqlite::finir_transaction($serveur);
1219
-	}
1220
-
1221
-	// renvoie le dernier id d'autoincrement ajoute
1222
-	// cas particulier : ne pas substituer la reponse spip_sqlite_query si on est en profilage
1223
-	return isset($_GET['var_profile']) ? $retour : $nb;
1160
+    if (!$desc) {
1161
+        $desc = description_table($table, $serveur);
1162
+    }
1163
+    if (!$desc) {
1164
+        die("$table insertion sans description");
1165
+    }
1166
+    if (!isset($desc['field'])) {
1167
+        $desc['field'] = [];
1168
+    }
1169
+
1170
+    // recuperer les champs 'timestamp' pour mise a jour auto de ceux-ci
1171
+    $maj = _sqlite_ajouter_champs_timestamp($table, [], $desc, $serveur);
1172
+
1173
+    // seul le nom de la table est a traduire ici :
1174
+    // le faire une seule fois au debut
1175
+    $query_start = "INSERT INTO $table ";
1176
+    $query_start = spip_sqlite::traduire_requete($query_start, $serveur);
1177
+
1178
+    // ouvrir une transaction
1179
+    if ($requeter) {
1180
+        spip_sqlite::demarrer_transaction($serveur);
1181
+    }
1182
+
1183
+    while ($couples = array_shift($tab_couples)) {
1184
+        foreach ($couples as $champ => $val) {
1185
+            $couples[$champ] = _sqlite_calculer_cite($val, $desc['field'][$champ]);
1186
+        }
1187
+
1188
+        // inserer les champs timestamp par defaut
1189
+        $couples = array_merge($maj, $couples);
1190
+
1191
+        $champs = $valeurs = '';
1192
+        if (count($couples)) {
1193
+            $champs = '(' . join(',', array_keys($couples)) . ')';
1194
+            $valeurs = '(' . join(',', $couples) . ')';
1195
+            $query = $query_start . "$champs VALUES $valeurs";
1196
+        } else {
1197
+            $query = $query_start . 'DEFAULT VALUES';
1198
+        }
1199
+
1200
+        if ($requeter) {
1201
+            $retour = spip_sqlite::executer_requete($query, $serveur);
1202
+        }
1203
+
1204
+        // sur le dernier couple uniquement
1205
+        if (!count($tab_couples)) {
1206
+            $nb = 0;
1207
+            if ($requeter) {
1208
+                $nb = spip_sqlite::last_insert_id($serveur);
1209
+            } else {
1210
+                return $query;
1211
+            }
1212
+        }
1213
+
1214
+        $err = spip_sqlite_error($query, $serveur);
1215
+    }
1216
+
1217
+    if ($requeter) {
1218
+        spip_sqlite::finir_transaction($serveur);
1219
+    }
1220
+
1221
+    // renvoie le dernier id d'autoincrement ajoute
1222
+    // cas particulier : ne pas substituer la reponse spip_sqlite_query si on est en profilage
1223
+    return isset($_GET['var_profile']) ? $retour : $nb;
1224 1224
 }
1225 1225
 
1226 1226
 
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
  *     Toujours true.
1236 1236
  **/
1237 1237
 function spip_sqlite_preferer_transaction($serveur = '', $requeter = true) {
1238
-	return true;
1238
+    return true;
1239 1239
 }
1240 1240
 
1241 1241
 /**
@@ -1252,12 +1252,12 @@  discard block
 block discarded – undo
1252 1252
  *     string si texte de la requête demandé, true sinon
1253 1253
  **/
1254 1254
 function spip_sqlite_demarrer_transaction($serveur = '', $requeter = true) {
1255
-	if (!$requeter) {
1256
-		return 'BEGIN TRANSACTION';
1257
-	}
1258
-	spip_sqlite::demarrer_transaction($serveur);
1255
+    if (!$requeter) {
1256
+        return 'BEGIN TRANSACTION';
1257
+    }
1258
+    spip_sqlite::demarrer_transaction($serveur);
1259 1259
 
1260
-	return true;
1260
+    return true;
1261 1261
 }
1262 1262
 
1263 1263
 /**
@@ -1271,12 +1271,12 @@  discard block
 block discarded – undo
1271 1271
  *     string si texte de la requête demandé, true sinon
1272 1272
  **/
1273 1273
 function spip_sqlite_terminer_transaction($serveur = '', $requeter = true) {
1274
-	if (!$requeter) {
1275
-		return 'COMMIT';
1276
-	}
1277
-	spip_sqlite::finir_transaction($serveur);
1274
+    if (!$requeter) {
1275
+        return 'COMMIT';
1276
+    }
1277
+    spip_sqlite::finir_transaction($serveur);
1278 1278
 
1279
-	return true;
1279
+    return true;
1280 1280
 }
1281 1281
 
1282 1282
 
@@ -1291,27 +1291,27 @@  discard block
 block discarded – undo
1291 1291
  *     Liste des noms de bases
1292 1292
  **/
1293 1293
 function spip_sqlite_listdbs($serveur = '', $requeter = true) {
1294
-	_sqlite_init();
1294
+    _sqlite_init();
1295 1295
 
1296
-	if (!is_dir($d = substr(_DIR_DB, 0, -1))) {
1297
-		return [];
1298
-	}
1296
+    if (!is_dir($d = substr(_DIR_DB, 0, -1))) {
1297
+        return [];
1298
+    }
1299 1299
 
1300
-	include_spip('inc/flock');
1301
-	$bases = preg_files($d, $pattern = '(.*)\.sqlite$');
1302
-	$bds = [];
1300
+    include_spip('inc/flock');
1301
+    $bases = preg_files($d, $pattern = '(.*)\.sqlite$');
1302
+    $bds = [];
1303 1303
 
1304
-	foreach ($bases as $b) {
1305
-		// pas de bases commencant pas sqlite
1306
-		// (on s'en sert pour l'installation pour simuler la presence d'un serveur)
1307
-		// les bases sont de la forme _sqliteX_tmp_spip_install.sqlite
1308
-		if (strpos($b, '_sqlite')) {
1309
-			continue;
1310
-		}
1311
-		$bds[] = preg_replace(";.*/$pattern;iS", '$1', $b);
1312
-	}
1304
+    foreach ($bases as $b) {
1305
+        // pas de bases commencant pas sqlite
1306
+        // (on s'en sert pour l'installation pour simuler la presence d'un serveur)
1307
+        // les bases sont de la forme _sqliteX_tmp_spip_install.sqlite
1308
+        if (strpos($b, '_sqlite')) {
1309
+            continue;
1310
+        }
1311
+        $bds[] = preg_replace(";.*/$pattern;iS", '$1', $b);
1312
+    }
1313 1313
 
1314
-	return $bds;
1314
+    return $bds;
1315 1315
 }
1316 1316
 
1317 1317
 
@@ -1326,9 +1326,9 @@  discard block
 block discarded – undo
1326 1326
  * @return string       Texte de sélection pour la requête
1327 1327
  */
1328 1328
 function spip_sqlite_multi($objet, $lang) {
1329
-	$r = 'EXTRAIRE_MULTI(' . $objet . ", '" . $lang . "') AS multi";
1329
+    $r = 'EXTRAIRE_MULTI(' . $objet . ", '" . $lang . "') AS multi";
1330 1330
 
1331
-	return $r;
1331
+    return $r;
1332 1332
 }
1333 1333
 
1334 1334
 
@@ -1345,15 +1345,15 @@  discard block
 block discarded – undo
1345 1345
  * @return bool|string true / false / requete
1346 1346
  **/
1347 1347
 function spip_sqlite_optimize($table, $serveur = '', $requeter = true) {
1348
-	static $do = false;
1349
-	if ($requeter and $do) {
1350
-		return true;
1351
-	}
1352
-	if ($requeter) {
1353
-		$do = true;
1354
-	}
1348
+    static $do = false;
1349
+    if ($requeter and $do) {
1350
+        return true;
1351
+    }
1352
+    if ($requeter) {
1353
+        $do = true;
1354
+    }
1355 1355
 
1356
-	return spip_sqlite_query('VACUUM', $serveur, $requeter);
1356
+    return spip_sqlite_query('VACUUM', $serveur, $requeter);
1357 1357
 }
1358 1358
 
1359 1359
 
@@ -1370,15 +1370,15 @@  discard block
 block discarded – undo
1370 1370
  *    Donnée prête à être utilisée par le gestionnaire SQL
1371 1371
  */
1372 1372
 function spip_sqlite_quote($v, $type = '') {
1373
-	if (!is_array($v)) {
1374
-		return _sqlite_calculer_cite($v, $type);
1375
-	}
1376
-	// si c'est un tableau, le parcourir en propageant le type
1377
-	foreach ($v as $k => $r) {
1378
-		$v[$k] = spip_sqlite_quote($r, $type);
1379
-	}
1373
+    if (!is_array($v)) {
1374
+        return _sqlite_calculer_cite($v, $type);
1375
+    }
1376
+    // si c'est un tableau, le parcourir en propageant le type
1377
+    foreach ($v as $k => $r) {
1378
+        $v[$k] = spip_sqlite_quote($r, $type);
1379
+    }
1380 1380
 
1381
-	return join(',', $v);
1381
+    return join(',', $v);
1382 1382
 }
1383 1383
 
1384 1384
 
@@ -1395,9 +1395,9 @@  discard block
 block discarded – undo
1395 1395
  *     Expression SQL
1396 1396
  **/
1397 1397
 function spip_sqlite_date_proche($champ, $interval, $unite) {
1398
-	$op = (($interval <= 0) ? '>' : '<');
1398
+    $op = (($interval <= 0) ? '>' : '<');
1399 1399
 
1400
-	return "($champ $op datetime('" . date('Y-m-d H:i:s') . "', '$interval $unite'))";
1400
+    return "($champ $op datetime('" . date('Y-m-d H:i:s') . "', '$interval $unite'))";
1401 1401
 }
1402 1402
 
1403 1403
 
@@ -1415,48 +1415,48 @@  discard block
 block discarded – undo
1415 1415
  *     l'état de la table après la réparation
1416 1416
  */
1417 1417
 function spip_sqlite_repair($table, $serveur = '', $requeter = true) {
1418
-	if (
1419
-		$desc = spip_sqlite_showtable($table, $serveur)
1420
-		and isset($desc['field'])
1421
-		and is_array($desc['field'])
1422
-	) {
1423
-		foreach ($desc['field'] as $c => $d) {
1424
-			if (
1425
-				preg_match(',^(tinytext|mediumtext|text|longtext|varchar|char),i', $d)
1426
-				and stripos($d, 'NOT NULL') !== false
1427
-				and stripos($d, 'DEFAULT') === false
1428
-				/* pas touche aux cles primaires */
1429
-				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1430
-			) {
1431
-				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT ''", $serveur);
1432
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1433
-			}
1434
-			if (
1435
-				preg_match(',^(INTEGER),i', $d)
1436
-				and stripos($d, 'NOT NULL') !== false
1437
-				and stripos($d, 'DEFAULT') === false
1438
-				/* pas touche aux cles primaires */
1439
-				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1440
-			) {
1441
-				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0'", $serveur);
1442
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1443
-			}
1444
-			if (
1445
-				preg_match(',^(datetime),i', $d)
1446
-				and stripos($d, 'NOT NULL') !== false
1447
-				and stripos($d, 'DEFAULT') === false
1448
-				/* pas touche aux cles primaires */
1449
-				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1450
-			) {
1451
-				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0000-00-00 00:00:00'", $serveur);
1452
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1453
-			}
1454
-		}
1455
-
1456
-		return [' OK '];
1457
-	}
1458
-
1459
-	return [' ERROR '];
1418
+    if (
1419
+        $desc = spip_sqlite_showtable($table, $serveur)
1420
+        and isset($desc['field'])
1421
+        and is_array($desc['field'])
1422
+    ) {
1423
+        foreach ($desc['field'] as $c => $d) {
1424
+            if (
1425
+                preg_match(',^(tinytext|mediumtext|text|longtext|varchar|char),i', $d)
1426
+                and stripos($d, 'NOT NULL') !== false
1427
+                and stripos($d, 'DEFAULT') === false
1428
+                /* pas touche aux cles primaires */
1429
+                and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1430
+            ) {
1431
+                spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT ''", $serveur);
1432
+                spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1433
+            }
1434
+            if (
1435
+                preg_match(',^(INTEGER),i', $d)
1436
+                and stripos($d, 'NOT NULL') !== false
1437
+                and stripos($d, 'DEFAULT') === false
1438
+                /* pas touche aux cles primaires */
1439
+                and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1440
+            ) {
1441
+                spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0'", $serveur);
1442
+                spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1443
+            }
1444
+            if (
1445
+                preg_match(',^(datetime),i', $d)
1446
+                and stripos($d, 'NOT NULL') !== false
1447
+                and stripos($d, 'DEFAULT') === false
1448
+                /* pas touche aux cles primaires */
1449
+                and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1450
+            ) {
1451
+                spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0000-00-00 00:00:00'", $serveur);
1452
+                spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1453
+            }
1454
+        }
1455
+
1456
+        return [' OK '];
1457
+    }
1458
+
1459
+    return [' ERROR '];
1460 1460
 }
1461 1461
 
1462 1462
 
@@ -1485,25 +1485,25 @@  discard block
 block discarded – undo
1485 1485
  *     - False en cas d'erreur.
1486 1486
  **/
1487 1487
 function spip_sqlite_replace($table, $couples, $desc = [], $serveur = '', $requeter = true) {
1488
-	if (!$desc) {
1489
-		$desc = description_table($table, $serveur);
1490
-	}
1491
-	if (!$desc) {
1492
-		die("$table insertion sans description");
1493
-	}
1494
-	$fields = isset($desc['field']) ? $desc['field'] : [];
1488
+    if (!$desc) {
1489
+        $desc = description_table($table, $serveur);
1490
+    }
1491
+    if (!$desc) {
1492
+        die("$table insertion sans description");
1493
+    }
1494
+    $fields = isset($desc['field']) ? $desc['field'] : [];
1495 1495
 
1496
-	foreach ($couples as $champ => $val) {
1497
-		$couples[$champ] = _sqlite_calculer_cite($val, $fields[$champ]);
1498
-	}
1496
+    foreach ($couples as $champ => $val) {
1497
+        $couples[$champ] = _sqlite_calculer_cite($val, $fields[$champ]);
1498
+    }
1499 1499
 
1500
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1501
-	$couples = _sqlite_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1500
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1501
+    $couples = _sqlite_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1502 1502
 
1503
-	return spip_sqlite_query("REPLACE INTO $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1504
-		',',
1505
-		$couples
1506
-	) . ')', $serveur);
1503
+    return spip_sqlite_query("REPLACE INTO $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1504
+        ',',
1505
+        $couples
1506
+    ) . ')', $serveur);
1507 1507
 }
1508 1508
 
1509 1509
 
@@ -1533,13 +1533,13 @@  discard block
 block discarded – undo
1533 1533
  **/
1534 1534
 function spip_sqlite_replace_multi($table, $tab_couples, $desc = [], $serveur = '', $requeter = true) {
1535 1535
 
1536
-	// boucler pour trainter chaque requete independemment
1537
-	foreach ($tab_couples as $couples) {
1538
-		$retour = spip_sqlite_replace($table, $couples, $desc, $serveur, $requeter);
1539
-	}
1536
+    // boucler pour trainter chaque requete independemment
1537
+    foreach ($tab_couples as $couples) {
1538
+        $retour = spip_sqlite_replace($table, $couples, $desc, $serveur, $requeter);
1539
+    }
1540 1540
 
1541
-	// renvoie le dernier id
1542
-	return $retour;
1541
+    // renvoie le dernier id
1542
+    return $retour;
1543 1543
 }
1544 1544
 
1545 1545
 
@@ -1566,44 +1566,44 @@  discard block
 block discarded – undo
1566 1566
  *     - array  : Tableau décrivant requête et temps d'exécution si var_profile actif pour tracer.
1567 1567
  */
1568 1568
 function spip_sqlite_select(
1569
-	$select,
1570
-	$from,
1571
-	$where = '',
1572
-	$groupby = '',
1573
-	$orderby = '',
1574
-	$limit = '',
1575
-	$having = '',
1576
-	$serveur = '',
1577
-	$requeter = true
1569
+    $select,
1570
+    $from,
1571
+    $where = '',
1572
+    $groupby = '',
1573
+    $orderby = '',
1574
+    $limit = '',
1575
+    $having = '',
1576
+    $serveur = '',
1577
+    $requeter = true
1578 1578
 ) {
1579 1579
 
1580
-	// version() n'est pas connu de sqlite
1581
-	$select = str_replace('version()', 'sqlite_version()', $select);
1580
+    // version() n'est pas connu de sqlite
1581
+    $select = str_replace('version()', 'sqlite_version()', $select);
1582 1582
 
1583
-	// recomposer from
1584
-	$from = (!is_array($from) ? $from : _sqlite_calculer_select_as($from));
1583
+    // recomposer from
1584
+    $from = (!is_array($from) ? $from : _sqlite_calculer_select_as($from));
1585 1585
 
1586
-	$query =
1587
-		_sqlite_calculer_expression('SELECT', $select, ', ')
1588
-		. _sqlite_calculer_expression('FROM', $from, ', ')
1589
-		. _sqlite_calculer_expression('WHERE', $where)
1590
-		. _sqlite_calculer_expression('GROUP BY', $groupby, ',')
1591
-		. _sqlite_calculer_expression('HAVING', $having)
1592
-		. ($orderby ? ("\nORDER BY " . _sqlite_calculer_order($orderby)) : '')
1593
-		. ($limit ? "\nLIMIT $limit" : '');
1586
+    $query =
1587
+        _sqlite_calculer_expression('SELECT', $select, ', ')
1588
+        . _sqlite_calculer_expression('FROM', $from, ', ')
1589
+        . _sqlite_calculer_expression('WHERE', $where)
1590
+        . _sqlite_calculer_expression('GROUP BY', $groupby, ',')
1591
+        . _sqlite_calculer_expression('HAVING', $having)
1592
+        . ($orderby ? ("\nORDER BY " . _sqlite_calculer_order($orderby)) : '')
1593
+        . ($limit ? "\nLIMIT $limit" : '');
1594 1594
 
1595
-	// dans un select, on doit renvoyer la requête en cas d'erreur
1596
-	$res = spip_sqlite_query($query, $serveur, $requeter);
1597
-	// texte de la requete demande ?
1598
-	if (!$requeter) {
1599
-		return $res;
1600
-	}
1601
-	// erreur survenue ?
1602
-	if ($res === false) {
1603
-		return spip_sqlite::traduire_requete($query, $serveur);
1604
-	}
1595
+    // dans un select, on doit renvoyer la requête en cas d'erreur
1596
+    $res = spip_sqlite_query($query, $serveur, $requeter);
1597
+    // texte de la requete demande ?
1598
+    if (!$requeter) {
1599
+        return $res;
1600
+    }
1601
+    // erreur survenue ?
1602
+    if ($res === false) {
1603
+        return spip_sqlite::traduire_requete($query, $serveur);
1604
+    }
1605 1605
 
1606
-	return $res;
1606
+    return $res;
1607 1607
 }
1608 1608
 
1609 1609
 
@@ -1622,32 +1622,32 @@  discard block
 block discarded – undo
1622 1622
  *     - False en cas d'erreur.
1623 1623
  **/
1624 1624
 function spip_sqlite_selectdb($db, $serveur = '', $requeter = true) {
1625
-	_sqlite_init();
1625
+    _sqlite_init();
1626 1626
 
1627
-	// interdire la creation d'une nouvelle base,
1628
-	// sauf si on est dans l'installation
1629
-	if (
1630
-		!is_file($f = _DIR_DB . $db . '.sqlite')
1631
-		&& (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)
1632
-	) {
1633
-		spip_log("Il est interdit de creer la base $db", 'sqlite.' . _LOG_HS);
1627
+    // interdire la creation d'une nouvelle base,
1628
+    // sauf si on est dans l'installation
1629
+    if (
1630
+        !is_file($f = _DIR_DB . $db . '.sqlite')
1631
+        && (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)
1632
+    ) {
1633
+        spip_log("Il est interdit de creer la base $db", 'sqlite.' . _LOG_HS);
1634 1634
 
1635
-		return false;
1636
-	}
1635
+        return false;
1636
+    }
1637 1637
 
1638
-	// se connecter a la base indiquee
1639
-	// avec les identifiants connus
1640
-	$index = $serveur ? $serveur : 0;
1638
+    // se connecter a la base indiquee
1639
+    // avec les identifiants connus
1640
+    $index = $serveur ? $serveur : 0;
1641 1641
 
1642
-	if ($link = spip_connect_db('', '', '', '', '@selectdb@' . $db, $serveur, '', '')) {
1643
-		if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
1644
-			return $db;
1645
-		}
1646
-	} else {
1647
-		spip_log("Impossible de selectionner la base $db", 'sqlite.' . _LOG_HS);
1642
+    if ($link = spip_connect_db('', '', '', '', '@selectdb@' . $db, $serveur, '', '')) {
1643
+        if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
1644
+            return $db;
1645
+        }
1646
+    } else {
1647
+        spip_log("Impossible de selectionner la base $db", 'sqlite.' . _LOG_HS);
1648 1648
 
1649
-		return false;
1650
-	}
1649
+        return false;
1650
+    }
1651 1651
 }
1652 1652
 
1653 1653
 
@@ -1662,8 +1662,8 @@  discard block
 block discarded – undo
1662 1662
  * @return void
1663 1663
  */
1664 1664
 function spip_sqlite_set_charset($charset, $serveur = '', $requeter = true) {
1665
-	# spip_log("Gestion charset sql a ecrire : "."SET NAMES "._q($charset), 'sqlite.'._LOG_ERREUR);
1666
-	# return spip_sqlite_query("SET NAMES ". spip_sqlite_quote($charset), $serveur); //<-- Passe pas !
1665
+    # spip_log("Gestion charset sql a ecrire : "."SET NAMES "._q($charset), 'sqlite.'._LOG_ERREUR);
1666
+    # return spip_sqlite_query("SET NAMES ". spip_sqlite_quote($charset), $serveur); //<-- Passe pas !
1667 1667
 }
1668 1668
 
1669 1669
 
@@ -1681,24 +1681,24 @@  discard block
 block discarded – undo
1681 1681
  *     Ressource à utiliser avec sql_fetch()
1682 1682
  **/
1683 1683
 function spip_sqlite_showbase($match, $serveur = '', $requeter = true) {
1684
-	// type est le type d'entrée : table / index / view
1685
-	// on ne retourne que les tables (?) et non les vues...
1686
-	# ESCAPE non supporte par les versions sqlite <3
1687
-	#	return spip_sqlite_query("SELECT name FROM sqlite_master WHERE type='table' AND tbl_name LIKE "._q($match)." ESCAPE '\'", $serveur, $requeter);
1688
-	$match = preg_quote($match);
1689
-	$match = str_replace('\\\_', '[[TIRETBAS]]', $match);
1690
-	$match = str_replace('\\\%', '[[POURCENT]]', $match);
1691
-	$match = str_replace('_', '.', $match);
1692
-	$match = str_replace('%', '.*', $match);
1693
-	$match = str_replace('[[TIRETBAS]]', '_', $match);
1694
-	$match = str_replace('[[POURCENT]]', '%', $match);
1695
-	$match = "^$match$";
1696
-
1697
-	return spip_sqlite_query(
1698
-		"SELECT name FROM sqlite_master WHERE type='table' AND tbl_name REGEXP " . _q($match),
1699
-		$serveur,
1700
-		$requeter
1701
-	);
1684
+    // type est le type d'entrée : table / index / view
1685
+    // on ne retourne que les tables (?) et non les vues...
1686
+    # ESCAPE non supporte par les versions sqlite <3
1687
+    #	return spip_sqlite_query("SELECT name FROM sqlite_master WHERE type='table' AND tbl_name LIKE "._q($match)." ESCAPE '\'", $serveur, $requeter);
1688
+    $match = preg_quote($match);
1689
+    $match = str_replace('\\\_', '[[TIRETBAS]]', $match);
1690
+    $match = str_replace('\\\%', '[[POURCENT]]', $match);
1691
+    $match = str_replace('_', '.', $match);
1692
+    $match = str_replace('%', '.*', $match);
1693
+    $match = str_replace('[[TIRETBAS]]', '_', $match);
1694
+    $match = str_replace('[[POURCENT]]', '%', $match);
1695
+    $match = "^$match$";
1696
+
1697
+    return spip_sqlite_query(
1698
+        "SELECT name FROM sqlite_master WHERE type='table' AND tbl_name REGEXP " . _q($match),
1699
+        $serveur,
1700
+        $requeter
1701
+    );
1702 1702
 }
1703 1703
 
1704 1704
 /**
@@ -1716,19 +1716,19 @@  discard block
 block discarded – undo
1716 1716
  *     - string : requete sql, si $requeter = true
1717 1717
  **/
1718 1718
 function spip_sqlite_table_exists(string $table, $serveur = '', $requeter = true) {
1719
-	$r = spip_sqlite_query(
1720
-		'SELECT name FROM sqlite_master WHERE'
1721
-		. ' type=\'table\''
1722
-		. ' AND name=' . spip_sqlite_quote($table, 'string')
1723
-		. ' AND name NOT LIKE \'sqlite_%\'',
1724
-		$serveur,
1725
-		$requeter
1726
-	);
1727
-	if (!$requeter) {
1728
-		return $r;
1729
-	}
1730
-	$res = spip_sqlite_fetch($r);
1731
-	return (bool) $res;
1719
+    $r = spip_sqlite_query(
1720
+        'SELECT name FROM sqlite_master WHERE'
1721
+        . ' type=\'table\''
1722
+        . ' AND name=' . spip_sqlite_quote($table, 'string')
1723
+        . ' AND name NOT LIKE \'sqlite_%\'',
1724
+        $serveur,
1725
+        $requeter
1726
+    );
1727
+    if (!$requeter) {
1728
+        return $r;
1729
+    }
1730
+    $res = spip_sqlite_fetch($r);
1731
+    return (bool) $res;
1732 1732
 }
1733 1733
 
1734 1734
 define('_SQLITE_RE_SHOW_TABLE', '/^[^(),]*\(((?:[^()]*\((?:[^()]*\([^()]*\))?[^()]*\)[^()]*)*[^()]*)\)[^()]*$/');
@@ -1751,129 +1751,129 @@  discard block
 block discarded – undo
1751 1751
  *     - array description de la table sinon
1752 1752
  */
1753 1753
 function spip_sqlite_showtable($nom_table, $serveur = '', $requeter = true) {
1754
-	$query =
1755
-		'SELECT sql, type FROM'
1756
-		. ' (SELECT * FROM sqlite_master UNION ALL'
1757
-		. ' SELECT * FROM sqlite_temp_master)'
1758
-		. " WHERE tbl_name LIKE '$nom_table'"
1759
-		. " AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'"
1760
-		. ' ORDER BY substr(type,2,1), name';
1761
-
1762
-	$a = spip_sqlite_query($query, $serveur, $requeter);
1763
-	if (!$a) {
1764
-		return '';
1765
-	}
1766
-	if (!$requeter) {
1767
-		return $a;
1768
-	}
1769
-	if (!($a = spip_sqlite_fetch($a, null, $serveur))) {
1770
-		return '';
1771
-	}
1772
-	$vue = ($a['type'] == 'view'); // table | vue
1773
-
1774
-	// c'est une table
1775
-	// il faut parser le create
1776
-	if (!$vue) {
1777
-		if (!preg_match(_SQLITE_RE_SHOW_TABLE, array_shift($a), $r)) {
1778
-			return '';
1779
-		} else {
1780
-			$desc = $r[1];
1781
-			// extraction d'une KEY éventuelle en prenant garde de ne pas
1782
-			// relever un champ dont le nom contient KEY (ex. ID_WHISKEY)
1783
-			if (preg_match('/^(.*?),([^,]*\sKEY[ (].*)$/s', $desc, $r)) {
1784
-				$namedkeys = $r[2];
1785
-				$desc = $r[1];
1786
-			} else {
1787
-				$namedkeys = '';
1788
-			}
1789
-
1790
-			$fields = [];
1791
-			$keys = [];
1792
-
1793
-			// enlever les contenus des valeurs DEFAULT 'xxx' qui pourraient perturber
1794
-			// par exemple s'il contiennent une virgule.
1795
-			// /!\ cela peut aussi echapper le nom des champs si la table a eu des operations avec SQLite Manager !
1796
-			list($desc, $echaps) = query_echappe_textes($desc);
1797
-
1798
-			// separer toutes les descriptions de champs, separes par des virgules
1799
-			# /!\ explode peut exploser aussi DECIMAL(10,2) !
1800
-			$k_precedent = null;
1801
-			foreach (explode(',', $desc) as $v) {
1802
-				preg_match('/^\s*([^\s]+)\s+(.*)/', $v, $r);
1803
-				// Les cles de champs peuvent etre entourees
1804
-				// de guillements doubles " , simples ', graves ` ou de crochets [ ],  ou rien.
1805
-				// http://www.sqlite.org/lang_keywords.html
1806
-				$k = strtolower(query_reinjecte_textes($r[1], $echaps)); // champ, "champ", [champ]...
1807
-				if ($char = strpbrk($k[0], '\'"[`')) {
1808
-					$k = trim($k, $char);
1809
-					if ($char == '[') {
1810
-						$k = rtrim($k, ']');
1811
-					}
1812
-				}
1813
-				$def = query_reinjecte_textes($r[2], $echaps); // valeur du champ
1814
-
1815
-				// rustine pour DECIMAL(10,2)
1816
-				// s'il y a une parenthèse fermante dans la clé
1817
-				// ou dans la définition sans qu'il n'y ait une ouverture avant
1818
-				if (false !== strpos($k, ')') or preg_match('/^[^\(]*\)/', $def)) {
1819
-					$fields[$k_precedent] .= ',' . $k . ' ' . $def;
1820
-					continue;
1821
-				}
1822
-
1823
-				// la primary key peut etre dans une des descriptions de champs
1824
-				// et non en fin de table, cas encore decouvert avec Sqlite Manager
1825
-				if (stripos($r[2], 'PRIMARY KEY') !== false) {
1826
-					$keys['PRIMARY KEY'] = $k;
1827
-				}
1828
-
1829
-				$fields[$k] = $def;
1830
-				$k_precedent = $k;
1831
-			}
1832
-			// key inclues dans la requete
1833
-			foreach (preg_split('/\)\s*(,|$)/', $namedkeys) as $v) {
1834
-				if (preg_match('/^\s*([^(]*)\(([^(]*(\(\d+\))?)$/', $v, $r)) {
1835
-					$k = str_replace('`', '', trim($r[1]));
1836
-					$t = trim(strtolower(str_replace('`', '', $r[2])), '"');
1837
-					if ($k && !isset($keys[$k])) {
1838
-						$keys[$k] = $t;
1839
-					} else {
1840
-						$keys[] = $t;
1841
-					}
1842
-				}
1843
-			}
1844
-			// sinon ajouter les key index
1845
-			$query =
1846
-				'SELECT name,sql FROM'
1847
-				. ' (SELECT * FROM sqlite_master UNION ALL'
1848
-				. ' SELECT * FROM sqlite_temp_master)'
1849
-				. " WHERE tbl_name LIKE '$nom_table'"
1850
-				. " AND type='index' AND name NOT LIKE 'sqlite_%'"
1851
-				. 'ORDER BY substr(type,2,1), name';
1852
-			$a = spip_sqlite_query($query, $serveur, $requeter);
1853
-			while ($r = spip_sqlite_fetch($a, null, $serveur)) {
1854
-				$key = str_replace($nom_table . '_', '', $r['name']); // enlever le nom de la table ajoute a l'index
1855
-				$keytype = 'KEY';
1856
-				if (strpos($r['sql'], 'UNIQUE INDEX') !== false) {
1857
-					$keytype = 'UNIQUE KEY';
1858
-				}
1859
-				$colonnes = preg_replace(',.*\((.*)\).*,', '$1', $r['sql']);
1860
-				$keys[$keytype . ' ' . $key] = $colonnes;
1861
-			}
1862
-		}
1863
-	} // c'est une vue, on liste les champs disponibles simplement
1864
-	else {
1865
-		if ($res = sql_fetsel('*', $nom_table, '', '', '', '1', '', $serveur)) { // limit 1
1866
-			$fields = [];
1867
-			foreach ($res as $c => $v) {
1868
-				$fields[$c] = '';
1869
-			}
1870
-			$keys = [];
1871
-		} else {
1872
-			return '';
1873
-		}
1874
-	}
1875
-
1876
-	return ['field' => $fields, 'key' => $keys];
1754
+    $query =
1755
+        'SELECT sql, type FROM'
1756
+        . ' (SELECT * FROM sqlite_master UNION ALL'
1757
+        . ' SELECT * FROM sqlite_temp_master)'
1758
+        . " WHERE tbl_name LIKE '$nom_table'"
1759
+        . " AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'"
1760
+        . ' ORDER BY substr(type,2,1), name';
1761
+
1762
+    $a = spip_sqlite_query($query, $serveur, $requeter);
1763
+    if (!$a) {
1764
+        return '';
1765
+    }
1766
+    if (!$requeter) {
1767
+        return $a;
1768
+    }
1769
+    if (!($a = spip_sqlite_fetch($a, null, $serveur))) {
1770
+        return '';
1771
+    }
1772
+    $vue = ($a['type'] == 'view'); // table | vue
1773
+
1774
+    // c'est une table
1775
+    // il faut parser le create
1776
+    if (!$vue) {
1777
+        if (!preg_match(_SQLITE_RE_SHOW_TABLE, array_shift($a), $r)) {
1778
+            return '';
1779
+        } else {
1780
+            $desc = $r[1];
1781
+            // extraction d'une KEY éventuelle en prenant garde de ne pas
1782
+            // relever un champ dont le nom contient KEY (ex. ID_WHISKEY)
1783
+            if (preg_match('/^(.*?),([^,]*\sKEY[ (].*)$/s', $desc, $r)) {
1784
+                $namedkeys = $r[2];
1785
+                $desc = $r[1];
1786
+            } else {
1787
+                $namedkeys = '';
1788
+            }
1789
+
1790
+            $fields = [];
1791
+            $keys = [];
1792
+
1793
+            // enlever les contenus des valeurs DEFAULT 'xxx' qui pourraient perturber
1794
+            // par exemple s'il contiennent une virgule.
1795
+            // /!\ cela peut aussi echapper le nom des champs si la table a eu des operations avec SQLite Manager !
1796
+            list($desc, $echaps) = query_echappe_textes($desc);
1797
+
1798
+            // separer toutes les descriptions de champs, separes par des virgules
1799
+            # /!\ explode peut exploser aussi DECIMAL(10,2) !
1800
+            $k_precedent = null;
1801
+            foreach (explode(',', $desc) as $v) {
1802
+                preg_match('/^\s*([^\s]+)\s+(.*)/', $v, $r);
1803
+                // Les cles de champs peuvent etre entourees
1804
+                // de guillements doubles " , simples ', graves ` ou de crochets [ ],  ou rien.
1805
+                // http://www.sqlite.org/lang_keywords.html
1806
+                $k = strtolower(query_reinjecte_textes($r[1], $echaps)); // champ, "champ", [champ]...
1807
+                if ($char = strpbrk($k[0], '\'"[`')) {
1808
+                    $k = trim($k, $char);
1809
+                    if ($char == '[') {
1810
+                        $k = rtrim($k, ']');
1811
+                    }
1812
+                }
1813
+                $def = query_reinjecte_textes($r[2], $echaps); // valeur du champ
1814
+
1815
+                // rustine pour DECIMAL(10,2)
1816
+                // s'il y a une parenthèse fermante dans la clé
1817
+                // ou dans la définition sans qu'il n'y ait une ouverture avant
1818
+                if (false !== strpos($k, ')') or preg_match('/^[^\(]*\)/', $def)) {
1819
+                    $fields[$k_precedent] .= ',' . $k . ' ' . $def;
1820
+                    continue;
1821
+                }
1822
+
1823
+                // la primary key peut etre dans une des descriptions de champs
1824
+                // et non en fin de table, cas encore decouvert avec Sqlite Manager
1825
+                if (stripos($r[2], 'PRIMARY KEY') !== false) {
1826
+                    $keys['PRIMARY KEY'] = $k;
1827
+                }
1828
+
1829
+                $fields[$k] = $def;
1830
+                $k_precedent = $k;
1831
+            }
1832
+            // key inclues dans la requete
1833
+            foreach (preg_split('/\)\s*(,|$)/', $namedkeys) as $v) {
1834
+                if (preg_match('/^\s*([^(]*)\(([^(]*(\(\d+\))?)$/', $v, $r)) {
1835
+                    $k = str_replace('`', '', trim($r[1]));
1836
+                    $t = trim(strtolower(str_replace('`', '', $r[2])), '"');
1837
+                    if ($k && !isset($keys[$k])) {
1838
+                        $keys[$k] = $t;
1839
+                    } else {
1840
+                        $keys[] = $t;
1841
+                    }
1842
+                }
1843
+            }
1844
+            // sinon ajouter les key index
1845
+            $query =
1846
+                'SELECT name,sql FROM'
1847
+                . ' (SELECT * FROM sqlite_master UNION ALL'
1848
+                . ' SELECT * FROM sqlite_temp_master)'
1849
+                . " WHERE tbl_name LIKE '$nom_table'"
1850
+                . " AND type='index' AND name NOT LIKE 'sqlite_%'"
1851
+                . 'ORDER BY substr(type,2,1), name';
1852
+            $a = spip_sqlite_query($query, $serveur, $requeter);
1853
+            while ($r = spip_sqlite_fetch($a, null, $serveur)) {
1854
+                $key = str_replace($nom_table . '_', '', $r['name']); // enlever le nom de la table ajoute a l'index
1855
+                $keytype = 'KEY';
1856
+                if (strpos($r['sql'], 'UNIQUE INDEX') !== false) {
1857
+                    $keytype = 'UNIQUE KEY';
1858
+                }
1859
+                $colonnes = preg_replace(',.*\((.*)\).*,', '$1', $r['sql']);
1860
+                $keys[$keytype . ' ' . $key] = $colonnes;
1861
+            }
1862
+        }
1863
+    } // c'est une vue, on liste les champs disponibles simplement
1864
+    else {
1865
+        if ($res = sql_fetsel('*', $nom_table, '', '', '', '1', '', $serveur)) { // limit 1
1866
+            $fields = [];
1867
+            foreach ($res as $c => $v) {
1868
+                $fields[$c] = '';
1869
+            }
1870
+            $keys = [];
1871
+        } else {
1872
+            return '';
1873
+        }
1874
+    }
1875
+
1876
+    return ['field' => $fields, 'key' => $keys];
1877 1877
 }
1878 1878
 
1879 1879
 
@@ -1899,22 +1899,22 @@  discard block
 block discarded – undo
1899 1899
  *     - array Tableau décrivant la requête et son temps d'exécution si var_profile est actif
1900 1900
  */
1901 1901
 function spip_sqlite_update($table, $champs, $where = '', $desc = '', $serveur = '', $requeter = true) {
1902
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1903
-	$champs = _sqlite_ajouter_champs_timestamp($table, $champs, $desc, $serveur);
1902
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1903
+    $champs = _sqlite_ajouter_champs_timestamp($table, $champs, $desc, $serveur);
1904 1904
 
1905
-	$set = [];
1906
-	foreach ($champs as $champ => $val) {
1907
-		$set[] = $champ . "=$val";
1908
-	}
1909
-	if (!empty($set)) {
1910
-		return spip_sqlite_query(
1911
-			_sqlite_calculer_expression('UPDATE', $table, ',')
1912
-			. _sqlite_calculer_expression('SET', $set, ',')
1913
-			. _sqlite_calculer_expression('WHERE', $where),
1914
-			$serveur,
1915
-			$requeter
1916
-		);
1917
-	}
1905
+    $set = [];
1906
+    foreach ($champs as $champ => $val) {
1907
+        $set[] = $champ . "=$val";
1908
+    }
1909
+    if (!empty($set)) {
1910
+        return spip_sqlite_query(
1911
+            _sqlite_calculer_expression('UPDATE', $table, ',')
1912
+            . _sqlite_calculer_expression('SET', $set, ',')
1913
+            . _sqlite_calculer_expression('WHERE', $where),
1914
+            $serveur,
1915
+            $requeter
1916
+        );
1917
+    }
1918 1918
 }
1919 1919
 
1920 1920
 
@@ -1944,38 +1944,38 @@  discard block
 block discarded – undo
1944 1944
  */
1945 1945
 function spip_sqlite_updateq($table, $champs, $where = '', $desc = [], $serveur = '', $requeter = true) {
1946 1946
 
1947
-	if (!$champs) {
1948
-		return;
1949
-	}
1950
-	if (!$desc) {
1951
-		$desc = description_table($table, $serveur);
1952
-	}
1953
-	if (!$desc) {
1954
-		die("$table insertion sans description");
1955
-	}
1956
-	$fields = $desc['field'];
1957
-
1958
-	$set = [];
1959
-	foreach ($champs as $champ => $val) {
1960
-		$set[$champ] = $champ . '=' . _sqlite_calculer_cite($val, isset($fields[$champ]) ? $fields[$champ] : '');
1961
-	}
1962
-
1963
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1964
-	// attention ils sont deja quotes
1965
-	$maj = _sqlite_ajouter_champs_timestamp($table, [], $desc, $serveur);
1966
-	foreach ($maj as $champ => $val) {
1967
-		if (!isset($set[$champ])) {
1968
-			$set[$champ] = $champ . '=' . $val;
1969
-		}
1970
-	}
1971
-
1972
-	return spip_sqlite_query(
1973
-		_sqlite_calculer_expression('UPDATE', $table, ',')
1974
-		. _sqlite_calculer_expression('SET', $set, ',')
1975
-		. _sqlite_calculer_expression('WHERE', $where),
1976
-		$serveur,
1977
-		$requeter
1978
-	);
1947
+    if (!$champs) {
1948
+        return;
1949
+    }
1950
+    if (!$desc) {
1951
+        $desc = description_table($table, $serveur);
1952
+    }
1953
+    if (!$desc) {
1954
+        die("$table insertion sans description");
1955
+    }
1956
+    $fields = $desc['field'];
1957
+
1958
+    $set = [];
1959
+    foreach ($champs as $champ => $val) {
1960
+        $set[$champ] = $champ . '=' . _sqlite_calculer_cite($val, isset($fields[$champ]) ? $fields[$champ] : '');
1961
+    }
1962
+
1963
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1964
+    // attention ils sont deja quotes
1965
+    $maj = _sqlite_ajouter_champs_timestamp($table, [], $desc, $serveur);
1966
+    foreach ($maj as $champ => $val) {
1967
+        if (!isset($set[$champ])) {
1968
+            $set[$champ] = $champ . '=' . $val;
1969
+        }
1970
+    }
1971
+
1972
+    return spip_sqlite_query(
1973
+        _sqlite_calculer_expression('UPDATE', $table, ',')
1974
+        . _sqlite_calculer_expression('SET', $set, ',')
1975
+        . _sqlite_calculer_expression('WHERE', $where),
1976
+        $serveur,
1977
+        $requeter
1978
+    );
1979 1979
 }
1980 1980
 
1981 1981
 
@@ -1993,17 +1993,17 @@  discard block
 block discarded – undo
1993 1993
  * @return void
1994 1994
  */
1995 1995
 function _sqlite_init() {
1996
-	if (!defined('_DIR_DB')) {
1997
-		define('_DIR_DB', _DIR_ETC . 'bases/');
1998
-	}
1999
-	if (!defined('_SQLITE_CHMOD')) {
2000
-		define('_SQLITE_CHMOD', _SPIP_CHMOD);
2001
-	}
1996
+    if (!defined('_DIR_DB')) {
1997
+        define('_DIR_DB', _DIR_ETC . 'bases/');
1998
+    }
1999
+    if (!defined('_SQLITE_CHMOD')) {
2000
+        define('_SQLITE_CHMOD', _SPIP_CHMOD);
2001
+    }
2002 2002
 
2003
-	if (!is_dir($d = _DIR_DB)) {
2004
-		include_spip('inc/flock');
2005
-		sous_repertoire($d);
2006
-	}
2003
+    if (!is_dir($d = _DIR_DB)) {
2004
+        include_spip('inc/flock');
2005
+        sous_repertoire($d);
2006
+    }
2007 2007
 }
2008 2008
 
2009 2009
 
@@ -2017,20 +2017,20 @@  discard block
 block discarded – undo
2017 2017
  * @return bool|int
2018 2018
  */
2019 2019
 function _sqlite_is_version($version = '', $link = '', $serveur = '', $requeter = true) {
2020
-	if ($link === '') {
2021
-		$link = _sqlite_link($serveur);
2022
-	}
2023
-	if (!$link) {
2024
-		return false;
2025
-	}
2020
+    if ($link === '') {
2021
+        $link = _sqlite_link($serveur);
2022
+    }
2023
+    if (!$link) {
2024
+        return false;
2025
+    }
2026 2026
 
2027
-	$v = 3;
2027
+    $v = 3;
2028 2028
 
2029
-	if (!$version) {
2030
-		return $v;
2031
-	}
2029
+    if (!$version) {
2030
+        return $v;
2031
+    }
2032 2032
 
2033
-	return ($version == $v);
2033
+    return ($version == $v);
2034 2034
 }
2035 2035
 
2036 2036
 
@@ -2041,9 +2041,9 @@  discard block
 block discarded – undo
2041 2041
  * @return PDO Information de connexion pour SQLite
2042 2042
  */
2043 2043
 function _sqlite_link($serveur = '') {
2044
-	$link = &$GLOBALS['connexions'][$serveur ? $serveur : 0]['link'];
2044
+    $link = &$GLOBALS['connexions'][$serveur ? $serveur : 0]['link'];
2045 2045
 
2046
-	return $link;
2046
+    return $link;
2047 2047
 }
2048 2048
 
2049 2049
 
@@ -2058,55 +2058,55 @@  discard block
 block discarded – undo
2058 2058
  * @return string|number     Texte ou nombre échappé
2059 2059
  */
2060 2060
 function _sqlite_calculer_cite($v, $type) {
2061
-	if ($type) {
2062
-		if (
2063
-			is_null($v)
2064
-			and stripos($type, 'NOT NULL') === false
2065
-		) {
2066
-			// null php se traduit en NULL SQL
2067
-			return 'NULL';
2068
-		}
2069
-
2070
-		if (sql_test_date($type) and preg_match('/^\w+\(/', $v)) {
2071
-			return $v;
2072
-		}
2073
-		if (sql_test_int($type)) {
2074
-			if (is_numeric($v)) {
2075
-				return $v;
2076
-			} elseif ($v === null) {
2077
-				return 0;
2078
-			} elseif (ctype_xdigit(substr($v, 2)) and strncmp($v, '0x', 2) === 0) {
2079
-				return hexdec(substr($v, 2));
2080
-			} else {
2081
-				return intval($v);
2082
-			}
2083
-		}
2084
-	} else {
2085
-		// si on ne connait pas le type on le deduit de $v autant que possible
2086
-		if (is_bool($v)) {
2087
-			return strval(intval($v));
2088
-		}
2089
-		elseif (is_numeric($v)) {
2090
-			return strval($v);
2091
-		}
2092
-	}
2093
-
2094
-	// trouver un link sqlite pour faire l'echappement
2095
-	foreach ($GLOBALS['connexions'] as $s) {
2096
-		if (
2097
-			$l = $s['link']
2098
-			and is_object($l)
2099
-			and $l instanceof \PDO
2100
-			and $l->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'sqlite'
2101
-		) {
2102
-			return $l->quote($v);
2103
-		}
2104
-	}
2105
-
2106
-	// echapper les ' en ''
2107
-	spip_log('Pas de methode ->quote pour echapper', 'sqlite.' . _LOG_INFO_IMPORTANTE);
2108
-
2109
-	return ("'" . str_replace("'", "''", $v) . "'");
2061
+    if ($type) {
2062
+        if (
2063
+            is_null($v)
2064
+            and stripos($type, 'NOT NULL') === false
2065
+        ) {
2066
+            // null php se traduit en NULL SQL
2067
+            return 'NULL';
2068
+        }
2069
+
2070
+        if (sql_test_date($type) and preg_match('/^\w+\(/', $v)) {
2071
+            return $v;
2072
+        }
2073
+        if (sql_test_int($type)) {
2074
+            if (is_numeric($v)) {
2075
+                return $v;
2076
+            } elseif ($v === null) {
2077
+                return 0;
2078
+            } elseif (ctype_xdigit(substr($v, 2)) and strncmp($v, '0x', 2) === 0) {
2079
+                return hexdec(substr($v, 2));
2080
+            } else {
2081
+                return intval($v);
2082
+            }
2083
+        }
2084
+    } else {
2085
+        // si on ne connait pas le type on le deduit de $v autant que possible
2086
+        if (is_bool($v)) {
2087
+            return strval(intval($v));
2088
+        }
2089
+        elseif (is_numeric($v)) {
2090
+            return strval($v);
2091
+        }
2092
+    }
2093
+
2094
+    // trouver un link sqlite pour faire l'echappement
2095
+    foreach ($GLOBALS['connexions'] as $s) {
2096
+        if (
2097
+            $l = $s['link']
2098
+            and is_object($l)
2099
+            and $l instanceof \PDO
2100
+            and $l->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'sqlite'
2101
+        ) {
2102
+            return $l->quote($v);
2103
+        }
2104
+    }
2105
+
2106
+    // echapper les ' en ''
2107
+    spip_log('Pas de methode ->quote pour echapper', 'sqlite.' . _LOG_INFO_IMPORTANTE);
2108
+
2109
+    return ("'" . str_replace("'", "''", $v) . "'");
2110 2110
 }
2111 2111
 
2112 2112
 
@@ -2122,21 +2122,21 @@  discard block
 block discarded – undo
2122 2122
  * @return string            Texte de l'expression, une partie donc, du texte la requête.
2123 2123
  */
2124 2124
 function _sqlite_calculer_expression($expression, $v, $join = 'AND') {
2125
-	if (empty($v)) {
2126
-		return '';
2127
-	}
2125
+    if (empty($v)) {
2126
+        return '';
2127
+    }
2128 2128
 
2129
-	$exp = "\n$expression ";
2129
+    $exp = "\n$expression ";
2130 2130
 
2131
-	if (!is_array($v)) {
2132
-		return $exp . $v;
2133
-	} else {
2134
-		if (strtoupper($join) === 'AND') {
2135
-			return $exp . join("\n\t$join ", array_map('_sqlite_calculer_where', $v));
2136
-		} else {
2137
-			return $exp . join($join, $v);
2138
-		}
2139
-	}
2131
+    if (!is_array($v)) {
2132
+        return $exp . $v;
2133
+    } else {
2134
+        if (strtoupper($join) === 'AND') {
2135
+            return $exp . join("\n\t$join ", array_map('_sqlite_calculer_where', $v));
2136
+        } else {
2137
+            return $exp . join($join, $v);
2138
+        }
2139
+    }
2140 2140
 }
2141 2141
 
2142 2142
 
@@ -2152,7 +2152,7 @@  discard block
 block discarded – undo
2152 2152
  * @return string Texte du orderby préparé
2153 2153
  */
2154 2154
 function _sqlite_calculer_order($orderby) {
2155
-	return (is_array($orderby)) ? join(', ', $orderby) : $orderby;
2155
+    return (is_array($orderby)) ? join(', ', $orderby) : $orderby;
2156 2156
 }
2157 2157
 
2158 2158
 
@@ -2163,26 +2163,26 @@  discard block
 block discarded – undo
2163 2163
  * @return string Sélection de colonnes pour une clause SELECT
2164 2164
  */
2165 2165
 function _sqlite_calculer_select_as($args) {
2166
-	$res = '';
2167
-	foreach ($args as $k => $v) {
2168
-		if (substr($k, -1) == '@') {
2169
-			// c'est une jointure qui se refere au from precedent
2170
-			// pas de virgule
2171
-			$res .= '  ' . $v;
2172
-		} else {
2173
-			if (!is_numeric($k)) {
2174
-				$p = strpos($v, ' ');
2175
-				if ($p) {
2176
-					$v = substr($v, 0, $p) . " AS '$k'" . substr($v, $p);
2177
-				} else {
2178
-					$v .= " AS '$k'";
2179
-				}
2180
-			}
2181
-			$res .= ', ' . $v;
2182
-		}
2183
-	}
2184
-
2185
-	return substr($res, 2);
2166
+    $res = '';
2167
+    foreach ($args as $k => $v) {
2168
+        if (substr($k, -1) == '@') {
2169
+            // c'est une jointure qui se refere au from precedent
2170
+            // pas de virgule
2171
+            $res .= '  ' . $v;
2172
+        } else {
2173
+            if (!is_numeric($k)) {
2174
+                $p = strpos($v, ' ');
2175
+                if ($p) {
2176
+                    $v = substr($v, 0, $p) . " AS '$k'" . substr($v, $p);
2177
+                } else {
2178
+                    $v .= " AS '$k'";
2179
+                }
2180
+            }
2181
+            $res .= ', ' . $v;
2182
+        }
2183
+    }
2184
+
2185
+    return substr($res, 2);
2186 2186
 }
2187 2187
 
2188 2188
 
@@ -2205,26 +2205,26 @@  discard block
 block discarded – undo
2205 2205
  *     Contrainte pour clause WHERE
2206 2206
  */
2207 2207
 function _sqlite_calculer_where($v) {
2208
-	if (!is_array($v)) {
2209
-		return $v;
2210
-	}
2211
-
2212
-	$op = array_shift($v);
2213
-	if (!($n = count($v))) {
2214
-		return $op;
2215
-	} else {
2216
-		$arg = _sqlite_calculer_where(array_shift($v));
2217
-		if ($n == 1) {
2218
-			return "$op($arg)";
2219
-		} else {
2220
-			$arg2 = _sqlite_calculer_where(array_shift($v));
2221
-			if ($n == 2) {
2222
-				return "($arg $op $arg2)";
2223
-			} else {
2224
-				return "($arg $op ($arg2) : $v[0])";
2225
-			}
2226
-		}
2227
-	}
2208
+    if (!is_array($v)) {
2209
+        return $v;
2210
+    }
2211
+
2212
+    $op = array_shift($v);
2213
+    if (!($n = count($v))) {
2214
+        return $op;
2215
+    } else {
2216
+        $arg = _sqlite_calculer_where(array_shift($v));
2217
+        if ($n == 1) {
2218
+            return "$op($arg)";
2219
+        } else {
2220
+            $arg2 = _sqlite_calculer_where(array_shift($v));
2221
+            if ($n == 2) {
2222
+                return "($arg $op $arg2)";
2223
+            } else {
2224
+                return "($arg $op ($arg2) : $v[0])";
2225
+            }
2226
+        }
2227
+    }
2228 2228
 }
2229 2229
 
2230 2230
 
@@ -2239,19 +2239,19 @@  discard block
 block discarded – undo
2239 2239
  * @return array|bool
2240 2240
  */
2241 2241
 function _sqlite_charger_version($version = '') {
2242
-	$versions = [];
2242
+    $versions = [];
2243 2243
 
2244
-	// version 3
2245
-	if (!$version || $version == 3) {
2246
-		if (extension_loaded('pdo') && extension_loaded('pdo_sqlite')) {
2247
-			$versions[] = 3;
2248
-		}
2249
-	}
2250
-	if ($version) {
2251
-		return in_array($version, $versions);
2252
-	}
2244
+    // version 3
2245
+    if (!$version || $version == 3) {
2246
+        if (extension_loaded('pdo') && extension_loaded('pdo_sqlite')) {
2247
+            $versions[] = 3;
2248
+        }
2249
+    }
2250
+    if ($version) {
2251
+        return in_array($version, $versions);
2252
+    }
2253 2253
 
2254
-	return $versions;
2254
+    return $versions;
2255 2255
 }
2256 2256
 
2257 2257
 
@@ -2289,147 +2289,147 @@  discard block
 block discarded – undo
2289 2289
  */
2290 2290
 function _sqlite_modifier_table($table, $colonne, $opt = [], $serveur = '') {
2291 2291
 
2292
-	if (is_array($table)) {
2293
-		$table_destination = reset($table);
2294
-		$table_origine = key($table);
2295
-	} else {
2296
-		$table_origine = $table_destination = $table;
2297
-	}
2298
-	// ne prend actuellement qu'un changement
2299
-	// mais pourra etre adapte pour changer plus qu'une colonne a la fois
2300
-	if (is_array($colonne)) {
2301
-		$colonne_destination = reset($colonne);
2302
-		$colonne_origine = key($colonne);
2303
-	} else {
2304
-		$colonne_origine = $colonne_destination = $colonne;
2305
-	}
2306
-	if (!isset($opt['field'])) {
2307
-		$opt['field'] = [];
2308
-	}
2309
-	if (!isset($opt['key'])) {
2310
-		$opt['key'] = [];
2311
-	}
2312
-
2313
-	// si les noms de tables sont differents, pas besoin de table temporaire
2314
-	// on prendra directement le nom de la future table
2315
-	$meme_table = ($table_origine == $table_destination);
2316
-
2317
-	$def_origine = sql_showtable($table_origine, false, $serveur);
2318
-	if (!$def_origine or !isset($def_origine['field'])) {
2319
-		spip_log("Alter table impossible sur $table_origine : table non trouvee", 'sqlite' . _LOG_ERREUR);
2320
-
2321
-		return false;
2322
-	}
2323
-
2324
-
2325
-	$table_tmp = $table_origine . '_tmp';
2326
-
2327
-	// 1) creer une table temporaire avec les modifications
2328
-	// - DROP : suppression de la colonne
2329
-	// - CHANGE : modification de la colonne
2330
-	// (foreach pour conserver l'ordre des champs)
2331
-
2332
-	// field
2333
-	$fields = [];
2334
-	// pour le INSERT INTO plus loin
2335
-	// stocker la correspondance nouvelles->anciennes colonnes
2336
-	$fields_correspondances = [];
2337
-	foreach ($def_origine['field'] as $c => $d) {
2338
-		if ($colonne_origine && ($c == $colonne_origine)) {
2339
-			// si pas DROP
2340
-			if ($colonne_destination) {
2341
-				$fields[$colonne_destination] = $opt['field'][$colonne_destination];
2342
-				$fields_correspondances[$colonne_destination] = $c;
2343
-			}
2344
-		} else {
2345
-			$fields[$c] = $d;
2346
-			$fields_correspondances[$c] = $c;
2347
-		}
2348
-	}
2349
-	// cas de ADD sqlite2 (ajout du champ en fin de table):
2350
-	if (!$colonne_origine && $colonne_destination) {
2351
-		$fields[$colonne_destination] = $opt['field'][$colonne_destination];
2352
-	}
2353
-
2354
-	// key...
2355
-	$keys = [];
2356
-	foreach ($def_origine['key'] as $c => $d) {
2357
-		$c = str_replace($colonne_origine, $colonne_destination, $c);
2358
-		$d = str_replace($colonne_origine, $colonne_destination, $d);
2359
-		// seulement si on ne supprime pas la colonne !
2360
-		if ($d) {
2361
-			$keys[$c] = $d;
2362
-		}
2363
-	}
2364
-
2365
-	// autres keys, on merge
2366
-	$keys = array_merge($keys, $opt['key']);
2367
-	$queries = [];
2368
-
2369
-	// copier dans destination (si differente de origine), sinon tmp
2370
-	$table_copie = ($meme_table) ? $table_tmp : $table_destination;
2371
-	$autoinc = (isset($keys['PRIMARY KEY'])
2372
-		and $keys['PRIMARY KEY']
2373
-		and stripos($keys['PRIMARY KEY'], ',') === false
2374
-		and stripos($fields[$keys['PRIMARY KEY']], 'default') === false);
2375
-
2376
-	if (
2377
-		$q = _sqlite_requete_create(
2378
-			$table_copie,
2379
-			$fields,
2380
-			$keys,
2381
-			$autoinc,
2382
-			$temporary = false,
2383
-			$ifnotexists = true,
2384
-			$serveur
2385
-		)
2386
-	) {
2387
-		$queries[] = $q;
2388
-	}
2389
-
2390
-
2391
-	// 2) y copier les champs qui vont bien
2392
-	$champs_dest = join(', ', array_keys($fields_correspondances));
2393
-	$champs_ori = join(', ', $fields_correspondances);
2394
-	$queries[] = "INSERT INTO $table_copie ($champs_dest) SELECT $champs_ori FROM $table_origine";
2395
-
2396
-	// 3) supprimer la table d'origine
2397
-	$queries[] = "DROP TABLE $table_origine";
2398
-
2399
-	// 4) renommer la table temporaire
2400
-	// avec le nom de la table destination
2401
-	// si necessaire
2402
-	if ($meme_table) {
2403
-		$queries[] = "ALTER TABLE $table_copie RENAME TO $table_destination";
2404
-	}
2405
-
2406
-	// 5) remettre les index !
2407
-	foreach ($keys as $k => $v) {
2408
-		if ($k == 'PRIMARY KEY') {
2409
-		} else {
2410
-			// enlever KEY
2411
-			$k = substr($k, 4);
2412
-			$queries[] = "CREATE INDEX $table_destination" . "_$k ON $table_destination ($v)";
2413
-		}
2414
-	}
2415
-
2416
-
2417
-	if (count($queries)) {
2418
-		spip_sqlite::demarrer_transaction($serveur);
2419
-		// il faut les faire une par une car $query = join('; ', $queries).";"; ne fonctionne pas
2420
-		foreach ($queries as $q) {
2421
-			if (!spip_sqlite::executer_requete($q, $serveur)) {
2422
-				spip_log('SQLite : ALTER TABLE table :'
2423
-					. " Erreur a l'execution de la requete : $q", 'sqlite.' . _LOG_ERREUR);
2424
-				spip_sqlite::annuler_transaction($serveur);
2425
-
2426
-				return false;
2427
-			}
2428
-		}
2429
-		spip_sqlite::finir_transaction($serveur);
2430
-	}
2431
-
2432
-	return true;
2292
+    if (is_array($table)) {
2293
+        $table_destination = reset($table);
2294
+        $table_origine = key($table);
2295
+    } else {
2296
+        $table_origine = $table_destination = $table;
2297
+    }
2298
+    // ne prend actuellement qu'un changement
2299
+    // mais pourra etre adapte pour changer plus qu'une colonne a la fois
2300
+    if (is_array($colonne)) {
2301
+        $colonne_destination = reset($colonne);
2302
+        $colonne_origine = key($colonne);
2303
+    } else {
2304
+        $colonne_origine = $colonne_destination = $colonne;
2305
+    }
2306
+    if (!isset($opt['field'])) {
2307
+        $opt['field'] = [];
2308
+    }
2309
+    if (!isset($opt['key'])) {
2310
+        $opt['key'] = [];
2311
+    }
2312
+
2313
+    // si les noms de tables sont differents, pas besoin de table temporaire
2314
+    // on prendra directement le nom de la future table
2315
+    $meme_table = ($table_origine == $table_destination);
2316
+
2317
+    $def_origine = sql_showtable($table_origine, false, $serveur);
2318
+    if (!$def_origine or !isset($def_origine['field'])) {
2319
+        spip_log("Alter table impossible sur $table_origine : table non trouvee", 'sqlite' . _LOG_ERREUR);
2320
+
2321
+        return false;
2322
+    }
2323
+
2324
+
2325
+    $table_tmp = $table_origine . '_tmp';
2326
+
2327
+    // 1) creer une table temporaire avec les modifications
2328
+    // - DROP : suppression de la colonne
2329
+    // - CHANGE : modification de la colonne
2330
+    // (foreach pour conserver l'ordre des champs)
2331
+
2332
+    // field
2333
+    $fields = [];
2334
+    // pour le INSERT INTO plus loin
2335
+    // stocker la correspondance nouvelles->anciennes colonnes
2336
+    $fields_correspondances = [];
2337
+    foreach ($def_origine['field'] as $c => $d) {
2338
+        if ($colonne_origine && ($c == $colonne_origine)) {
2339
+            // si pas DROP
2340
+            if ($colonne_destination) {
2341
+                $fields[$colonne_destination] = $opt['field'][$colonne_destination];
2342
+                $fields_correspondances[$colonne_destination] = $c;
2343
+            }
2344
+        } else {
2345
+            $fields[$c] = $d;
2346
+            $fields_correspondances[$c] = $c;
2347
+        }
2348
+    }
2349
+    // cas de ADD sqlite2 (ajout du champ en fin de table):
2350
+    if (!$colonne_origine && $colonne_destination) {
2351
+        $fields[$colonne_destination] = $opt['field'][$colonne_destination];
2352
+    }
2353
+
2354
+    // key...
2355
+    $keys = [];
2356
+    foreach ($def_origine['key'] as $c => $d) {
2357
+        $c = str_replace($colonne_origine, $colonne_destination, $c);
2358
+        $d = str_replace($colonne_origine, $colonne_destination, $d);
2359
+        // seulement si on ne supprime pas la colonne !
2360
+        if ($d) {
2361
+            $keys[$c] = $d;
2362
+        }
2363
+    }
2364
+
2365
+    // autres keys, on merge
2366
+    $keys = array_merge($keys, $opt['key']);
2367
+    $queries = [];
2368
+
2369
+    // copier dans destination (si differente de origine), sinon tmp
2370
+    $table_copie = ($meme_table) ? $table_tmp : $table_destination;
2371
+    $autoinc = (isset($keys['PRIMARY KEY'])
2372
+        and $keys['PRIMARY KEY']
2373
+        and stripos($keys['PRIMARY KEY'], ',') === false
2374
+        and stripos($fields[$keys['PRIMARY KEY']], 'default') === false);
2375
+
2376
+    if (
2377
+        $q = _sqlite_requete_create(
2378
+            $table_copie,
2379
+            $fields,
2380
+            $keys,
2381
+            $autoinc,
2382
+            $temporary = false,
2383
+            $ifnotexists = true,
2384
+            $serveur
2385
+        )
2386
+    ) {
2387
+        $queries[] = $q;
2388
+    }
2389
+
2390
+
2391
+    // 2) y copier les champs qui vont bien
2392
+    $champs_dest = join(', ', array_keys($fields_correspondances));
2393
+    $champs_ori = join(', ', $fields_correspondances);
2394
+    $queries[] = "INSERT INTO $table_copie ($champs_dest) SELECT $champs_ori FROM $table_origine";
2395
+
2396
+    // 3) supprimer la table d'origine
2397
+    $queries[] = "DROP TABLE $table_origine";
2398
+
2399
+    // 4) renommer la table temporaire
2400
+    // avec le nom de la table destination
2401
+    // si necessaire
2402
+    if ($meme_table) {
2403
+        $queries[] = "ALTER TABLE $table_copie RENAME TO $table_destination";
2404
+    }
2405
+
2406
+    // 5) remettre les index !
2407
+    foreach ($keys as $k => $v) {
2408
+        if ($k == 'PRIMARY KEY') {
2409
+        } else {
2410
+            // enlever KEY
2411
+            $k = substr($k, 4);
2412
+            $queries[] = "CREATE INDEX $table_destination" . "_$k ON $table_destination ($v)";
2413
+        }
2414
+    }
2415
+
2416
+
2417
+    if (count($queries)) {
2418
+        spip_sqlite::demarrer_transaction($serveur);
2419
+        // il faut les faire une par une car $query = join('; ', $queries).";"; ne fonctionne pas
2420
+        foreach ($queries as $q) {
2421
+            if (!spip_sqlite::executer_requete($q, $serveur)) {
2422
+                spip_log('SQLite : ALTER TABLE table :'
2423
+                    . " Erreur a l'execution de la requete : $q", 'sqlite.' . _LOG_ERREUR);
2424
+                spip_sqlite::annuler_transaction($serveur);
2425
+
2426
+                return false;
2427
+            }
2428
+        }
2429
+        spip_sqlite::finir_transaction($serveur);
2430
+    }
2431
+
2432
+    return true;
2433 2433
 }
2434 2434
 
2435 2435
 
@@ -2439,61 +2439,61 @@  discard block
 block discarded – undo
2439 2439
  * @return array
2440 2440
  */
2441 2441
 function _sqlite_ref_fonctions() {
2442
-	$fonctions = [
2443
-		'alter' => 'spip_sqlite_alter',
2444
-		'count' => 'spip_sqlite_count',
2445
-		'countsel' => 'spip_sqlite_countsel',
2446
-		'create' => 'spip_sqlite_create',
2447
-		'create_base' => 'spip_sqlite_create_base',
2448
-		'create_view' => 'spip_sqlite_create_view',
2449
-		'date_proche' => 'spip_sqlite_date_proche',
2450
-		'delete' => 'spip_sqlite_delete',
2451
-		'drop_table' => 'spip_sqlite_drop_table',
2452
-		'drop_view' => 'spip_sqlite_drop_view',
2453
-		'errno' => 'spip_sqlite_errno',
2454
-		'error' => 'spip_sqlite_error',
2455
-		'explain' => 'spip_sqlite_explain',
2456
-		'fetch' => 'spip_sqlite_fetch',
2457
-		'seek' => 'spip_sqlite_seek',
2458
-		'free' => 'spip_sqlite_free',
2459
-		'hex' => 'spip_sqlite_hex',
2460
-		'in' => 'spip_sqlite_in',
2461
-		'insert' => 'spip_sqlite_insert',
2462
-		'insertq' => 'spip_sqlite_insertq',
2463
-		'insertq_multi' => 'spip_sqlite_insertq_multi',
2464
-		'listdbs' => 'spip_sqlite_listdbs',
2465
-		'multi' => 'spip_sqlite_multi',
2466
-		'optimize' => 'spip_sqlite_optimize',
2467
-		'query' => 'spip_sqlite_query',
2468
-		'quote' => 'spip_sqlite_quote',
2469
-		'repair' => 'spip_sqlite_repair',
2470
-		'replace' => 'spip_sqlite_replace',
2471
-		'replace_multi' => 'spip_sqlite_replace_multi',
2472
-		'select' => 'spip_sqlite_select',
2473
-		'selectdb' => 'spip_sqlite_selectdb',
2474
-		'set_charset' => 'spip_sqlite_set_charset',
2475
-		'get_charset' => 'spip_sqlite_get_charset',
2476
-		'showbase' => 'spip_sqlite_showbase',
2477
-		'showtable' => 'spip_sqlite_showtable',
2478
-		'table_exists' => 'spip_sqlite_table_exists',
2479
-		'update' => 'spip_sqlite_update',
2480
-		'updateq' => 'spip_sqlite_updateq',
2481
-		'preferer_transaction' => 'spip_sqlite_preferer_transaction',
2482
-		'demarrer_transaction' => 'spip_sqlite_demarrer_transaction',
2483
-		'terminer_transaction' => 'spip_sqlite_terminer_transaction',
2484
-	];
2485
-
2486
-	// association de chaque nom http d'un charset aux couples sqlite
2487
-	// SQLite supporte utf-8 et utf-16 uniquement.
2488
-	$charsets = [
2489
-		'utf-8' => ['charset' => 'utf8', 'collation' => 'utf8_general_ci'],
2490
-		//'utf-16be'=>array('charset'=>'utf16be','collation'=>'UTF-16BE'),// aucune idee de quoi il faut remplir dans es champs la
2491
-		//'utf-16le'=>array('charset'=>'utf16le','collation'=>'UTF-16LE')
2492
-	];
2493
-
2494
-	$fonctions['charsets'] = $charsets;
2495
-
2496
-	return $fonctions;
2442
+    $fonctions = [
2443
+        'alter' => 'spip_sqlite_alter',
2444
+        'count' => 'spip_sqlite_count',
2445
+        'countsel' => 'spip_sqlite_countsel',
2446
+        'create' => 'spip_sqlite_create',
2447
+        'create_base' => 'spip_sqlite_create_base',
2448
+        'create_view' => 'spip_sqlite_create_view',
2449
+        'date_proche' => 'spip_sqlite_date_proche',
2450
+        'delete' => 'spip_sqlite_delete',
2451
+        'drop_table' => 'spip_sqlite_drop_table',
2452
+        'drop_view' => 'spip_sqlite_drop_view',
2453
+        'errno' => 'spip_sqlite_errno',
2454
+        'error' => 'spip_sqlite_error',
2455
+        'explain' => 'spip_sqlite_explain',
2456
+        'fetch' => 'spip_sqlite_fetch',
2457
+        'seek' => 'spip_sqlite_seek',
2458
+        'free' => 'spip_sqlite_free',
2459
+        'hex' => 'spip_sqlite_hex',
2460
+        'in' => 'spip_sqlite_in',
2461
+        'insert' => 'spip_sqlite_insert',
2462
+        'insertq' => 'spip_sqlite_insertq',
2463
+        'insertq_multi' => 'spip_sqlite_insertq_multi',
2464
+        'listdbs' => 'spip_sqlite_listdbs',
2465
+        'multi' => 'spip_sqlite_multi',
2466
+        'optimize' => 'spip_sqlite_optimize',
2467
+        'query' => 'spip_sqlite_query',
2468
+        'quote' => 'spip_sqlite_quote',
2469
+        'repair' => 'spip_sqlite_repair',
2470
+        'replace' => 'spip_sqlite_replace',
2471
+        'replace_multi' => 'spip_sqlite_replace_multi',
2472
+        'select' => 'spip_sqlite_select',
2473
+        'selectdb' => 'spip_sqlite_selectdb',
2474
+        'set_charset' => 'spip_sqlite_set_charset',
2475
+        'get_charset' => 'spip_sqlite_get_charset',
2476
+        'showbase' => 'spip_sqlite_showbase',
2477
+        'showtable' => 'spip_sqlite_showtable',
2478
+        'table_exists' => 'spip_sqlite_table_exists',
2479
+        'update' => 'spip_sqlite_update',
2480
+        'updateq' => 'spip_sqlite_updateq',
2481
+        'preferer_transaction' => 'spip_sqlite_preferer_transaction',
2482
+        'demarrer_transaction' => 'spip_sqlite_demarrer_transaction',
2483
+        'terminer_transaction' => 'spip_sqlite_terminer_transaction',
2484
+    ];
2485
+
2486
+    // association de chaque nom http d'un charset aux couples sqlite
2487
+    // SQLite supporte utf-8 et utf-16 uniquement.
2488
+    $charsets = [
2489
+        'utf-8' => ['charset' => 'utf8', 'collation' => 'utf8_general_ci'],
2490
+        //'utf-16be'=>array('charset'=>'utf16be','collation'=>'UTF-16BE'),// aucune idee de quoi il faut remplir dans es champs la
2491
+        //'utf-16le'=>array('charset'=>'utf16le','collation'=>'UTF-16LE')
2492
+    ];
2493
+
2494
+    $fonctions['charsets'] = $charsets;
2495
+
2496
+    return $fonctions;
2497 2497
 }
2498 2498
 
2499 2499
 
@@ -2505,56 +2505,56 @@  discard block
 block discarded – undo
2505 2505
  * @return mixed
2506 2506
  */
2507 2507
 function _sqlite_remplacements_definitions_table($query, $autoinc = false) {
2508
-	// quelques remplacements
2509
-	$num = '(\s*\([0-9]*\))?';
2510
-	$enum = '(\s*\([^\)]*\))?';
2511
-
2512
-	$remplace = [
2513
-		'/enum' . $enum . '/is' => 'VARCHAR(255)',
2514
-		'/COLLATE \w+_bin/is' => 'COLLATE BINARY',
2515
-		'/COLLATE \w+_ci/is' => 'COLLATE NOCASE',
2516
-		'/auto_increment/is' => '',
2517
-		'/current_timestamp\(\)/is' => 'CURRENT_TIMESTAMP', // Fix export depuis mariaDB #4374
2518
-		'/(timestamp .* )ON .*$/is' => '\\1',
2519
-		'/character set \w+/is' => '',
2520
-		'/((big|small|medium|tiny)?int(eger)?)' . $num . '\s*unsigned/is' => '\\1 UNSIGNED',
2521
-		'/(text\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2522
-		'/((char|varchar)' . $num . '\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2523
-		'/(datetime\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00 00:00:00'",
2524
-		'/(date\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00'",
2525
-	];
2526
-
2527
-	// pour l'autoincrement, il faut des INTEGER NOT NULL PRIMARY KEY
2528
-	$remplace_autocinc = [
2529
-		'/(big|small|medium|tiny)?int(eger)?' . $num . '/is' => 'INTEGER'
2530
-	];
2531
-	// pour les int non autoincrement, il faut un DEFAULT
2532
-	$remplace_nonautocinc = [
2533
-		'/((big|small|medium|tiny)?int(eger)?' . $num . '\s+not\s+null)\s*$/is' => "\\1 DEFAULT 0",
2534
-	];
2535
-
2536
-	if (is_string($query)) {
2537
-		$query = preg_replace(array_keys($remplace), $remplace, $query);
2538
-		if ($autoinc or preg_match(',AUTO_INCREMENT,is', $query)) {
2539
-			$query = preg_replace(array_keys($remplace_autocinc), $remplace_autocinc, $query);
2540
-		} else {
2541
-			$query = preg_replace(array_keys($remplace_nonautocinc), $remplace_nonautocinc, $query);
2542
-			$query = _sqlite_collate_ci($query);
2543
-		}
2544
-	} elseif (is_array($query)) {
2545
-		foreach ($query as $k => $q) {
2546
-			$ai = ($autoinc ? $k == $autoinc : preg_match(',AUTO_INCREMENT,is', $q));
2547
-			$query[$k] = preg_replace(array_keys($remplace), $remplace, $query[$k]);
2548
-			if ($ai) {
2549
-				$query[$k] = preg_replace(array_keys($remplace_autocinc), $remplace_autocinc, $query[$k]);
2550
-			} else {
2551
-				$query[$k] = preg_replace(array_keys($remplace_nonautocinc), $remplace_nonautocinc, $query[$k]);
2552
-				$query[$k] = _sqlite_collate_ci($query[$k]);
2553
-			}
2554
-		}
2555
-	}
2556
-
2557
-	return $query;
2508
+    // quelques remplacements
2509
+    $num = '(\s*\([0-9]*\))?';
2510
+    $enum = '(\s*\([^\)]*\))?';
2511
+
2512
+    $remplace = [
2513
+        '/enum' . $enum . '/is' => 'VARCHAR(255)',
2514
+        '/COLLATE \w+_bin/is' => 'COLLATE BINARY',
2515
+        '/COLLATE \w+_ci/is' => 'COLLATE NOCASE',
2516
+        '/auto_increment/is' => '',
2517
+        '/current_timestamp\(\)/is' => 'CURRENT_TIMESTAMP', // Fix export depuis mariaDB #4374
2518
+        '/(timestamp .* )ON .*$/is' => '\\1',
2519
+        '/character set \w+/is' => '',
2520
+        '/((big|small|medium|tiny)?int(eger)?)' . $num . '\s*unsigned/is' => '\\1 UNSIGNED',
2521
+        '/(text\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2522
+        '/((char|varchar)' . $num . '\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2523
+        '/(datetime\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00 00:00:00'",
2524
+        '/(date\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00'",
2525
+    ];
2526
+
2527
+    // pour l'autoincrement, il faut des INTEGER NOT NULL PRIMARY KEY
2528
+    $remplace_autocinc = [
2529
+        '/(big|small|medium|tiny)?int(eger)?' . $num . '/is' => 'INTEGER'
2530
+    ];
2531
+    // pour les int non autoincrement, il faut un DEFAULT
2532
+    $remplace_nonautocinc = [
2533
+        '/((big|small|medium|tiny)?int(eger)?' . $num . '\s+not\s+null)\s*$/is' => "\\1 DEFAULT 0",
2534
+    ];
2535
+
2536
+    if (is_string($query)) {
2537
+        $query = preg_replace(array_keys($remplace), $remplace, $query);
2538
+        if ($autoinc or preg_match(',AUTO_INCREMENT,is', $query)) {
2539
+            $query = preg_replace(array_keys($remplace_autocinc), $remplace_autocinc, $query);
2540
+        } else {
2541
+            $query = preg_replace(array_keys($remplace_nonautocinc), $remplace_nonautocinc, $query);
2542
+            $query = _sqlite_collate_ci($query);
2543
+        }
2544
+    } elseif (is_array($query)) {
2545
+        foreach ($query as $k => $q) {
2546
+            $ai = ($autoinc ? $k == $autoinc : preg_match(',AUTO_INCREMENT,is', $q));
2547
+            $query[$k] = preg_replace(array_keys($remplace), $remplace, $query[$k]);
2548
+            if ($ai) {
2549
+                $query[$k] = preg_replace(array_keys($remplace_autocinc), $remplace_autocinc, $query[$k]);
2550
+            } else {
2551
+                $query[$k] = preg_replace(array_keys($remplace_nonautocinc), $remplace_nonautocinc, $query[$k]);
2552
+                $query[$k] = _sqlite_collate_ci($query[$k]);
2553
+            }
2554
+        }
2555
+    }
2556
+
2557
+    return $query;
2558 2558
 }
2559 2559
 
2560 2560
 /**
@@ -2565,17 +2565,17 @@  discard block
 block discarded – undo
2565 2565
  * @return string
2566 2566
  */
2567 2567
 function _sqlite_collate_ci($champ) {
2568
-	if (stripos($champ, 'COLLATE') !== false) {
2569
-		return $champ;
2570
-	}
2571
-	if (stripos($champ, 'BINARY') !== false) {
2572
-		return str_ireplace('BINARY', 'COLLATE BINARY', $champ);
2573
-	}
2574
-	if (preg_match(',^(char|varchar|(long|small|medium|tiny)?text),i', $champ)) {
2575
-		return $champ . ' COLLATE NOCASE';
2576
-	}
2568
+    if (stripos($champ, 'COLLATE') !== false) {
2569
+        return $champ;
2570
+    }
2571
+    if (stripos($champ, 'BINARY') !== false) {
2572
+        return str_ireplace('BINARY', 'COLLATE BINARY', $champ);
2573
+    }
2574
+    if (preg_match(',^(char|varchar|(long|small|medium|tiny)?text),i', $champ)) {
2575
+        return $champ . ' COLLATE NOCASE';
2576
+    }
2577 2577
 
2578
-	return $champ;
2578
+    return $champ;
2579 2579
 }
2580 2580
 
2581 2581
 
@@ -2594,84 +2594,84 @@  discard block
 block discarded – undo
2594 2594
  * @return bool|string
2595 2595
  */
2596 2596
 function _sqlite_requete_create(
2597
-	$nom,
2598
-	$champs,
2599
-	$cles,
2600
-	$autoinc = false,
2601
-	$temporary = false,
2602
-	$_ifnotexists = true,
2603
-	$serveur = '',
2604
-	$requeter = true
2597
+    $nom,
2598
+    $champs,
2599
+    $cles,
2600
+    $autoinc = false,
2601
+    $temporary = false,
2602
+    $_ifnotexists = true,
2603
+    $serveur = '',
2604
+    $requeter = true
2605 2605
 ) {
2606
-	$query = $keys = $s = $p = '';
2607
-
2608
-	// certains plugins declarent les tables  (permet leur inclusion dans le dump)
2609
-	// sans les renseigner (laisse le compilo recuperer la description)
2610
-	if (!is_array($champs) || !is_array($cles)) {
2611
-		return;
2612
-	}
2613
-
2614
-	// sqlite ne gere pas KEY tout court dans une requete CREATE TABLE
2615
-	// il faut passer par des create index
2616
-	// Il gere par contre primary key !
2617
-	// Soit la PK est definie dans les cles, soit dans un champs
2618
-	// soit faussement dans les 2 (et dans ce cas, il faut l’enlever à un des 2 endroits !)
2619
-	$pk = 'PRIMARY KEY';
2620
-	// le champ de cle primaire
2621
-	$champ_pk = !empty($cles[$pk]) ? $cles[$pk] : '';
2622
-
2623
-	foreach ($champs as $k => $v) {
2624
-		if (false !== stripos($v, $pk)) {
2625
-			$champ_pk = $k;
2626
-			// on n'en a plus besoin dans field, vu que defini dans key
2627
-			$champs[$k] = preg_replace("/$pk/is", '', $champs[$k]);
2628
-			break;
2629
-		}
2630
-	}
2631
-
2632
-	if ($champ_pk) {
2633
-		$keys = "\n\t\t$pk ($champ_pk)";
2634
-	}
2635
-	// Pas de DEFAULT 0 sur les cles primaires en auto-increment
2636
-	if (
2637
-		isset($champs[$champ_pk])
2638
-		and stripos($champs[$champ_pk], 'default 0') !== false
2639
-	) {
2640
-		$champs[$champ_pk] = trim(str_ireplace('default 0', '', $champs[$champ_pk]));
2641
-	}
2642
-
2643
-	$champs = _sqlite_remplacements_definitions_table($champs, $autoinc ? $champ_pk : false);
2644
-	foreach ($champs as $k => $v) {
2645
-		$query .= "$s\n\t\t$k $v";
2646
-		$s = ',';
2647
-	}
2648
-
2649
-	$ifnotexists = '';
2650
-	if ($_ifnotexists) {
2651
-		$version = spip_sqlite_fetch(
2652
-			spip_sqlite_query('select sqlite_version() AS sqlite_version', $serveur),
2653
-			'',
2654
-			$serveur
2655
-		);
2656
-		if (!function_exists('spip_version_compare')) {
2657
-			include_spip('plugins/installer');
2658
-		}
2659
-
2660
-		if ($version and spip_version_compare($version['sqlite_version'], '3.3.0', '>=')) {
2661
-			$ifnotexists = ' IF NOT EXISTS';
2662
-		} else {
2663
-			/* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
2664
-			$a = spip_sqlite_showtable($nom, $serveur);
2665
-			if (isset($a['key']['KEY ' . $nom])) {
2666
-				return true;
2667
-			}
2668
-		}
2669
-	}
2670
-
2671
-	$temporary = $temporary ? ' TEMPORARY' : '';
2672
-	$q = "CREATE$temporary TABLE$ifnotexists $nom ($query" . ($keys ? ",$keys" : '') . ")\n";
2673
-
2674
-	return $q;
2606
+    $query = $keys = $s = $p = '';
2607
+
2608
+    // certains plugins declarent les tables  (permet leur inclusion dans le dump)
2609
+    // sans les renseigner (laisse le compilo recuperer la description)
2610
+    if (!is_array($champs) || !is_array($cles)) {
2611
+        return;
2612
+    }
2613
+
2614
+    // sqlite ne gere pas KEY tout court dans une requete CREATE TABLE
2615
+    // il faut passer par des create index
2616
+    // Il gere par contre primary key !
2617
+    // Soit la PK est definie dans les cles, soit dans un champs
2618
+    // soit faussement dans les 2 (et dans ce cas, il faut l’enlever à un des 2 endroits !)
2619
+    $pk = 'PRIMARY KEY';
2620
+    // le champ de cle primaire
2621
+    $champ_pk = !empty($cles[$pk]) ? $cles[$pk] : '';
2622
+
2623
+    foreach ($champs as $k => $v) {
2624
+        if (false !== stripos($v, $pk)) {
2625
+            $champ_pk = $k;
2626
+            // on n'en a plus besoin dans field, vu que defini dans key
2627
+            $champs[$k] = preg_replace("/$pk/is", '', $champs[$k]);
2628
+            break;
2629
+        }
2630
+    }
2631
+
2632
+    if ($champ_pk) {
2633
+        $keys = "\n\t\t$pk ($champ_pk)";
2634
+    }
2635
+    // Pas de DEFAULT 0 sur les cles primaires en auto-increment
2636
+    if (
2637
+        isset($champs[$champ_pk])
2638
+        and stripos($champs[$champ_pk], 'default 0') !== false
2639
+    ) {
2640
+        $champs[$champ_pk] = trim(str_ireplace('default 0', '', $champs[$champ_pk]));
2641
+    }
2642
+
2643
+    $champs = _sqlite_remplacements_definitions_table($champs, $autoinc ? $champ_pk : false);
2644
+    foreach ($champs as $k => $v) {
2645
+        $query .= "$s\n\t\t$k $v";
2646
+        $s = ',';
2647
+    }
2648
+
2649
+    $ifnotexists = '';
2650
+    if ($_ifnotexists) {
2651
+        $version = spip_sqlite_fetch(
2652
+            spip_sqlite_query('select sqlite_version() AS sqlite_version', $serveur),
2653
+            '',
2654
+            $serveur
2655
+        );
2656
+        if (!function_exists('spip_version_compare')) {
2657
+            include_spip('plugins/installer');
2658
+        }
2659
+
2660
+        if ($version and spip_version_compare($version['sqlite_version'], '3.3.0', '>=')) {
2661
+            $ifnotexists = ' IF NOT EXISTS';
2662
+        } else {
2663
+            /* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
2664
+            $a = spip_sqlite_showtable($nom, $serveur);
2665
+            if (isset($a['key']['KEY ' . $nom])) {
2666
+                return true;
2667
+            }
2668
+        }
2669
+    }
2670
+
2671
+    $temporary = $temporary ? ' TEMPORARY' : '';
2672
+    $q = "CREATE$temporary TABLE$ifnotexists $nom ($query" . ($keys ? ",$keys" : '') . ")\n";
2673
+
2674
+    return $q;
2675 2675
 }
2676 2676
 
2677 2677
 
@@ -2690,41 +2690,41 @@  discard block
 block discarded – undo
2690 2690
  * @return
2691 2691
  */
2692 2692
 function _sqlite_ajouter_champs_timestamp($table, $couples, $desc = '', $serveur = '') {
2693
-	static $tables = [];
2694
-
2695
-	if (!isset($tables[$table])) {
2696
-		if (!$desc) {
2697
-			$trouver_table = charger_fonction('trouver_table', 'base');
2698
-			$desc = $trouver_table($table, $serveur);
2699
-			// si pas de description, on ne fait rien, ou on die() ?
2700
-			if (!$desc) {
2701
-				return $couples;
2702
-			}
2703
-		}
2704
-
2705
-		// recherche des champs avec simplement 'TIMESTAMP'
2706
-		// cependant, il faudra peut etre etendre
2707
-		// avec la gestion de DEFAULT et ON UPDATE
2708
-		// mais ceux-ci ne sont pas utilises dans le core
2709
-		$tables[$table] = ['valeur' => [], 'cite' => [], 'desc' => []];
2710
-
2711
-		$now = _sqlite_func_now(true);
2712
-		foreach ($desc['field'] as $k => $v) {
2713
-			if (strpos(strtolower(ltrim($v)), 'timestamp') === 0) {
2714
-				$tables[$table]['desc'][$k] = $v;
2715
-				$tables[$table]['valeur'][$k] = _sqlite_calculer_cite($now, $tables[$table]['desc'][$k]);
2716
-			}
2717
-		}
2718
-	}
2719
-	else {
2720
-		$now = _sqlite_func_now(true);
2721
-		foreach (array_keys($tables[$table]['desc']) as $k) {
2722
-			$tables[$table]['valeur'][$k] = _sqlite_calculer_cite($now, $tables[$table]['desc'][$k]);
2723
-		}
2724
-	}
2725
-
2726
-	// ajout des champs type 'timestamp' absents
2727
-	return array_merge($tables[$table]['valeur'], $couples);
2693
+    static $tables = [];
2694
+
2695
+    if (!isset($tables[$table])) {
2696
+        if (!$desc) {
2697
+            $trouver_table = charger_fonction('trouver_table', 'base');
2698
+            $desc = $trouver_table($table, $serveur);
2699
+            // si pas de description, on ne fait rien, ou on die() ?
2700
+            if (!$desc) {
2701
+                return $couples;
2702
+            }
2703
+        }
2704
+
2705
+        // recherche des champs avec simplement 'TIMESTAMP'
2706
+        // cependant, il faudra peut etre etendre
2707
+        // avec la gestion de DEFAULT et ON UPDATE
2708
+        // mais ceux-ci ne sont pas utilises dans le core
2709
+        $tables[$table] = ['valeur' => [], 'cite' => [], 'desc' => []];
2710
+
2711
+        $now = _sqlite_func_now(true);
2712
+        foreach ($desc['field'] as $k => $v) {
2713
+            if (strpos(strtolower(ltrim($v)), 'timestamp') === 0) {
2714
+                $tables[$table]['desc'][$k] = $v;
2715
+                $tables[$table]['valeur'][$k] = _sqlite_calculer_cite($now, $tables[$table]['desc'][$k]);
2716
+            }
2717
+        }
2718
+    }
2719
+    else {
2720
+        $now = _sqlite_func_now(true);
2721
+        foreach (array_keys($tables[$table]['desc']) as $k) {
2722
+            $tables[$table]['valeur'][$k] = _sqlite_calculer_cite($now, $tables[$table]['desc'][$k]);
2723
+        }
2724
+    }
2725
+
2726
+    // ajout des champs type 'timestamp' absents
2727
+    return array_merge($tables[$table]['valeur'], $couples);
2728 2728
 }
2729 2729
 
2730 2730
 
@@ -2735,7 +2735,7 @@  discard block
 block discarded – undo
2735 2735
  * @return array|bool
2736 2736
  */
2737 2737
 function spip_versions_sqlite() {
2738
-	return _sqlite_charger_version();
2738
+    return _sqlite_charger_version();
2739 2739
 }
2740 2740
 
2741 2741
 /**
@@ -2743,114 +2743,114 @@  discard block
 block discarded – undo
2743 2743
  * encadrées de transactions.
2744 2744
  **/
2745 2745
 class spip_sqlite {
2746
-	/** @var sqlite_requeteur[] Liste des instances de requêteurs créés */
2747
-	public static $requeteurs = [];
2748
-	/** @var bool[] Pour chaque connexion, flag pour savoir si une transaction est en cours */
2749
-	public static $transaction_en_cours = [];
2750
-
2751
-
2752
-	/**
2753
-	 * Retourne une unique instance du requêteur
2754
-	 *
2755
-	 * Retourne une instance unique du requêteur pour une connexion SQLite
2756
-	 * donnée
2757
-	 *
2758
-	 * @param string $serveur
2759
-	 *    Nom du connecteur
2760
-	 * @return sqlite_requeteur
2761
-	 *    Instance unique du requêteur
2762
-	 **/
2763
-	public static function requeteur($serveur) {
2764
-		if (!isset(spip_sqlite::$requeteurs[$serveur])) {
2765
-			spip_sqlite::$requeteurs[$serveur] = new sqlite_requeteur($serveur);
2766
-		}
2767
-
2768
-		return spip_sqlite::$requeteurs[$serveur];
2769
-	}
2770
-
2771
-	/**
2772
-	 * Prépare le texte d'une requête avant son exécution
2773
-	 *
2774
-	 * Adapte la requête au format plus ou moins MySQL par un format
2775
-	 * compris de SQLite.
2776
-	 *
2777
-	 * Change les préfixes de tables SPIP par ceux véritables
2778
-	 *
2779
-	 * @param string $query Requête à préparer
2780
-	 * @param string $serveur Nom de la connexion
2781
-	 * @return string           Requête préparée
2782
-	 */
2783
-	public static function traduire_requete($query, $serveur) {
2784
-		$requeteur = spip_sqlite::requeteur($serveur);
2785
-		$traducteur = new sqlite_traducteur($query, $requeteur->prefixe, $requeteur->sqlite_version);
2786
-
2787
-		return $traducteur->traduire_requete();
2788
-	}
2789
-
2790
-	/**
2791
-	 * Démarre une transaction
2792
-	 *
2793
-	 * @param string $serveur Nom de la connexion
2794
-	 **/
2795
-	public static function demarrer_transaction($serveur) {
2796
-		spip_sqlite::executer_requete('BEGIN TRANSACTION', $serveur);
2797
-		spip_sqlite::$transaction_en_cours[$serveur] = true;
2798
-	}
2799
-
2800
-	/**
2801
-	 * Exécute la requête donnée
2802
-	 *
2803
-	 * @param string $query Requête
2804
-	 * @param string $serveur Nom de la connexion
2805
-	 * @param null|bool $tracer Demander des statistiques (temps) ?
2806
-	 **/
2807
-	public static function executer_requete($query, $serveur, $tracer = null) {
2808
-		$requeteur = spip_sqlite::requeteur($serveur);
2809
-
2810
-		return $requeteur->executer_requete($query, $tracer);
2811
-	}
2812
-
2813
-	/**
2814
-	 * Obtient l'identifiant de la dernière ligne insérée ou modifiée
2815
-	 *
2816
-	 * @param string $serveur Nom de la connexion
2817
-	 * return int                Identifiant
2818
-	 **/
2819
-	public static function last_insert_id($serveur) {
2820
-		$requeteur = spip_sqlite::requeteur($serveur);
2821
-
2822
-		return $requeteur->last_insert_id($serveur);
2823
-	}
2824
-
2825
-	/**
2826
-	 * Annule une transaction
2827
-	 *
2828
-	 * @param string $serveur Nom de la connexion
2829
-	 **/
2830
-	public static function annuler_transaction($serveur) {
2831
-		spip_sqlite::executer_requete('ROLLBACK', $serveur);
2832
-		spip_sqlite::$transaction_en_cours[$serveur] = false;
2833
-	}
2834
-
2835
-	/**
2836
-	 * Termine une transaction
2837
-	 *
2838
-	 * @param string $serveur Nom de la connexion
2839
-	 **/
2840
-	public static function finir_transaction($serveur) {
2841
-		// si pas de transaction en cours, ne rien faire et le dire
2842
-		if (
2843
-			!isset(spip_sqlite::$transaction_en_cours[$serveur])
2844
-			or spip_sqlite::$transaction_en_cours[$serveur] == false
2845
-		) {
2846
-			return false;
2847
-		}
2848
-		// sinon fermer la transaction et retourner true
2849
-		spip_sqlite::executer_requete('COMMIT', $serveur);
2850
-		spip_sqlite::$transaction_en_cours[$serveur] = false;
2851
-
2852
-		return true;
2853
-	}
2746
+    /** @var sqlite_requeteur[] Liste des instances de requêteurs créés */
2747
+    public static $requeteurs = [];
2748
+    /** @var bool[] Pour chaque connexion, flag pour savoir si une transaction est en cours */
2749
+    public static $transaction_en_cours = [];
2750
+
2751
+
2752
+    /**
2753
+     * Retourne une unique instance du requêteur
2754
+     *
2755
+     * Retourne une instance unique du requêteur pour une connexion SQLite
2756
+     * donnée
2757
+     *
2758
+     * @param string $serveur
2759
+     *    Nom du connecteur
2760
+     * @return sqlite_requeteur
2761
+     *    Instance unique du requêteur
2762
+     **/
2763
+    public static function requeteur($serveur) {
2764
+        if (!isset(spip_sqlite::$requeteurs[$serveur])) {
2765
+            spip_sqlite::$requeteurs[$serveur] = new sqlite_requeteur($serveur);
2766
+        }
2767
+
2768
+        return spip_sqlite::$requeteurs[$serveur];
2769
+    }
2770
+
2771
+    /**
2772
+     * Prépare le texte d'une requête avant son exécution
2773
+     *
2774
+     * Adapte la requête au format plus ou moins MySQL par un format
2775
+     * compris de SQLite.
2776
+     *
2777
+     * Change les préfixes de tables SPIP par ceux véritables
2778
+     *
2779
+     * @param string $query Requête à préparer
2780
+     * @param string $serveur Nom de la connexion
2781
+     * @return string           Requête préparée
2782
+     */
2783
+    public static function traduire_requete($query, $serveur) {
2784
+        $requeteur = spip_sqlite::requeteur($serveur);
2785
+        $traducteur = new sqlite_traducteur($query, $requeteur->prefixe, $requeteur->sqlite_version);
2786
+
2787
+        return $traducteur->traduire_requete();
2788
+    }
2789
+
2790
+    /**
2791
+     * Démarre une transaction
2792
+     *
2793
+     * @param string $serveur Nom de la connexion
2794
+     **/
2795
+    public static function demarrer_transaction($serveur) {
2796
+        spip_sqlite::executer_requete('BEGIN TRANSACTION', $serveur);
2797
+        spip_sqlite::$transaction_en_cours[$serveur] = true;
2798
+    }
2799
+
2800
+    /**
2801
+     * Exécute la requête donnée
2802
+     *
2803
+     * @param string $query Requête
2804
+     * @param string $serveur Nom de la connexion
2805
+     * @param null|bool $tracer Demander des statistiques (temps) ?
2806
+     **/
2807
+    public static function executer_requete($query, $serveur, $tracer = null) {
2808
+        $requeteur = spip_sqlite::requeteur($serveur);
2809
+
2810
+        return $requeteur->executer_requete($query, $tracer);
2811
+    }
2812
+
2813
+    /**
2814
+     * Obtient l'identifiant de la dernière ligne insérée ou modifiée
2815
+     *
2816
+     * @param string $serveur Nom de la connexion
2817
+     * return int                Identifiant
2818
+     **/
2819
+    public static function last_insert_id($serveur) {
2820
+        $requeteur = spip_sqlite::requeteur($serveur);
2821
+
2822
+        return $requeteur->last_insert_id($serveur);
2823
+    }
2824
+
2825
+    /**
2826
+     * Annule une transaction
2827
+     *
2828
+     * @param string $serveur Nom de la connexion
2829
+     **/
2830
+    public static function annuler_transaction($serveur) {
2831
+        spip_sqlite::executer_requete('ROLLBACK', $serveur);
2832
+        spip_sqlite::$transaction_en_cours[$serveur] = false;
2833
+    }
2834
+
2835
+    /**
2836
+     * Termine une transaction
2837
+     *
2838
+     * @param string $serveur Nom de la connexion
2839
+     **/
2840
+    public static function finir_transaction($serveur) {
2841
+        // si pas de transaction en cours, ne rien faire et le dire
2842
+        if (
2843
+            !isset(spip_sqlite::$transaction_en_cours[$serveur])
2844
+            or spip_sqlite::$transaction_en_cours[$serveur] == false
2845
+        ) {
2846
+            return false;
2847
+        }
2848
+        // sinon fermer la transaction et retourner true
2849
+        spip_sqlite::executer_requete('COMMIT', $serveur);
2850
+        spip_sqlite::$transaction_en_cours[$serveur] = false;
2851
+
2852
+        return true;
2853
+    }
2854 2854
 }
2855 2855
 
2856 2856
 /*
@@ -2863,121 +2863,121 @@  discard block
 block discarded – undo
2863 2863
  */
2864 2864
 
2865 2865
 class sqlite_requeteur {
2866
-	/** @var string Texte de la requête */
2867
-	public $query = ''; // la requete
2868
-	/** @var string Nom de la connexion */
2869
-	public $serveur = '';
2870
-	/** @var PDO Identifiant de la connexion SQLite */
2871
-	public $link = '';
2872
-	/** @var string Prefixe des tables SPIP */
2873
-	public $prefixe = '';
2874
-	/** @var string Nom de la base de donnée */
2875
-	public $db = '';
2876
-	/** @var bool Doit-on tracer les requetes (var_profile) ? */
2877
-	public $tracer = false; // doit-on tracer les requetes (var_profile)
2878
-
2879
-	/** @var string Version de SQLite (2 ou 3) */
2880
-	public $sqlite_version = '';
2881
-
2882
-	/**
2883
-	 * Constructeur
2884
-	 *
2885
-	 * @param string $serveur
2886
-	 * @return bool
2887
-	 */
2888
-	public function __construct($serveur = '') {
2889
-		_sqlite_init();
2890
-		$this->serveur = strtolower($serveur);
2891
-
2892
-		if (!($this->link = _sqlite_link($this->serveur)) && (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)) {
2893
-			spip_log('Aucune connexion sqlite (link)', 'sqlite.' . _LOG_ERREUR);
2894
-
2895
-			return false;
2896
-		}
2897
-
2898
-		$this->sqlite_version = _sqlite_is_version('', $this->link);
2899
-
2900
-		$this->prefixe = $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['prefixe'];
2901
-		$this->db = $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['db'];
2902
-
2903
-		// tracage des requetes ?
2904
-		$this->tracer = (isset($_GET['var_profile']) && $_GET['var_profile']);
2905
-	}
2906
-
2907
-	/**
2908
-	 * Lancer la requête transmise et faire le tracage si demandé
2909
-	 *
2910
-	 * @param string $query
2911
-	 *     Requête à exécuter
2912
-	 * @param bool|null $tracer
2913
-	 *     true pour tracer la requête
2914
-	 * @return bool|PDOStatement|array
2915
-	 */
2916
-	public function executer_requete($query, $tracer = null) {
2917
-		if (is_null($tracer)) {
2918
-			$tracer = $this->tracer;
2919
-		}
2920
-		$err = '';
2921
-		$t = 0;
2922
-		if ($tracer or (defined('_DEBUG_TRACE_QUERIES') and _DEBUG_TRACE_QUERIES)) {
2923
-			include_spip('public/tracer');
2924
-			$t = trace_query_start();
2925
-		}
2926
-
2927
-		# spip_log("requete: $this->serveur >> $query",'sqlite.'._LOG_DEBUG); // boum ? pourquoi ?
2928
-		if ($this->link) {
2929
-			// memoriser la derniere erreur PHP vue
2930
-			$last_error = (function_exists('error_get_last') ? error_get_last() : '');
2931
-			$e = null;
2932
-			// sauver la derniere requete
2933
-			$GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['last'] = $query;
2934
-			$GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['total_requetes']++;
2935
-
2936
-			try {
2937
-				$r = $this->link->query($query);
2938
-			} catch (\PDOException $e) {
2939
-				spip_log('PDOException: ' . $e->getMessage(), 'sqlite.' . _LOG_DEBUG);
2940
-				$r = false;
2941
-			}
2942
-
2943
-			// comptage : oblige de compter le nombre d'entrees retournees
2944
-			// par une requete SELECT
2945
-			// aucune autre solution ne donne le nombre attendu :( !
2946
-			// particulierement s'il y a des LIMIT dans la requete.
2947
-			if ($r and strtoupper(substr(ltrim($query), 0, 6)) === 'SELECT') {
2948
-				// noter le link et la query pour faire le comptage *si* on en a besoin
2949
-				$r->spipSqliteRowCount = [$this->link, $query];
2950
-			}
2951
-
2952
-			// loger les warnings/erreurs eventuels de sqlite remontant dans PHP
2953
-			if ($e and $e instanceof \PDOException) {
2954
-				$err = strip_tags($e->getMessage()) . ' in ' . $e->getFile() . ' line ' . $e->getLine();
2955
-				spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2956
-			} elseif ($err = (function_exists('error_get_last') ? error_get_last() : '') and $err != $last_error) {
2957
-				$err = strip_tags($err['message']) . ' in ' . $err['file'] . ' line ' . $err['line'];
2958
-				spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2959
-			} else {
2960
-				$err = '';
2961
-			}
2962
-		} else {
2963
-			$r = false;
2964
-		}
2965
-
2966
-		if (spip_sqlite_errno($this->serveur)) {
2967
-			$err .= spip_sqlite_error($query, $this->serveur);
2968
-		}
2969
-
2970
-		return $t ? trace_query_end($query, $t, $r, $err, $this->serveur) : $r;
2971
-	}
2972
-
2973
-	/**
2974
-	 * Obtient l'identifiant de la dernière ligne insérée ou modifiée
2975
-	 *
2976
-	 * @return string|false
2977
-	 **/
2978
-	public function last_insert_id() {
2979
-		return $this->link->lastInsertId();
2980
-	}
2866
+    /** @var string Texte de la requête */
2867
+    public $query = ''; // la requete
2868
+    /** @var string Nom de la connexion */
2869
+    public $serveur = '';
2870
+    /** @var PDO Identifiant de la connexion SQLite */
2871
+    public $link = '';
2872
+    /** @var string Prefixe des tables SPIP */
2873
+    public $prefixe = '';
2874
+    /** @var string Nom de la base de donnée */
2875
+    public $db = '';
2876
+    /** @var bool Doit-on tracer les requetes (var_profile) ? */
2877
+    public $tracer = false; // doit-on tracer les requetes (var_profile)
2878
+
2879
+    /** @var string Version de SQLite (2 ou 3) */
2880
+    public $sqlite_version = '';
2881
+
2882
+    /**
2883
+     * Constructeur
2884
+     *
2885
+     * @param string $serveur
2886
+     * @return bool
2887
+     */
2888
+    public function __construct($serveur = '') {
2889
+        _sqlite_init();
2890
+        $this->serveur = strtolower($serveur);
2891
+
2892
+        if (!($this->link = _sqlite_link($this->serveur)) && (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)) {
2893
+            spip_log('Aucune connexion sqlite (link)', 'sqlite.' . _LOG_ERREUR);
2894
+
2895
+            return false;
2896
+        }
2897
+
2898
+        $this->sqlite_version = _sqlite_is_version('', $this->link);
2899
+
2900
+        $this->prefixe = $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['prefixe'];
2901
+        $this->db = $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['db'];
2902
+
2903
+        // tracage des requetes ?
2904
+        $this->tracer = (isset($_GET['var_profile']) && $_GET['var_profile']);
2905
+    }
2906
+
2907
+    /**
2908
+     * Lancer la requête transmise et faire le tracage si demandé
2909
+     *
2910
+     * @param string $query
2911
+     *     Requête à exécuter
2912
+     * @param bool|null $tracer
2913
+     *     true pour tracer la requête
2914
+     * @return bool|PDOStatement|array
2915
+     */
2916
+    public function executer_requete($query, $tracer = null) {
2917
+        if (is_null($tracer)) {
2918
+            $tracer = $this->tracer;
2919
+        }
2920
+        $err = '';
2921
+        $t = 0;
2922
+        if ($tracer or (defined('_DEBUG_TRACE_QUERIES') and _DEBUG_TRACE_QUERIES)) {
2923
+            include_spip('public/tracer');
2924
+            $t = trace_query_start();
2925
+        }
2926
+
2927
+        # spip_log("requete: $this->serveur >> $query",'sqlite.'._LOG_DEBUG); // boum ? pourquoi ?
2928
+        if ($this->link) {
2929
+            // memoriser la derniere erreur PHP vue
2930
+            $last_error = (function_exists('error_get_last') ? error_get_last() : '');
2931
+            $e = null;
2932
+            // sauver la derniere requete
2933
+            $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['last'] = $query;
2934
+            $GLOBALS['connexions'][$this->serveur ? $this->serveur : 0]['total_requetes']++;
2935
+
2936
+            try {
2937
+                $r = $this->link->query($query);
2938
+            } catch (\PDOException $e) {
2939
+                spip_log('PDOException: ' . $e->getMessage(), 'sqlite.' . _LOG_DEBUG);
2940
+                $r = false;
2941
+            }
2942
+
2943
+            // comptage : oblige de compter le nombre d'entrees retournees
2944
+            // par une requete SELECT
2945
+            // aucune autre solution ne donne le nombre attendu :( !
2946
+            // particulierement s'il y a des LIMIT dans la requete.
2947
+            if ($r and strtoupper(substr(ltrim($query), 0, 6)) === 'SELECT') {
2948
+                // noter le link et la query pour faire le comptage *si* on en a besoin
2949
+                $r->spipSqliteRowCount = [$this->link, $query];
2950
+            }
2951
+
2952
+            // loger les warnings/erreurs eventuels de sqlite remontant dans PHP
2953
+            if ($e and $e instanceof \PDOException) {
2954
+                $err = strip_tags($e->getMessage()) . ' in ' . $e->getFile() . ' line ' . $e->getLine();
2955
+                spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2956
+            } elseif ($err = (function_exists('error_get_last') ? error_get_last() : '') and $err != $last_error) {
2957
+                $err = strip_tags($err['message']) . ' in ' . $err['file'] . ' line ' . $err['line'];
2958
+                spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2959
+            } else {
2960
+                $err = '';
2961
+            }
2962
+        } else {
2963
+            $r = false;
2964
+        }
2965
+
2966
+        if (spip_sqlite_errno($this->serveur)) {
2967
+            $err .= spip_sqlite_error($query, $this->serveur);
2968
+        }
2969
+
2970
+        return $t ? trace_query_end($query, $t, $r, $err, $this->serveur) : $r;
2971
+    }
2972
+
2973
+    /**
2974
+     * Obtient l'identifiant de la dernière ligne insérée ou modifiée
2975
+     *
2976
+     * @return string|false
2977
+     **/
2978
+    public function last_insert_id() {
2979
+        return $this->link->lastInsertId();
2980
+    }
2981 2981
 }
2982 2982
 
2983 2983
 
@@ -2987,206 +2987,206 @@  discard block
 block discarded – undo
2987 2987
  * (fonction pour proteger les textes)
2988 2988
  */
2989 2989
 class sqlite_traducteur {
2990
-	/** @var string $query Texte de la requête */
2991
-	public $query = '';
2992
-	/** @var string $prefixe Préfixe des tables */
2993
-	public $prefixe = '';
2994
-	/** @var string $sqlite_version Version de sqlite (2 ou 3) */
2995
-	public $sqlite_version = '';
2996
-
2997
-	/** Pour les corrections à effectuer sur les requêtes : array(code=>'texte') trouvé
2998
-	 *
2999
-	 * @var array
3000
-	 */
3001
-	public $textes = [];
3002
-
3003
-	/**
3004
-	 * Constructeur
3005
-	 *
3006
-	 * @param string $query Requête à préparer
3007
-	 * @param string $prefixe Prefixe des tables à utiliser
3008
-	 * @param string $sqlite_version Version SQLite (2 ou 3)
3009
-	 */
3010
-	public function __construct($query, $prefixe, $sqlite_version) {
3011
-		$this->query = $query;
3012
-		$this->prefixe = $prefixe;
3013
-		$this->sqlite_version = $sqlite_version;
3014
-	}
3015
-
3016
-	/**
3017
-	 * Transformer la requete pour SQLite
3018
-	 *
3019
-	 * Enlève les textes, transforme la requête pour quelle soit
3020
-	 * bien interprétée par SQLite, puis remet les textes
3021
-	 * la fonction affecte `$this->query`
3022
-	 */
3023
-	public function traduire_requete() {
3024
-		//
3025
-		// 1) Protection des textes en les remplacant par des codes
3026
-		//
3027
-		// enlever les 'textes' et initialiser avec
3028
-		list($this->query, $textes) = query_echappe_textes($this->query);
3029
-
3030
-		//
3031
-		// 2) Corrections de la requete
3032
-		//
3033
-		// Correction Create Database
3034
-		// Create Database -> requete ignoree
3035
-		if (strpos($this->query, 'CREATE DATABASE') === 0) {
3036
-			spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.' . _LOG_AVERTISSEMENT);
3037
-			$this->query = 'SELECT 1';
3038
-		}
3039
-
3040
-		// Correction Insert Ignore
3041
-		// INSERT IGNORE -> insert (tout court et pas 'insert or replace')
3042
-		if (strpos($this->query, 'INSERT IGNORE') === 0) {
3043
-			spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.' . _LOG_DEBUG);
3044
-			$this->query = 'INSERT ' . substr($this->query, '13');
3045
-		}
3046
-
3047
-		// Correction des dates avec INTERVAL
3048
-		// utiliser sql_date_proche() de preference
3049
-		if (strpos($this->query, 'INTERVAL') !== false) {
3050
-			$this->query = preg_replace_callback(
3051
-				'/DATE_(ADD|SUB)(.*)INTERVAL\s+(\d+)\s+([a-zA-Z]+)\)/U',
3052
-				[&$this, '_remplacerDateParTime'],
3053
-				$this->query
3054
-			);
3055
-		}
3056
-
3057
-		if (strpos($this->query, 'LEFT(') !== false) {
3058
-			$this->query = str_replace('LEFT(', '_LEFT(', $this->query);
3059
-		}
3060
-
3061
-		if (strpos($this->query, 'TIMESTAMPDIFF(') !== false) {
3062
-			$this->query = preg_replace('/TIMESTAMPDIFF\(\s*([^,]*)\s*,/Uims', "TIMESTAMPDIFF('\\1',", $this->query);
3063
-		}
3064
-
3065
-
3066
-		// Correction Using
3067
-		// USING (non reconnu en sqlite2)
3068
-		// problematique car la jointure ne se fait pas du coup.
3069
-		if (($this->sqlite_version == 2) && (strpos($this->query, 'USING') !== false)) {
3070
-			spip_log(
3071
-				"'USING (champ)' n'est pas reconnu en SQLite 2. Utilisez 'ON table1.champ = table2.champ'",
3072
-				'sqlite.' . _LOG_ERREUR
3073
-			);
3074
-			$this->query = preg_replace('/USING\s*\([^\)]*\)/', '', $this->query);
3075
-		}
3076
-
3077
-		// Correction Field
3078
-		// remplace FIELD(table,i,j,k...) par CASE WHEN table=i THEN n ... ELSE 0 END
3079
-		if (strpos($this->query, 'FIELD') !== false) {
3080
-			$this->query = preg_replace_callback(
3081
-				'/FIELD\s*\(([^\)]*)\)/',
3082
-				[&$this, '_remplacerFieldParCase'],
3083
-				$this->query
3084
-			);
3085
-		}
3086
-
3087
-		// Correction des noms de tables FROM
3088
-		// mettre les bons noms de table dans from, update, insert, replace...
3089
-		if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/iS', $this->query, $regs)) {
3090
-			$suite = strstr($this->query, $regs[0]);
3091
-			$this->query = substr($this->query, 0, -strlen($suite));
3092
-		} else {
3093
-			$suite = '';
3094
-		}
3095
-		$pref = ($this->prefixe) ? $this->prefixe . '_' : '';
3096
-		$this->query = preg_replace('/([,\s])spip_/S', '\1' . $pref, $this->query) . $suite;
3097
-
3098
-		// Correction zero AS x
3099
-		// pg n'aime pas 0+x AS alias, sqlite, dans le meme style,
3100
-		// n'apprecie pas du tout SELECT 0 as x ... ORDER BY x
3101
-		// il dit que x ne doit pas être un integer dans le order by !
3102
-		// on remplace du coup x par vide() dans ce cas uniquement
3103
-		//
3104
-		// apparait dans public/vertebrer.php et dans le plugin menu aussi qui genere aussi ce genre de requete via un {par num #GET{tri_num}}
3105
-		// mais est-ce encore un soucis pour sqlite en 2021 ? (ie commenter le preg_replace marche très bien en sqlite 3.28)
3106
-		if ((strpos($this->query, '0 AS') !== false)) {
3107
-			// on ne remplace que dans ORDER BY ou GROUP BY
3108
-			if (preg_match('/\s(ORDER|GROUP) BY\s/i', $this->query, $regs)) {
3109
-				$suite = strstr($this->query, $regs[0]);
3110
-				$this->query = substr($this->query, 0, -strlen($suite));
3111
-
3112
-				// on cherche les noms des x dans 0 AS x
3113
-				// on remplace dans $suite le nom par vide()
3114
-				preg_match_all('/\b0 AS\s*([^\s,]+)/', $this->query, $matches, PREG_PATTERN_ORDER);
3115
-				foreach ($matches[1] as $m) {
3116
-					if (strpos($suite, $m) !== false) {
3117
-						$suite = preg_replace(",\b$m\b,", 'VIDE()', $suite);
3118
-					}
3119
-				}
3120
-				$this->query .= $suite;
3121
-			}
3122
-		}
3123
-
3124
-		// Correction possible des divisions entieres
3125
-		// Le standard SQL (lequel? ou?) semble indiquer que
3126
-		// a/b=c doit donner c entier si a et b sont entiers 4/3=1.
3127
-		// C'est ce que retournent effectivement SQL Server et SQLite
3128
-		// Ce n'est pas ce qu'applique MySQL qui retourne un reel : 4/3=1.333...
3129
-		//
3130
-		// On peut forcer la conversion en multipliant par 1.0 avant la division
3131
-		// /!\ SQLite 3.5.9 Debian/Ubuntu est victime d'un bug en plus !
3132
-		// cf. https://bugs.launchpad.net/ubuntu/+source/sqlite3/+bug/254228
3133
-		//     http://www.sqlite.org/cvstrac/tktview?tn=3202
3134
-		// (4*1.0/3) n'est pas rendu dans ce cas !
3135
-		# $this->query = str_replace('/','* 1.00 / ',$this->query);
3136
-
3137
-
3138
-		// Correction critere REGEXP, non reconnu en sqlite2
3139
-		if (($this->sqlite_version == 2) && (strpos($this->query, 'REGEXP') !== false)) {
3140
-			$this->query = preg_replace('/([^\s\(]*)(\s*)REGEXP(\s*)([^\s\)]*)/', 'REGEXP($4, $1)', $this->query);
3141
-		}
3142
-
3143
-		//
3144
-		// 3) Remise en place des textes d'origine
3145
-		//
3146
-		// Correction Antiquotes et echappements
3147
-		// ` => rien
3148
-		if (strpos($this->query, '`') !== false) {
3149
-			$this->query = str_replace('`', '', $this->query);
3150
-		}
3151
-
3152
-		$this->query = query_reinjecte_textes($this->query, $textes);
3153
-
3154
-		return $this->query;
3155
-	}
3156
-
3157
-
3158
-	/**
3159
-	 * Callback pour remplacer `DATE_` / `INTERVAL`
3160
-	 * par `DATE ... strtotime`
3161
-	 *
3162
-	 * @param array $matches Captures
3163
-	 * @return string Texte de date compris par SQLite
3164
-	 */
3165
-	public function _remplacerDateParTime($matches) {
3166
-		$op = strtoupper($matches[1] == 'ADD') ? '+' : '-';
3167
-
3168
-		return "datetime$matches[2] '$op$matches[3] $matches[4]')";
3169
-	}
3170
-
3171
-	/**
3172
-	 * Callback pour remplacer `FIELD(table,i,j,k...)`
3173
-	 * par `CASE WHEN table=i THEN n ... ELSE 0 END`
3174
-	 *
3175
-	 * @param array $matches Captures
3176
-	 * @return string Texte de liste ordonnée compris par SQLite
3177
-	 */
3178
-	public function _remplacerFieldParCase($matches) {
3179
-		$fields = substr($matches[0], 6, -1); // ne recuperer que l'interieur X de field(X)
3180
-		$t = explode(',', $fields);
3181
-		$index = array_shift($t);
3182
-
3183
-		$res = '';
3184
-		$n = 0;
3185
-		foreach ($t as $v) {
3186
-			$n++;
3187
-			$res .= "\nWHEN $index=$v THEN $n";
3188
-		}
3189
-
3190
-		return "CASE $res ELSE 0 END ";
3191
-	}
2990
+    /** @var string $query Texte de la requête */
2991
+    public $query = '';
2992
+    /** @var string $prefixe Préfixe des tables */
2993
+    public $prefixe = '';
2994
+    /** @var string $sqlite_version Version de sqlite (2 ou 3) */
2995
+    public $sqlite_version = '';
2996
+
2997
+    /** Pour les corrections à effectuer sur les requêtes : array(code=>'texte') trouvé
2998
+     *
2999
+     * @var array
3000
+     */
3001
+    public $textes = [];
3002
+
3003
+    /**
3004
+     * Constructeur
3005
+     *
3006
+     * @param string $query Requête à préparer
3007
+     * @param string $prefixe Prefixe des tables à utiliser
3008
+     * @param string $sqlite_version Version SQLite (2 ou 3)
3009
+     */
3010
+    public function __construct($query, $prefixe, $sqlite_version) {
3011
+        $this->query = $query;
3012
+        $this->prefixe = $prefixe;
3013
+        $this->sqlite_version = $sqlite_version;
3014
+    }
3015
+
3016
+    /**
3017
+     * Transformer la requete pour SQLite
3018
+     *
3019
+     * Enlève les textes, transforme la requête pour quelle soit
3020
+     * bien interprétée par SQLite, puis remet les textes
3021
+     * la fonction affecte `$this->query`
3022
+     */
3023
+    public function traduire_requete() {
3024
+        //
3025
+        // 1) Protection des textes en les remplacant par des codes
3026
+        //
3027
+        // enlever les 'textes' et initialiser avec
3028
+        list($this->query, $textes) = query_echappe_textes($this->query);
3029
+
3030
+        //
3031
+        // 2) Corrections de la requete
3032
+        //
3033
+        // Correction Create Database
3034
+        // Create Database -> requete ignoree
3035
+        if (strpos($this->query, 'CREATE DATABASE') === 0) {
3036
+            spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.' . _LOG_AVERTISSEMENT);
3037
+            $this->query = 'SELECT 1';
3038
+        }
3039
+
3040
+        // Correction Insert Ignore
3041
+        // INSERT IGNORE -> insert (tout court et pas 'insert or replace')
3042
+        if (strpos($this->query, 'INSERT IGNORE') === 0) {
3043
+            spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.' . _LOG_DEBUG);
3044
+            $this->query = 'INSERT ' . substr($this->query, '13');
3045
+        }
3046
+
3047
+        // Correction des dates avec INTERVAL
3048
+        // utiliser sql_date_proche() de preference
3049
+        if (strpos($this->query, 'INTERVAL') !== false) {
3050
+            $this->query = preg_replace_callback(
3051
+                '/DATE_(ADD|SUB)(.*)INTERVAL\s+(\d+)\s+([a-zA-Z]+)\)/U',
3052
+                [&$this, '_remplacerDateParTime'],
3053
+                $this->query
3054
+            );
3055
+        }
3056
+
3057
+        if (strpos($this->query, 'LEFT(') !== false) {
3058
+            $this->query = str_replace('LEFT(', '_LEFT(', $this->query);
3059
+        }
3060
+
3061
+        if (strpos($this->query, 'TIMESTAMPDIFF(') !== false) {
3062
+            $this->query = preg_replace('/TIMESTAMPDIFF\(\s*([^,]*)\s*,/Uims', "TIMESTAMPDIFF('\\1',", $this->query);
3063
+        }
3064
+
3065
+
3066
+        // Correction Using
3067
+        // USING (non reconnu en sqlite2)
3068
+        // problematique car la jointure ne se fait pas du coup.
3069
+        if (($this->sqlite_version == 2) && (strpos($this->query, 'USING') !== false)) {
3070
+            spip_log(
3071
+                "'USING (champ)' n'est pas reconnu en SQLite 2. Utilisez 'ON table1.champ = table2.champ'",
3072
+                'sqlite.' . _LOG_ERREUR
3073
+            );
3074
+            $this->query = preg_replace('/USING\s*\([^\)]*\)/', '', $this->query);
3075
+        }
3076
+
3077
+        // Correction Field
3078
+        // remplace FIELD(table,i,j,k...) par CASE WHEN table=i THEN n ... ELSE 0 END
3079
+        if (strpos($this->query, 'FIELD') !== false) {
3080
+            $this->query = preg_replace_callback(
3081
+                '/FIELD\s*\(([^\)]*)\)/',
3082
+                [&$this, '_remplacerFieldParCase'],
3083
+                $this->query
3084
+            );
3085
+        }
3086
+
3087
+        // Correction des noms de tables FROM
3088
+        // mettre les bons noms de table dans from, update, insert, replace...
3089
+        if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/iS', $this->query, $regs)) {
3090
+            $suite = strstr($this->query, $regs[0]);
3091
+            $this->query = substr($this->query, 0, -strlen($suite));
3092
+        } else {
3093
+            $suite = '';
3094
+        }
3095
+        $pref = ($this->prefixe) ? $this->prefixe . '_' : '';
3096
+        $this->query = preg_replace('/([,\s])spip_/S', '\1' . $pref, $this->query) . $suite;
3097
+
3098
+        // Correction zero AS x
3099
+        // pg n'aime pas 0+x AS alias, sqlite, dans le meme style,
3100
+        // n'apprecie pas du tout SELECT 0 as x ... ORDER BY x
3101
+        // il dit que x ne doit pas être un integer dans le order by !
3102
+        // on remplace du coup x par vide() dans ce cas uniquement
3103
+        //
3104
+        // apparait dans public/vertebrer.php et dans le plugin menu aussi qui genere aussi ce genre de requete via un {par num #GET{tri_num}}
3105
+        // mais est-ce encore un soucis pour sqlite en 2021 ? (ie commenter le preg_replace marche très bien en sqlite 3.28)
3106
+        if ((strpos($this->query, '0 AS') !== false)) {
3107
+            // on ne remplace que dans ORDER BY ou GROUP BY
3108
+            if (preg_match('/\s(ORDER|GROUP) BY\s/i', $this->query, $regs)) {
3109
+                $suite = strstr($this->query, $regs[0]);
3110
+                $this->query = substr($this->query, 0, -strlen($suite));
3111
+
3112
+                // on cherche les noms des x dans 0 AS x
3113
+                // on remplace dans $suite le nom par vide()
3114
+                preg_match_all('/\b0 AS\s*([^\s,]+)/', $this->query, $matches, PREG_PATTERN_ORDER);
3115
+                foreach ($matches[1] as $m) {
3116
+                    if (strpos($suite, $m) !== false) {
3117
+                        $suite = preg_replace(",\b$m\b,", 'VIDE()', $suite);
3118
+                    }
3119
+                }
3120
+                $this->query .= $suite;
3121
+            }
3122
+        }
3123
+
3124
+        // Correction possible des divisions entieres
3125
+        // Le standard SQL (lequel? ou?) semble indiquer que
3126
+        // a/b=c doit donner c entier si a et b sont entiers 4/3=1.
3127
+        // C'est ce que retournent effectivement SQL Server et SQLite
3128
+        // Ce n'est pas ce qu'applique MySQL qui retourne un reel : 4/3=1.333...
3129
+        //
3130
+        // On peut forcer la conversion en multipliant par 1.0 avant la division
3131
+        // /!\ SQLite 3.5.9 Debian/Ubuntu est victime d'un bug en plus !
3132
+        // cf. https://bugs.launchpad.net/ubuntu/+source/sqlite3/+bug/254228
3133
+        //     http://www.sqlite.org/cvstrac/tktview?tn=3202
3134
+        // (4*1.0/3) n'est pas rendu dans ce cas !
3135
+        # $this->query = str_replace('/','* 1.00 / ',$this->query);
3136
+
3137
+
3138
+        // Correction critere REGEXP, non reconnu en sqlite2
3139
+        if (($this->sqlite_version == 2) && (strpos($this->query, 'REGEXP') !== false)) {
3140
+            $this->query = preg_replace('/([^\s\(]*)(\s*)REGEXP(\s*)([^\s\)]*)/', 'REGEXP($4, $1)', $this->query);
3141
+        }
3142
+
3143
+        //
3144
+        // 3) Remise en place des textes d'origine
3145
+        //
3146
+        // Correction Antiquotes et echappements
3147
+        // ` => rien
3148
+        if (strpos($this->query, '`') !== false) {
3149
+            $this->query = str_replace('`', '', $this->query);
3150
+        }
3151
+
3152
+        $this->query = query_reinjecte_textes($this->query, $textes);
3153
+
3154
+        return $this->query;
3155
+    }
3156
+
3157
+
3158
+    /**
3159
+     * Callback pour remplacer `DATE_` / `INTERVAL`
3160
+     * par `DATE ... strtotime`
3161
+     *
3162
+     * @param array $matches Captures
3163
+     * @return string Texte de date compris par SQLite
3164
+     */
3165
+    public function _remplacerDateParTime($matches) {
3166
+        $op = strtoupper($matches[1] == 'ADD') ? '+' : '-';
3167
+
3168
+        return "datetime$matches[2] '$op$matches[3] $matches[4]')";
3169
+    }
3170
+
3171
+    /**
3172
+     * Callback pour remplacer `FIELD(table,i,j,k...)`
3173
+     * par `CASE WHEN table=i THEN n ... ELSE 0 END`
3174
+     *
3175
+     * @param array $matches Captures
3176
+     * @return string Texte de liste ordonnée compris par SQLite
3177
+     */
3178
+    public function _remplacerFieldParCase($matches) {
3179
+        $fields = substr($matches[0], 6, -1); // ne recuperer que l'interieur X de field(X)
3180
+        $t = explode(',', $fields);
3181
+        $index = array_shift($t);
3182
+
3183
+        $res = '';
3184
+        $n = 0;
3185
+        foreach ($t as $v) {
3186
+            $n++;
3187
+            $res .= "\nWHEN $index=$v THEN $n";
3188
+        }
3189
+
3190
+        return "CASE $res ELSE 0 END ";
3191
+    }
3192 3192
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -64,27 +64,27 @@  discard block
 block discarded – undo
64 64
 	// determiner le dossier de la base : $addr ou _DIR_DB
65 65
 	$f = _DIR_DB;
66 66
 	if ($addr and strpos($addr, '/') !== false) {
67
-		$f = rtrim($addr, '/') . '/';
67
+		$f = rtrim($addr, '/').'/';
68 68
 	}
69 69
 
70 70
 	// un nom de base demande et impossible d'obtenir la base, on s'en va :
71 71
 	// il faut que la base existe ou que le repertoire parent soit writable
72
-	if ($db and !is_file($f .= $db . '.sqlite') and !is_writable(dirname($f))) {
73
-		spip_log("base $f non trouvee ou droits en ecriture manquants", 'sqlite.' . _LOG_HS);
72
+	if ($db and !is_file($f .= $db.'.sqlite') and !is_writable(dirname($f))) {
73
+		spip_log("base $f non trouvee ou droits en ecriture manquants", 'sqlite.'._LOG_HS);
74 74
 
75 75
 		return false;
76 76
 	}
77 77
 
78 78
 	// charger les modules sqlite au besoin
79 79
 	if (!_sqlite_charger_version($sqlite_version)) {
80
-		spip_log("Impossible de trouver/charger le module SQLite ($sqlite_version)!", 'sqlite.' . _LOG_HS);
80
+		spip_log("Impossible de trouver/charger le module SQLite ($sqlite_version)!", 'sqlite.'._LOG_HS);
81 81
 
82 82
 		return false;
83 83
 	}
84 84
 
85 85
 	// chargement des constantes
86 86
 	// il ne faut pas definir les constantes avant d'avoir charge les modules sqlite
87
-	$define = 'spip_sqlite' . $sqlite_version . '_constantes';
87
+	$define = 'spip_sqlite'.$sqlite_version.'_constantes';
88 88
 	$define();
89 89
 
90 90
 	$ok = false;
@@ -92,8 +92,8 @@  discard block
 block discarded – undo
92 92
 		// si pas de db ->
93 93
 		// base temporaire tant qu'on ne connait pas son vrai nom
94 94
 		// pour tester la connexion
95
-		$db = '_sqlite' . $sqlite_version . '_install';
96
-		$tmp = _DIR_DB . $db . '.sqlite';
95
+		$db = '_sqlite'.$sqlite_version.'_install';
96
+		$tmp = _DIR_DB.$db.'.sqlite';
97 97
 		$ok = $link = new \PDO("sqlite:$tmp");
98 98
 	} else {
99 99
 		// Ouvrir (eventuellement creer la base)
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 
103 103
 	if (!$ok) {
104 104
 		$e = _sqlite_last_error_from_link($link);
105
-		spip_log("Impossible d'ouvrir la base SQLite($sqlite_version) $f : $e", 'sqlite.' . _LOG_HS);
105
+		spip_log("Impossible d'ouvrir la base SQLite($sqlite_version) $f : $e", 'sqlite.'._LOG_HS);
106 106
 
107 107
 		return false;
108 108
 	}
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 		$table = $regs[3];
189 189
 		$suite = $regs[4];
190 190
 	} else {
191
-		spip_log("SQLite : Probleme de ALTER TABLE mal forme dans $query", 'sqlite.' . _LOG_ERREUR);
191
+		spip_log("SQLite : Probleme de ALTER TABLE mal forme dans $query", 'sqlite.'._LOG_ERREUR);
192 192
 
193 193
 		return false;
194 194
 	}
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 	$i = 0;
206 206
 	$ouverte = false;
207 207
 	while ($do = array_shift($todo)) {
208
-		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . ',' . $do : $do;
208
+		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i].','.$do : $do;
209 209
 		$o = (false !== strpos($do, '('));
210 210
 		$f = (false !== strpos($do, ')'));
211 211
 		if ($o and !$f) {
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 		) {
232 232
 			spip_log(
233 233
 				"SQLite : Probleme de ALTER TABLE, utilisation non reconnue dans : $do \n(requete d'origine : $query)",
234
-				'sqlite.' . _LOG_ERREUR
234
+				'sqlite.'._LOG_ERREUR
235 235
 			);
236 236
 
237 237
 			return false;
@@ -327,10 +327,10 @@  discard block
 block discarded – undo
327 327
 
328 328
 			// pas geres en sqlite2
329 329
 			case 'RENAME':
330
-				$do = 'RENAME TO' . substr($do, 6);
330
+				$do = 'RENAME TO'.substr($do, 6);
331 331
 			case 'RENAME TO':
332 332
 				if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
333
-					spip_log("SQLite : Erreur ALTER TABLE / RENAME : $query", 'sqlite.' . _LOG_ERREUR);
333
+					spip_log("SQLite : Erreur ALTER TABLE / RENAME : $query", 'sqlite.'._LOG_ERREUR);
334 334
 
335 335
 					return false;
336 336
 				}
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 						$colonnes = substr($colonne_origine, 1, -1);
374 374
 						if (false !== strpos(',', $colonnes)) {
375 375
 							spip_log('SQLite : Erreur, impossible de creer un index sur plusieurs colonnes'
376
-								. " sans qu'il ait de nom ($table, ($colonnes))", 'sqlite.' . _LOG_ERREUR);
376
+								. " sans qu'il ait de nom ($table, ($colonnes))", 'sqlite.'._LOG_ERREUR);
377 377
 							break;
378 378
 						} else {
379 379
 							$nom_index = $colonnes;
@@ -388,12 +388,12 @@  discard block
 block discarded – undo
388 388
 
389 389
 			// pas geres en sqlite2
390 390
 			case 'ADD COLUMN':
391
-				$do = 'ADD' . substr($do, 10);
391
+				$do = 'ADD'.substr($do, 10);
392 392
 			case 'ADD':
393 393
 			default:
394 394
 				if (!preg_match(',primary\s+key,i', $do)) {
395 395
 					if (!spip_sqlite::executer_requete("$debut $do", $serveur)) {
396
-						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
396
+						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.'._LOG_ERREUR);
397 397
 
398 398
 						return false;
399 399
 					}
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 					}
414 414
 					$opts['field'] = [$colonne_ajoutee => $def];
415 415
 					if (!_sqlite_modifier_table($table, [$colonne_ajoutee], $opts, $serveur)) {
416
-						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.' . _LOG_ERREUR);
416
+						spip_log("SQLite : Erreur ALTER TABLE / ADD : $query", 'sqlite.'._LOG_ERREUR);
417 417
 
418 418
 						return false;
419 419
 					}
@@ -421,10 +421,10 @@  discard block
 block discarded – undo
421 421
 				break;
422 422
 		}
423 423
 		// tout est bon, ouf !
424
-		spip_log("SQLite ($serveur) : Changements OK : $debut $do", 'sqlite.' . _LOG_INFO);
424
+		spip_log("SQLite ($serveur) : Changements OK : $debut $do", 'sqlite.'._LOG_INFO);
425 425
 	}
426 426
 
427
-	spip_log("SQLite ($serveur) : fin ALTER TABLE OK !", 'sqlite.' . _LOG_INFO);
427
+	spip_log("SQLite ($serveur) : fin ALTER TABLE OK !", 'sqlite.'._LOG_INFO);
428 428
 
429 429
 	return true;
430 430
 }
@@ -493,9 +493,9 @@  discard block
 block discarded – undo
493 493
  * @return bool true si la base est créee.
494 494
  **/
495 495
 function spip_sqlite_create_base($nom, $serveur = '', $option = true) {
496
-	$f = $nom . '.sqlite';
496
+	$f = $nom.'.sqlite';
497 497
 	if (strpos($nom, '/') === false) {
498
-		$f = _DIR_DB . $f;
498
+		$f = _DIR_DB.$f;
499 499
 	}
500 500
 
501 501
 	$ok = new \PDO("sqlite:$f");
@@ -535,13 +535,13 @@  discard block
 block discarded – undo
535 535
 	if (sql_showtable($nom, false, $serveur)) {
536 536
 		spip_log(
537 537
 			"Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)",
538
-			'sqlite.' . _LOG_ERREUR
538
+			'sqlite.'._LOG_ERREUR
539 539
 		);
540 540
 
541 541
 		return false;
542 542
 	}
543 543
 
544
-	$query = "CREATE VIEW $nom AS " . $query_select;
544
+	$query = "CREATE VIEW $nom AS ".$query_select;
545 545
 
546 546
 	return spip_sqlite_query($query, $serveur, $requeter);
547 547
 }
@@ -567,8 +567,8 @@  discard block
 block discarded – undo
567 567
 function spip_sqlite_create_index($nom, $table, $champs, $unique = '', $serveur = '', $requeter = true) {
568 568
 	if (!($nom or $table or $champs)) {
569 569
 		spip_log(
570
-			"Champ manquant pour creer un index sqlite ($nom, $table, (" . join(',', $champs) . '))',
571
-			'sqlite.' . _LOG_ERREUR
570
+			"Champ manquant pour creer un index sqlite ($nom, $table, (".join(',', $champs).'))',
571
+			'sqlite.'._LOG_ERREUR
572 572
 		);
573 573
 
574 574
 		return false;
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 
577 577
 	// SQLite ne differentie pas noms des index en fonction des tables
578 578
 	// il faut donc creer des noms uniques d'index pour une base sqlite
579
-	$nom = $table . '_' . $nom;
579
+	$nom = $table.'_'.$nom;
580 580
 	// enlever d'eventuelles parentheses deja presentes sur champs
581 581
 	if (!is_array($champs)) {
582 582
 		if ($champs[0] == '(') {
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
 	} else {
599 599
 		/* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
600 600
 		$a = spip_sqlite_showtable($table, $serveur);
601
-		if (isset($a['key']['KEY ' . $nom])) {
601
+		if (isset($a['key']['KEY '.$nom])) {
602 602
 			return true;
603 603
 		}
604 604
 	}
605 605
 
606
-	$query = 'CREATE ' . ($unique ? 'UNIQUE ' : '') . "INDEX$ifnotexists $nom ON $table (" . join(',', $champs) . ')';
606
+	$query = 'CREATE '.($unique ? 'UNIQUE ' : '')."INDEX$ifnotexists $nom ON $table (".join(',', $champs).')';
607 607
 	$res = spip_sqlite_query($query, $serveur, $requeter);
608 608
 	if (!$requeter) {
609 609
 		return $res;
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
 	$serveur = '',
680 680
 	$requeter = true
681 681
 ) {
682
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
682
+	$c = !$groupby ? '*' : ('DISTINCT '.(is_string($groupby) ? $groupby : join(',', $groupby)));
683 683
 	$r = spip_sqlite_select(
684 684
 		"COUNT($c)",
685 685
 		$from,
@@ -788,14 +788,14 @@  discard block
 block discarded – undo
788 788
  */
789 789
 function spip_sqlite_drop_index($nom, $table, $serveur = '', $requeter = true) {
790 790
 	if (!($nom or $table)) {
791
-		spip_log("Champ manquant pour supprimer un index sqlite ($nom, $table)", 'sqlite.' . _LOG_ERREUR);
791
+		spip_log("Champ manquant pour supprimer un index sqlite ($nom, $table)", 'sqlite.'._LOG_ERREUR);
792 792
 
793 793
 		return false;
794 794
 	}
795 795
 
796 796
 	// SQLite ne differentie pas noms des index en fonction des tables
797 797
 	// il faut donc creer des noms uniques d'index pour une base sqlite
798
-	$index = $table . '_' . $nom;
798
+	$index = $table.'_'.$nom;
799 799
 	$exist = ' IF EXISTS';
800 800
 
801 801
 	$query = "DROP INDEX$exist $index";
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
 	if ($s) {
828 828
 		$trace = debug_backtrace();
829 829
 		if ($trace[0]['function'] != 'spip_sqlite_error') {
830
-			spip_log("$s - $query - " . sql_error_backtrace(), 'sqlite.' . _LOG_ERREUR);
830
+			spip_log("$s - $query - ".sql_error_backtrace(), 'sqlite.'._LOG_ERREUR);
831 831
 		}
832 832
 	}
833 833
 
@@ -874,14 +874,14 @@  discard block
 block discarded – undo
874 874
 		$t = $link->errorInfo();
875 875
 		$s = ltrim($t[0], '0'); // 00000 si pas d'erreur
876 876
 		if ($s) {
877
-			$s .= ' / ' . $t[1];
877
+			$s .= ' / '.$t[1];
878 878
 		} // ajoute l'erreur du moteur SQLite
879 879
 	} else {
880 880
 		$s = ': aucune ressource sqlite (link)';
881 881
 	}
882 882
 
883 883
 	if ($s) {
884
-		spip_log("Erreur sqlite $s", 'sqlite.' . _LOG_ERREUR);
884
+		spip_log("Erreur sqlite $s", 'sqlite.'._LOG_ERREUR);
885 885
 	}
886 886
 
887 887
 	return $s ? $s : 0;
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
 	}
906 906
 
907 907
 	$query = spip_sqlite::traduire_requete($query, $serveur);
908
-	$query = 'EXPLAIN ' . $query;
908
+	$query = 'EXPLAIN '.$query;
909 909
 	if (!$requeter) {
910 910
 		return $query;
911 911
 	}
@@ -1074,7 +1074,7 @@  discard block
 block discarded – undo
1074 1074
  **/
1075 1075
 function spip_sqlite_insert($table, $champs, $valeurs, $desc = [], $serveur = '', $requeter = true) {
1076 1076
 
1077
-	$query = "INSERT INTO $table " . ($champs ? "$champs VALUES $valeurs" : 'DEFAULT VALUES');
1077
+	$query = "INSERT INTO $table ".($champs ? "$champs VALUES $valeurs" : 'DEFAULT VALUES');
1078 1078
 	if ($r = spip_sqlite_query($query, $serveur, $requeter)) {
1079 1079
 		if (!$requeter) {
1080 1080
 			return $r;
@@ -1129,8 +1129,8 @@  discard block
 block discarded – undo
1129 1129
 
1130 1130
 	$cles = $valeurs = '';
1131 1131
 	if (count($couples)) {
1132
-		$cles = '(' . join(',', array_keys($couples)) . ')';
1133
-		$valeurs = '(' . join(',', $couples) . ')';
1132
+		$cles = '('.join(',', array_keys($couples)).')';
1133
+		$valeurs = '('.join(',', $couples).')';
1134 1134
 	}
1135 1135
 
1136 1136
 	return spip_sqlite_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
@@ -1190,11 +1190,11 @@  discard block
 block discarded – undo
1190 1190
 
1191 1191
 		$champs = $valeurs = '';
1192 1192
 		if (count($couples)) {
1193
-			$champs = '(' . join(',', array_keys($couples)) . ')';
1194
-			$valeurs = '(' . join(',', $couples) . ')';
1195
-			$query = $query_start . "$champs VALUES $valeurs";
1193
+			$champs = '('.join(',', array_keys($couples)).')';
1194
+			$valeurs = '('.join(',', $couples).')';
1195
+			$query = $query_start."$champs VALUES $valeurs";
1196 1196
 		} else {
1197
-			$query = $query_start . 'DEFAULT VALUES';
1197
+			$query = $query_start.'DEFAULT VALUES';
1198 1198
 		}
1199 1199
 
1200 1200
 		if ($requeter) {
@@ -1326,7 +1326,7 @@  discard block
 block discarded – undo
1326 1326
  * @return string       Texte de sélection pour la requête
1327 1327
  */
1328 1328
 function spip_sqlite_multi($objet, $lang) {
1329
-	$r = 'EXTRAIRE_MULTI(' . $objet . ", '" . $lang . "') AS multi";
1329
+	$r = 'EXTRAIRE_MULTI('.$objet.", '".$lang."') AS multi";
1330 1330
 
1331 1331
 	return $r;
1332 1332
 }
@@ -1397,7 +1397,7 @@  discard block
 block discarded – undo
1397 1397
 function spip_sqlite_date_proche($champ, $interval, $unite) {
1398 1398
 	$op = (($interval <= 0) ? '>' : '<');
1399 1399
 
1400
-	return "($champ $op datetime('" . date('Y-m-d H:i:s') . "', '$interval $unite'))";
1400
+	return "($champ $op datetime('".date('Y-m-d H:i:s')."', '$interval $unite'))";
1401 1401
 }
1402 1402
 
1403 1403
 
@@ -1429,7 +1429,7 @@  discard block
 block discarded – undo
1429 1429
 				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1430 1430
 			) {
1431 1431
 				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT ''", $serveur);
1432
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1432
+				spip_log("ALTER $q", 'repair'._LOG_INFO_IMPORTANTE);
1433 1433
 			}
1434 1434
 			if (
1435 1435
 				preg_match(',^(INTEGER),i', $d)
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
 				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1440 1440
 			) {
1441 1441
 				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0'", $serveur);
1442
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1442
+				spip_log("ALTER $q", 'repair'._LOG_INFO_IMPORTANTE);
1443 1443
 			}
1444 1444
 			if (
1445 1445
 				preg_match(',^(datetime),i', $d)
@@ -1449,7 +1449,7 @@  discard block
 block discarded – undo
1449 1449
 				and (!isset($desc['key']['PRIMARY KEY']) or $desc['key']['PRIMARY KEY'] !== $c)
1450 1450
 			) {
1451 1451
 				spip_sqlite_alter($q = "TABLE $table CHANGE $c $c $d DEFAULT '0000-00-00 00:00:00'", $serveur);
1452
-				spip_log("ALTER $q", 'repair' . _LOG_INFO_IMPORTANTE);
1452
+				spip_log("ALTER $q", 'repair'._LOG_INFO_IMPORTANTE);
1453 1453
 			}
1454 1454
 		}
1455 1455
 
@@ -1500,10 +1500,10 @@  discard block
 block discarded – undo
1500 1500
 	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1501 1501
 	$couples = _sqlite_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1502 1502
 
1503
-	return spip_sqlite_query("REPLACE INTO $table (" . join(',', array_keys($couples)) . ') VALUES (' . join(
1503
+	return spip_sqlite_query("REPLACE INTO $table (".join(',', array_keys($couples)).') VALUES ('.join(
1504 1504
 		',',
1505 1505
 		$couples
1506
-	) . ')', $serveur);
1506
+	).')', $serveur);
1507 1507
 }
1508 1508
 
1509 1509
 
@@ -1589,7 +1589,7 @@  discard block
 block discarded – undo
1589 1589
 		. _sqlite_calculer_expression('WHERE', $where)
1590 1590
 		. _sqlite_calculer_expression('GROUP BY', $groupby, ',')
1591 1591
 		. _sqlite_calculer_expression('HAVING', $having)
1592
-		. ($orderby ? ("\nORDER BY " . _sqlite_calculer_order($orderby)) : '')
1592
+		. ($orderby ? ("\nORDER BY "._sqlite_calculer_order($orderby)) : '')
1593 1593
 		. ($limit ? "\nLIMIT $limit" : '');
1594 1594
 
1595 1595
 	// dans un select, on doit renvoyer la requête en cas d'erreur
@@ -1627,10 +1627,10 @@  discard block
 block discarded – undo
1627 1627
 	// interdire la creation d'une nouvelle base,
1628 1628
 	// sauf si on est dans l'installation
1629 1629
 	if (
1630
-		!is_file($f = _DIR_DB . $db . '.sqlite')
1630
+		!is_file($f = _DIR_DB.$db.'.sqlite')
1631 1631
 		&& (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)
1632 1632
 	) {
1633
-		spip_log("Il est interdit de creer la base $db", 'sqlite.' . _LOG_HS);
1633
+		spip_log("Il est interdit de creer la base $db", 'sqlite.'._LOG_HS);
1634 1634
 
1635 1635
 		return false;
1636 1636
 	}
@@ -1639,12 +1639,12 @@  discard block
 block discarded – undo
1639 1639
 	// avec les identifiants connus
1640 1640
 	$index = $serveur ? $serveur : 0;
1641 1641
 
1642
-	if ($link = spip_connect_db('', '', '', '', '@selectdb@' . $db, $serveur, '', '')) {
1642
+	if ($link = spip_connect_db('', '', '', '', '@selectdb@'.$db, $serveur, '', '')) {
1643 1643
 		if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
1644 1644
 			return $db;
1645 1645
 		}
1646 1646
 	} else {
1647
-		spip_log("Impossible de selectionner la base $db", 'sqlite.' . _LOG_HS);
1647
+		spip_log("Impossible de selectionner la base $db", 'sqlite.'._LOG_HS);
1648 1648
 
1649 1649
 		return false;
1650 1650
 	}
@@ -1695,7 +1695,7 @@  discard block
 block discarded – undo
1695 1695
 	$match = "^$match$";
1696 1696
 
1697 1697
 	return spip_sqlite_query(
1698
-		"SELECT name FROM sqlite_master WHERE type='table' AND tbl_name REGEXP " . _q($match),
1698
+		"SELECT name FROM sqlite_master WHERE type='table' AND tbl_name REGEXP "._q($match),
1699 1699
 		$serveur,
1700 1700
 		$requeter
1701 1701
 	);
@@ -1719,7 +1719,7 @@  discard block
 block discarded – undo
1719 1719
 	$r = spip_sqlite_query(
1720 1720
 		'SELECT name FROM sqlite_master WHERE'
1721 1721
 		. ' type=\'table\''
1722
-		. ' AND name=' . spip_sqlite_quote($table, 'string')
1722
+		. ' AND name='.spip_sqlite_quote($table, 'string')
1723 1723
 		. ' AND name NOT LIKE \'sqlite_%\'',
1724 1724
 		$serveur,
1725 1725
 		$requeter
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
 				// s'il y a une parenthèse fermante dans la clé
1817 1817
 				// ou dans la définition sans qu'il n'y ait une ouverture avant
1818 1818
 				if (false !== strpos($k, ')') or preg_match('/^[^\(]*\)/', $def)) {
1819
-					$fields[$k_precedent] .= ',' . $k . ' ' . $def;
1819
+					$fields[$k_precedent] .= ','.$k.' '.$def;
1820 1820
 					continue;
1821 1821
 				}
1822 1822
 
@@ -1851,13 +1851,13 @@  discard block
 block discarded – undo
1851 1851
 				. 'ORDER BY substr(type,2,1), name';
1852 1852
 			$a = spip_sqlite_query($query, $serveur, $requeter);
1853 1853
 			while ($r = spip_sqlite_fetch($a, null, $serveur)) {
1854
-				$key = str_replace($nom_table . '_', '', $r['name']); // enlever le nom de la table ajoute a l'index
1854
+				$key = str_replace($nom_table.'_', '', $r['name']); // enlever le nom de la table ajoute a l'index
1855 1855
 				$keytype = 'KEY';
1856 1856
 				if (strpos($r['sql'], 'UNIQUE INDEX') !== false) {
1857 1857
 					$keytype = 'UNIQUE KEY';
1858 1858
 				}
1859 1859
 				$colonnes = preg_replace(',.*\((.*)\).*,', '$1', $r['sql']);
1860
-				$keys[$keytype . ' ' . $key] = $colonnes;
1860
+				$keys[$keytype.' '.$key] = $colonnes;
1861 1861
 			}
1862 1862
 		}
1863 1863
 	} // c'est une vue, on liste les champs disponibles simplement
@@ -1904,7 +1904,7 @@  discard block
 block discarded – undo
1904 1904
 
1905 1905
 	$set = [];
1906 1906
 	foreach ($champs as $champ => $val) {
1907
-		$set[] = $champ . "=$val";
1907
+		$set[] = $champ."=$val";
1908 1908
 	}
1909 1909
 	if (!empty($set)) {
1910 1910
 		return spip_sqlite_query(
@@ -1957,7 +1957,7 @@  discard block
 block discarded – undo
1957 1957
 
1958 1958
 	$set = [];
1959 1959
 	foreach ($champs as $champ => $val) {
1960
-		$set[$champ] = $champ . '=' . _sqlite_calculer_cite($val, isset($fields[$champ]) ? $fields[$champ] : '');
1960
+		$set[$champ] = $champ.'='._sqlite_calculer_cite($val, isset($fields[$champ]) ? $fields[$champ] : '');
1961 1961
 	}
1962 1962
 
1963 1963
 	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
@@ -1965,7 +1965,7 @@  discard block
 block discarded – undo
1965 1965
 	$maj = _sqlite_ajouter_champs_timestamp($table, [], $desc, $serveur);
1966 1966
 	foreach ($maj as $champ => $val) {
1967 1967
 		if (!isset($set[$champ])) {
1968
-			$set[$champ] = $champ . '=' . $val;
1968
+			$set[$champ] = $champ.'='.$val;
1969 1969
 		}
1970 1970
 	}
1971 1971
 
@@ -1994,7 +1994,7 @@  discard block
 block discarded – undo
1994 1994
  */
1995 1995
 function _sqlite_init() {
1996 1996
 	if (!defined('_DIR_DB')) {
1997
-		define('_DIR_DB', _DIR_ETC . 'bases/');
1997
+		define('_DIR_DB', _DIR_ETC.'bases/');
1998 1998
 	}
1999 1999
 	if (!defined('_SQLITE_CHMOD')) {
2000 2000
 		define('_SQLITE_CHMOD', _SPIP_CHMOD);
@@ -2104,9 +2104,9 @@  discard block
 block discarded – undo
2104 2104
 	}
2105 2105
 
2106 2106
 	// echapper les ' en ''
2107
-	spip_log('Pas de methode ->quote pour echapper', 'sqlite.' . _LOG_INFO_IMPORTANTE);
2107
+	spip_log('Pas de methode ->quote pour echapper', 'sqlite.'._LOG_INFO_IMPORTANTE);
2108 2108
 
2109
-	return ("'" . str_replace("'", "''", $v) . "'");
2109
+	return ("'".str_replace("'", "''", $v)."'");
2110 2110
 }
2111 2111
 
2112 2112
 
@@ -2129,12 +2129,12 @@  discard block
 block discarded – undo
2129 2129
 	$exp = "\n$expression ";
2130 2130
 
2131 2131
 	if (!is_array($v)) {
2132
-		return $exp . $v;
2132
+		return $exp.$v;
2133 2133
 	} else {
2134 2134
 		if (strtoupper($join) === 'AND') {
2135
-			return $exp . join("\n\t$join ", array_map('_sqlite_calculer_where', $v));
2135
+			return $exp.join("\n\t$join ", array_map('_sqlite_calculer_where', $v));
2136 2136
 		} else {
2137
-			return $exp . join($join, $v);
2137
+			return $exp.join($join, $v);
2138 2138
 		}
2139 2139
 	}
2140 2140
 }
@@ -2168,17 +2168,17 @@  discard block
 block discarded – undo
2168 2168
 		if (substr($k, -1) == '@') {
2169 2169
 			// c'est une jointure qui se refere au from precedent
2170 2170
 			// pas de virgule
2171
-			$res .= '  ' . $v;
2171
+			$res .= '  '.$v;
2172 2172
 		} else {
2173 2173
 			if (!is_numeric($k)) {
2174 2174
 				$p = strpos($v, ' ');
2175 2175
 				if ($p) {
2176
-					$v = substr($v, 0, $p) . " AS '$k'" . substr($v, $p);
2176
+					$v = substr($v, 0, $p)." AS '$k'".substr($v, $p);
2177 2177
 				} else {
2178 2178
 					$v .= " AS '$k'";
2179 2179
 				}
2180 2180
 			}
2181
-			$res .= ', ' . $v;
2181
+			$res .= ', '.$v;
2182 2182
 		}
2183 2183
 	}
2184 2184
 
@@ -2316,13 +2316,13 @@  discard block
 block discarded – undo
2316 2316
 
2317 2317
 	$def_origine = sql_showtable($table_origine, false, $serveur);
2318 2318
 	if (!$def_origine or !isset($def_origine['field'])) {
2319
-		spip_log("Alter table impossible sur $table_origine : table non trouvee", 'sqlite' . _LOG_ERREUR);
2319
+		spip_log("Alter table impossible sur $table_origine : table non trouvee", 'sqlite'._LOG_ERREUR);
2320 2320
 
2321 2321
 		return false;
2322 2322
 	}
2323 2323
 
2324 2324
 
2325
-	$table_tmp = $table_origine . '_tmp';
2325
+	$table_tmp = $table_origine.'_tmp';
2326 2326
 
2327 2327
 	// 1) creer une table temporaire avec les modifications
2328 2328
 	// - DROP : suppression de la colonne
@@ -2409,7 +2409,7 @@  discard block
 block discarded – undo
2409 2409
 		} else {
2410 2410
 			// enlever KEY
2411 2411
 			$k = substr($k, 4);
2412
-			$queries[] = "CREATE INDEX $table_destination" . "_$k ON $table_destination ($v)";
2412
+			$queries[] = "CREATE INDEX $table_destination"."_$k ON $table_destination ($v)";
2413 2413
 		}
2414 2414
 	}
2415 2415
 
@@ -2420,7 +2420,7 @@  discard block
 block discarded – undo
2420 2420
 		foreach ($queries as $q) {
2421 2421
 			if (!spip_sqlite::executer_requete($q, $serveur)) {
2422 2422
 				spip_log('SQLite : ALTER TABLE table :'
2423
-					. " Erreur a l'execution de la requete : $q", 'sqlite.' . _LOG_ERREUR);
2423
+					. " Erreur a l'execution de la requete : $q", 'sqlite.'._LOG_ERREUR);
2424 2424
 				spip_sqlite::annuler_transaction($serveur);
2425 2425
 
2426 2426
 				return false;
@@ -2510,27 +2510,27 @@  discard block
 block discarded – undo
2510 2510
 	$enum = '(\s*\([^\)]*\))?';
2511 2511
 
2512 2512
 	$remplace = [
2513
-		'/enum' . $enum . '/is' => 'VARCHAR(255)',
2513
+		'/enum'.$enum.'/is' => 'VARCHAR(255)',
2514 2514
 		'/COLLATE \w+_bin/is' => 'COLLATE BINARY',
2515 2515
 		'/COLLATE \w+_ci/is' => 'COLLATE NOCASE',
2516 2516
 		'/auto_increment/is' => '',
2517 2517
 		'/current_timestamp\(\)/is' => 'CURRENT_TIMESTAMP', // Fix export depuis mariaDB #4374
2518 2518
 		'/(timestamp .* )ON .*$/is' => '\\1',
2519 2519
 		'/character set \w+/is' => '',
2520
-		'/((big|small|medium|tiny)?int(eger)?)' . $num . '\s*unsigned/is' => '\\1 UNSIGNED',
2520
+		'/((big|small|medium|tiny)?int(eger)?)'.$num.'\s*unsigned/is' => '\\1 UNSIGNED',
2521 2521
 		'/(text\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2522
-		'/((char|varchar)' . $num . '\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2522
+		'/((char|varchar)'.$num.'\s+not\s+null(\s+collate\s+\w+)?)\s*$/is' => "\\1 DEFAULT ''",
2523 2523
 		'/(datetime\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00 00:00:00'",
2524 2524
 		'/(date\s+not\s+null)\s*$/is' => "\\1 DEFAULT '0000-00-00'",
2525 2525
 	];
2526 2526
 
2527 2527
 	// pour l'autoincrement, il faut des INTEGER NOT NULL PRIMARY KEY
2528 2528
 	$remplace_autocinc = [
2529
-		'/(big|small|medium|tiny)?int(eger)?' . $num . '/is' => 'INTEGER'
2529
+		'/(big|small|medium|tiny)?int(eger)?'.$num.'/is' => 'INTEGER'
2530 2530
 	];
2531 2531
 	// pour les int non autoincrement, il faut un DEFAULT
2532 2532
 	$remplace_nonautocinc = [
2533
-		'/((big|small|medium|tiny)?int(eger)?' . $num . '\s+not\s+null)\s*$/is' => "\\1 DEFAULT 0",
2533
+		'/((big|small|medium|tiny)?int(eger)?'.$num.'\s+not\s+null)\s*$/is' => "\\1 DEFAULT 0",
2534 2534
 	];
2535 2535
 
2536 2536
 	if (is_string($query)) {
@@ -2572,7 +2572,7 @@  discard block
 block discarded – undo
2572 2572
 		return str_ireplace('BINARY', 'COLLATE BINARY', $champ);
2573 2573
 	}
2574 2574
 	if (preg_match(',^(char|varchar|(long|small|medium|tiny)?text),i', $champ)) {
2575
-		return $champ . ' COLLATE NOCASE';
2575
+		return $champ.' COLLATE NOCASE';
2576 2576
 	}
2577 2577
 
2578 2578
 	return $champ;
@@ -2662,14 +2662,14 @@  discard block
 block discarded – undo
2662 2662
 		} else {
2663 2663
 			/* simuler le IF EXISTS - version 2 et sqlite < 3.3a */
2664 2664
 			$a = spip_sqlite_showtable($nom, $serveur);
2665
-			if (isset($a['key']['KEY ' . $nom])) {
2665
+			if (isset($a['key']['KEY '.$nom])) {
2666 2666
 				return true;
2667 2667
 			}
2668 2668
 		}
2669 2669
 	}
2670 2670
 
2671 2671
 	$temporary = $temporary ? ' TEMPORARY' : '';
2672
-	$q = "CREATE$temporary TABLE$ifnotexists $nom ($query" . ($keys ? ",$keys" : '') . ")\n";
2672
+	$q = "CREATE$temporary TABLE$ifnotexists $nom ($query".($keys ? ",$keys" : '').")\n";
2673 2673
 
2674 2674
 	return $q;
2675 2675
 }
@@ -2890,7 +2890,7 @@  discard block
 block discarded – undo
2890 2890
 		$this->serveur = strtolower($serveur);
2891 2891
 
2892 2892
 		if (!($this->link = _sqlite_link($this->serveur)) && (!defined('_ECRIRE_INSTALL') || !_ECRIRE_INSTALL)) {
2893
-			spip_log('Aucune connexion sqlite (link)', 'sqlite.' . _LOG_ERREUR);
2893
+			spip_log('Aucune connexion sqlite (link)', 'sqlite.'._LOG_ERREUR);
2894 2894
 
2895 2895
 			return false;
2896 2896
 		}
@@ -2936,7 +2936,7 @@  discard block
 block discarded – undo
2936 2936
 			try {
2937 2937
 				$r = $this->link->query($query);
2938 2938
 			} catch (\PDOException $e) {
2939
-				spip_log('PDOException: ' . $e->getMessage(), 'sqlite.' . _LOG_DEBUG);
2939
+				spip_log('PDOException: '.$e->getMessage(), 'sqlite.'._LOG_DEBUG);
2940 2940
 				$r = false;
2941 2941
 			}
2942 2942
 
@@ -2951,11 +2951,11 @@  discard block
 block discarded – undo
2951 2951
 
2952 2952
 			// loger les warnings/erreurs eventuels de sqlite remontant dans PHP
2953 2953
 			if ($e and $e instanceof \PDOException) {
2954
-				$err = strip_tags($e->getMessage()) . ' in ' . $e->getFile() . ' line ' . $e->getLine();
2955
-				spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2954
+				$err = strip_tags($e->getMessage()).' in '.$e->getFile().' line '.$e->getLine();
2955
+				spip_log("$err - ".$query, 'sqlite.'._LOG_ERREUR);
2956 2956
 			} elseif ($err = (function_exists('error_get_last') ? error_get_last() : '') and $err != $last_error) {
2957
-				$err = strip_tags($err['message']) . ' in ' . $err['file'] . ' line ' . $err['line'];
2958
-				spip_log("$err - " . $query, 'sqlite.' . _LOG_ERREUR);
2957
+				$err = strip_tags($err['message']).' in '.$err['file'].' line '.$err['line'];
2958
+				spip_log("$err - ".$query, 'sqlite.'._LOG_ERREUR);
2959 2959
 			} else {
2960 2960
 				$err = '';
2961 2961
 			}
@@ -3033,15 +3033,15 @@  discard block
 block discarded – undo
3033 3033
 		// Correction Create Database
3034 3034
 		// Create Database -> requete ignoree
3035 3035
 		if (strpos($this->query, 'CREATE DATABASE') === 0) {
3036
-			spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.' . _LOG_AVERTISSEMENT);
3036
+			spip_log("Sqlite : requete non executee -> $this->query", 'sqlite.'._LOG_AVERTISSEMENT);
3037 3037
 			$this->query = 'SELECT 1';
3038 3038
 		}
3039 3039
 
3040 3040
 		// Correction Insert Ignore
3041 3041
 		// INSERT IGNORE -> insert (tout court et pas 'insert or replace')
3042 3042
 		if (strpos($this->query, 'INSERT IGNORE') === 0) {
3043
-			spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.' . _LOG_DEBUG);
3044
-			$this->query = 'INSERT ' . substr($this->query, '13');
3043
+			spip_log("Sqlite : requete transformee -> $this->query", 'sqlite.'._LOG_DEBUG);
3044
+			$this->query = 'INSERT '.substr($this->query, '13');
3045 3045
 		}
3046 3046
 
3047 3047
 		// Correction des dates avec INTERVAL
@@ -3069,7 +3069,7 @@  discard block
 block discarded – undo
3069 3069
 		if (($this->sqlite_version == 2) && (strpos($this->query, 'USING') !== false)) {
3070 3070
 			spip_log(
3071 3071
 				"'USING (champ)' n'est pas reconnu en SQLite 2. Utilisez 'ON table1.champ = table2.champ'",
3072
-				'sqlite.' . _LOG_ERREUR
3072
+				'sqlite.'._LOG_ERREUR
3073 3073
 			);
3074 3074
 			$this->query = preg_replace('/USING\s*\([^\)]*\)/', '', $this->query);
3075 3075
 		}
@@ -3092,8 +3092,8 @@  discard block
 block discarded – undo
3092 3092
 		} else {
3093 3093
 			$suite = '';
3094 3094
 		}
3095
-		$pref = ($this->prefixe) ? $this->prefixe . '_' : '';
3096
-		$this->query = preg_replace('/([,\s])spip_/S', '\1' . $pref, $this->query) . $suite;
3095
+		$pref = ($this->prefixe) ? $this->prefixe.'_' : '';
3096
+		$this->query = preg_replace('/([,\s])spip_/S', '\1'.$pref, $this->query).$suite;
3097 3097
 
3098 3098
 		// Correction zero AS x
3099 3099
 		// pg n'aime pas 0+x AS alias, sqlite, dans le meme style,
Please login to merge, or discard this patch.