Completed
Push — master ( a56a38...81a660 )
by cam
01:36
created
ecrire/src/Compilateur/Iterateur/Data.php 2 patches
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -12,486 +12,486 @@
 block discarded – undo
12 12
  */
13 13
 class Data extends AbstractIterateur implements Iterator
14 14
 {
15
-	/** Tableau de données */
16
-	protected array $tableau = [];
17
-
18
-	/**
19
-	 * Conditions de filtrage
20
-	 * ie criteres de selection
21
-	 */
22
-	protected array $filtre = [];
23
-
24
-	/**
25
-	 * Cle courante
26
-	 *
27
-	 * @var scalar
28
-	 */
29
-	protected $cle = null;
30
-
31
-	/**
32
-	 * Valeur courante
33
-	 *
34
-	 * @var mixed
35
-	 */
36
-	protected $valeur = null;
37
-
38
-	/**
39
-	 * Constructeur
40
-	 *
41
-	 * @param  $command
42
-	 * @param array $info
43
-	 */
44
-	public function __construct(array $command, array $info = []) {
45
-		include_spip('iterateur/data');
46
-		$this->type = 'DATA';
47
-		$this->command = $command;
48
-		$this->info = $info;
49
-		$this->select($command);
50
-	}
51
-
52
-	/**
53
-	 * Revenir au depart
54
-	 *
55
-	 * @return void
56
-	 */
57
-	public function rewind(): void {
58
-		reset($this->tableau);
59
-		$this->cle = array_key_first($this->tableau);
60
-		$this->valeur = current($this->tableau);
61
-		next($this->tableau);
62
-	}
63
-
64
-	/**
65
-	 * Déclarer les critères exceptions
66
-	 *
67
-	 * @return array
68
-	 */
69
-	public function exception_des_criteres() {
70
-		return ['tableau'];
71
-	}
72
-
73
-	/**
74
-	 * Récupérer depuis le cache si possible
75
-	 *
76
-	 * @param string $cle
77
-	 * @return mixed
78
-	 */
79
-	protected function cache_get($cle) {
80
-		if (!$cle) {
81
-			return;
82
-		}
83
-		# utiliser memoization si dispo
84
-		if (!function_exists('cache_get')) {
85
-			return;
86
-		}
87
-
88
-		return cache_get($cle);
89
-	}
90
-
91
-	/**
92
-	 * Stocker en cache si possible
93
-	 *
94
-	 * @param string $cle
95
-	 * @param int $ttl
96
-	 * @param null|mixed $valeur
97
-	 * @return bool
98
-	 */
99
-	protected function cache_set($cle, $ttl, $valeur = null) {
100
-		if (!$cle) {
101
-			return;
102
-		}
103
-		if (is_null($valeur)) {
104
-			$valeur = $this->tableau;
105
-		}
106
-		# utiliser memoization si dispo
107
-		if (!function_exists('cache_set')) {
108
-			return;
109
-		}
110
-
111
-		return cache_set(
112
-			$cle,
113
-			[
114
-				'data' => $valeur,
115
-				'time' => time(),
116
-				'ttl' => $ttl
117
-			],
118
-			3600 + $ttl
119
-		);
120
-		# conserver le cache 1h de plus que la validite demandee,
121
-		# pour le cas ou le serveur distant ne reponde plus
122
-	}
123
-
124
-	/**
125
-	 * Aller chercher les données de la boucle DATA
126
-	 *
127
-	 * @throws Exception
128
-	 * @param array $command
129
-	 * @return void
130
-	 */
131
-	protected function select($command) {
132
-
133
-		// l'iterateur DATA peut etre appele en passant (data:type)
134
-		// le type se retrouve dans la commande 'from'
135
-		// dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
136
-		if (isset($this->command['from'][0])) {
137
-			if (isset($this->command['source']) && is_array($this->command['source'])) {
138
-				array_unshift($this->command['source'], $this->command['sourcemode']);
139
-			}
140
-			$this->command['sourcemode'] = $this->command['from'][0];
141
-		}
142
-
143
-		// cherchons differents moyens de creer le tableau de donnees
144
-		// les commandes connues pour l'iterateur DATA
145
-		// sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
146
-
147
-		// {source format, [URL], [arg2]...}
148
-		if (
149
-			isset($this->command['source'])
150
-			&& isset($this->command['sourcemode'])
151
-		) {
152
-			$this->select_source();
153
-		}
154
-
155
-		// Critere {liste X1, X2, X3}
156
-		if (isset($this->command['liste'])) {
157
-			$this->select_liste();
158
-		}
159
-		if (isset($this->command['enum'])) {
160
-			$this->select_enum();
161
-		}
162
-
163
-		// Si a ce stade on n'a pas de table, il y a un bug
164
-		if (!is_array($this->tableau)) {
165
-			$this->err = true;
166
-			spip_log('erreur datasource ' . var_export($command, true));
167
-		}
168
-
169
-		// {datapath query.results}
170
-		// extraire le chemin "query.results" du tableau de donnees
171
-		if (
172
-			!$this->err
173
-			&& isset($this->command['datapath'])
174
-			&& is_array($this->command['datapath'])
175
-		) {
176
-			$this->select_datapath();
177
-		}
178
-
179
-		// tri {par x}
180
-		if ($this->command['orderby']) {
181
-			$this->select_orderby();
182
-		}
183
-
184
-		// grouper les resultats {fusion /x/y/z} ;
185
-		if ($this->command['groupby']) {
186
-			$this->select_groupby();
187
-		}
188
-
189
-		$this->rewind();
190
-		#var_dump($this->tableau);
191
-	}
192
-
193
-
194
-	/**
195
-	 * Aller chercher les donnees de la boucle DATA
196
-	 * depuis une source
197
-	 * {source format, [URL], [arg2]...}
198
-	 */
199
-	protected function select_source() {
200
-		# un peu crado : avant de charger le cache il faut charger
201
-		# les class indispensables, sinon PHP ne saura pas gerer
202
-		# l'objet en cache ; cf plugins/icalendar
203
-		# perf : pas de fonction table_to_array ! (table est deja un array)
204
-		if (
205
-			isset($this->command['sourcemode'])
206
-			&& !in_array($this->command['sourcemode'], ['table', 'array', 'tableau'])
207
-		) {
208
-			charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
209
-		}
210
-
211
-		# le premier argument peut etre un array, une URL etc.
212
-		$src = $this->command['source'][0] ?? null;
213
-
214
-		# avons-nous un cache dispo ?
215
-		$cle = null;
216
-		if (is_string($src)) {
217
-			$cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
218
-		}
219
-
220
-		$cache = $this->cache_get($cle);
221
-		if (isset($this->command['datacache'])) {
222
-			$ttl = (int) $this->command['datacache'];
223
-		}
224
-		if (
225
-			$cache
226
-			&& $cache['time'] + ($ttl ?? $cache['ttl']) > time()
227
-			&& !(_request('var_mode') === 'recalcul' && include_spip('inc/autoriser') && autoriser('recalcul'))
228
-		) {
229
-			$this->tableau = $cache['data'];
230
-		} else {
231
-			try {
232
-				if (
233
-					isset($this->command['sourcemode'])
234
-					&& in_array(
235
-						$this->command['sourcemode'],
236
-						['table', 'array', 'tableau']
237
-					)
238
-				) {
239
-					if (
240
-						is_array($a = $src)
241
-						|| is_string($a) && ($a = str_replace('"', '"', $a)) && is_array($a = @unserialize($a))
242
-					) {
243
-						$this->tableau = $a;
244
-					}
245
-				} else {
246
-					$data = $src;
247
-					if (is_string($src)) {
248
-						if (tester_url_absolue($src)) {
249
-							include_spip('inc/distant');
250
-							$data = recuperer_url($src, ['taille_max' => _DATA_SOURCE_MAX_SIZE]);
251
-							$data = $data['page'] ?? '';
252
-							if (!$data) {
253
-								throw new Exception('404');
254
-							}
255
-							if (!isset($ttl)) {
256
-								$ttl = 24 * 3600;
257
-							}
258
-						} elseif (@is_dir($src)) {
259
-							$data = $src;
260
-						} elseif (@is_readable($src) && @is_file($src)) {
261
-							$data = spip_file_get_contents($src);
262
-						}
263
-						if (!isset($ttl)) {
264
-							$ttl = 10;
265
-						}
266
-					}
267
-					if (
268
-						!$this->err
269
-						&& ($data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true))
270
-					) {
271
-						$args = $this->command['source'];
272
-						$args[0] = $data;
273
-						if (is_array($a = $data_to_array(...$args))) {
274
-							$this->tableau = $a;
275
-						}
276
-					}
277
-				}
278
-
279
-				if (!is_array($this->tableau)) {
280
-					$this->err = true;
281
-				}
282
-
283
-				if (!$this->err && isset($ttl) && $ttl > 0) {
284
-					$this->cache_set($cle, $ttl);
285
-				}
286
-			} catch (Exception $e) {
287
-				$e = $e->getMessage();
288
-				$err = sprintf(
289
-					"[%s, %s] $e",
290
-					$src,
291
-					$this->command['sourcemode']
292
-				);
293
-				erreur_squelette([$err, []]);
294
-				$this->err = true;
295
-			}
296
-		}
297
-
298
-		# en cas d'erreur, utiliser le cache si encore dispo
299
-		if ($this->err && $cache) {
300
-			$this->tableau = $cache['data'];
301
-			$this->err = false;
302
-		}
303
-	}
304
-
305
-
306
-	/**
307
-	 * Retourne un tableau donne depuis un critère liste
308
-	 *
309
-	 * Critère `{liste X1, X2, X3}`
310
-	 *
311
-	 * @see critere_DATA_liste_dist()
312
-	 *
313
-	 **/
314
-	protected function select_liste() {
315
-		# s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
316
-		if (!isset($this->command['liste'][1])) {
317
-			if (!is_array($this->command['liste'][0])) {
318
-				$this->command['liste'] = explode(',', $this->command['liste'][0]);
319
-			} else {
320
-				$this->command['liste'] = $this->command['liste'][0];
321
-			}
322
-		}
323
-		$this->tableau = $this->command['liste'];
324
-	}
325
-
326
-	/**
327
-	 * Retourne un tableau donne depuis un critere liste
328
-	 * Critere {enum Xmin, Xmax}
329
-	 *
330
-	 **/
331
-	protected function select_enum() {
332
-		# s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
333
-		if (!isset($this->command['enum'][1])) {
334
-			if (!is_array($this->command['enum'][0])) {
335
-				$this->command['enum'] = explode(',', $this->command['enum'][0]);
336
-			} else {
337
-				$this->command['enum'] = $this->command['enum'][0];
338
-			}
339
-		}
340
-		if ((is_countable($this->command['enum']) ? count($this->command['enum']) : 0) >= 3) {
341
-			$enum = range(
342
-				array_shift($this->command['enum']),
343
-				array_shift($this->command['enum']),
344
-				array_shift($this->command['enum'])
345
-			);
346
-		} else {
347
-			$enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']));
348
-		}
349
-		$this->tableau = $enum;
350
-	}
351
-
352
-
353
-	/**
354
-	 * extraire le chemin "query.results" du tableau de donnees
355
-	 * {datapath query.results}
356
-	 *
357
-	 **/
358
-	protected function select_datapath() {
359
-		$base = reset($this->command['datapath']);
360
-		if (strlen($base = ltrim(trim($base), '/'))) {
361
-			$results = table_valeur($this->tableau, $base);
362
-			if (is_array($results)) {
363
-				$this->tableau = $results;
364
-			} else {
365
-				$this->tableau = [];
366
-				$this->err = true;
367
-				spip_log("datapath '$base' absent");
368
-			}
369
-		}
370
-	}
371
-
372
-	/**
373
-	 * Ordonner les resultats
374
-	 * {par x}
375
-	 *
376
-	 **/
377
-	protected function select_orderby() {
378
-		$sortfunc = '';
379
-		$aleas = 0;
380
-		foreach ($this->command['orderby'] as $tri) {
381
-			// virer le / initial pour les criteres de la forme {par /xx}
382
-			if (preg_match(',^\.?([/\w:_-]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
383
-				$r = array_pad($r, 3, null);
384
-
385
-				// tri par cle
386
-				if ($r[1] == 'cle') {
387
-					if (isset($r[2]) && $r[2]) {
388
-						krsort($this->tableau);
389
-					} else {
390
-						ksort($this->tableau);
391
-					}
392
-				} # {par hasard}
393
-				else {
394
-					if ($r[1] == 'hasard') {
395
-						$k = array_keys($this->tableau);
396
-						shuffle($k);
397
-						$v = [];
398
-						foreach ($k as $cle) {
399
-							$v[$cle] = $this->tableau[$cle];
400
-						}
401
-						$this->tableau = $v;
402
-					} else {
403
-						# {par valeur} ou {par valeur/xx/yy}
404
-						$tv = $r[1] == 'valeur' ? '%s' : 'table_valeur(%s, ' . var_export($r[1], true) . ')';
405
-						$sortfunc .= '
15
+    /** Tableau de données */
16
+    protected array $tableau = [];
17
+
18
+    /**
19
+     * Conditions de filtrage
20
+     * ie criteres de selection
21
+     */
22
+    protected array $filtre = [];
23
+
24
+    /**
25
+     * Cle courante
26
+     *
27
+     * @var scalar
28
+     */
29
+    protected $cle = null;
30
+
31
+    /**
32
+     * Valeur courante
33
+     *
34
+     * @var mixed
35
+     */
36
+    protected $valeur = null;
37
+
38
+    /**
39
+     * Constructeur
40
+     *
41
+     * @param  $command
42
+     * @param array $info
43
+     */
44
+    public function __construct(array $command, array $info = []) {
45
+        include_spip('iterateur/data');
46
+        $this->type = 'DATA';
47
+        $this->command = $command;
48
+        $this->info = $info;
49
+        $this->select($command);
50
+    }
51
+
52
+    /**
53
+     * Revenir au depart
54
+     *
55
+     * @return void
56
+     */
57
+    public function rewind(): void {
58
+        reset($this->tableau);
59
+        $this->cle = array_key_first($this->tableau);
60
+        $this->valeur = current($this->tableau);
61
+        next($this->tableau);
62
+    }
63
+
64
+    /**
65
+     * Déclarer les critères exceptions
66
+     *
67
+     * @return array
68
+     */
69
+    public function exception_des_criteres() {
70
+        return ['tableau'];
71
+    }
72
+
73
+    /**
74
+     * Récupérer depuis le cache si possible
75
+     *
76
+     * @param string $cle
77
+     * @return mixed
78
+     */
79
+    protected function cache_get($cle) {
80
+        if (!$cle) {
81
+            return;
82
+        }
83
+        # utiliser memoization si dispo
84
+        if (!function_exists('cache_get')) {
85
+            return;
86
+        }
87
+
88
+        return cache_get($cle);
89
+    }
90
+
91
+    /**
92
+     * Stocker en cache si possible
93
+     *
94
+     * @param string $cle
95
+     * @param int $ttl
96
+     * @param null|mixed $valeur
97
+     * @return bool
98
+     */
99
+    protected function cache_set($cle, $ttl, $valeur = null) {
100
+        if (!$cle) {
101
+            return;
102
+        }
103
+        if (is_null($valeur)) {
104
+            $valeur = $this->tableau;
105
+        }
106
+        # utiliser memoization si dispo
107
+        if (!function_exists('cache_set')) {
108
+            return;
109
+        }
110
+
111
+        return cache_set(
112
+            $cle,
113
+            [
114
+                'data' => $valeur,
115
+                'time' => time(),
116
+                'ttl' => $ttl
117
+            ],
118
+            3600 + $ttl
119
+        );
120
+        # conserver le cache 1h de plus que la validite demandee,
121
+        # pour le cas ou le serveur distant ne reponde plus
122
+    }
123
+
124
+    /**
125
+     * Aller chercher les données de la boucle DATA
126
+     *
127
+     * @throws Exception
128
+     * @param array $command
129
+     * @return void
130
+     */
131
+    protected function select($command) {
132
+
133
+        // l'iterateur DATA peut etre appele en passant (data:type)
134
+        // le type se retrouve dans la commande 'from'
135
+        // dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
136
+        if (isset($this->command['from'][0])) {
137
+            if (isset($this->command['source']) && is_array($this->command['source'])) {
138
+                array_unshift($this->command['source'], $this->command['sourcemode']);
139
+            }
140
+            $this->command['sourcemode'] = $this->command['from'][0];
141
+        }
142
+
143
+        // cherchons differents moyens de creer le tableau de donnees
144
+        // les commandes connues pour l'iterateur DATA
145
+        // sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
146
+
147
+        // {source format, [URL], [arg2]...}
148
+        if (
149
+            isset($this->command['source'])
150
+            && isset($this->command['sourcemode'])
151
+        ) {
152
+            $this->select_source();
153
+        }
154
+
155
+        // Critere {liste X1, X2, X3}
156
+        if (isset($this->command['liste'])) {
157
+            $this->select_liste();
158
+        }
159
+        if (isset($this->command['enum'])) {
160
+            $this->select_enum();
161
+        }
162
+
163
+        // Si a ce stade on n'a pas de table, il y a un bug
164
+        if (!is_array($this->tableau)) {
165
+            $this->err = true;
166
+            spip_log('erreur datasource ' . var_export($command, true));
167
+        }
168
+
169
+        // {datapath query.results}
170
+        // extraire le chemin "query.results" du tableau de donnees
171
+        if (
172
+            !$this->err
173
+            && isset($this->command['datapath'])
174
+            && is_array($this->command['datapath'])
175
+        ) {
176
+            $this->select_datapath();
177
+        }
178
+
179
+        // tri {par x}
180
+        if ($this->command['orderby']) {
181
+            $this->select_orderby();
182
+        }
183
+
184
+        // grouper les resultats {fusion /x/y/z} ;
185
+        if ($this->command['groupby']) {
186
+            $this->select_groupby();
187
+        }
188
+
189
+        $this->rewind();
190
+        #var_dump($this->tableau);
191
+    }
192
+
193
+
194
+    /**
195
+     * Aller chercher les donnees de la boucle DATA
196
+     * depuis une source
197
+     * {source format, [URL], [arg2]...}
198
+     */
199
+    protected function select_source() {
200
+        # un peu crado : avant de charger le cache il faut charger
201
+        # les class indispensables, sinon PHP ne saura pas gerer
202
+        # l'objet en cache ; cf plugins/icalendar
203
+        # perf : pas de fonction table_to_array ! (table est deja un array)
204
+        if (
205
+            isset($this->command['sourcemode'])
206
+            && !in_array($this->command['sourcemode'], ['table', 'array', 'tableau'])
207
+        ) {
208
+            charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
209
+        }
210
+
211
+        # le premier argument peut etre un array, une URL etc.
212
+        $src = $this->command['source'][0] ?? null;
213
+
214
+        # avons-nous un cache dispo ?
215
+        $cle = null;
216
+        if (is_string($src)) {
217
+            $cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
218
+        }
219
+
220
+        $cache = $this->cache_get($cle);
221
+        if (isset($this->command['datacache'])) {
222
+            $ttl = (int) $this->command['datacache'];
223
+        }
224
+        if (
225
+            $cache
226
+            && $cache['time'] + ($ttl ?? $cache['ttl']) > time()
227
+            && !(_request('var_mode') === 'recalcul' && include_spip('inc/autoriser') && autoriser('recalcul'))
228
+        ) {
229
+            $this->tableau = $cache['data'];
230
+        } else {
231
+            try {
232
+                if (
233
+                    isset($this->command['sourcemode'])
234
+                    && in_array(
235
+                        $this->command['sourcemode'],
236
+                        ['table', 'array', 'tableau']
237
+                    )
238
+                ) {
239
+                    if (
240
+                        is_array($a = $src)
241
+                        || is_string($a) && ($a = str_replace('"', '"', $a)) && is_array($a = @unserialize($a))
242
+                    ) {
243
+                        $this->tableau = $a;
244
+                    }
245
+                } else {
246
+                    $data = $src;
247
+                    if (is_string($src)) {
248
+                        if (tester_url_absolue($src)) {
249
+                            include_spip('inc/distant');
250
+                            $data = recuperer_url($src, ['taille_max' => _DATA_SOURCE_MAX_SIZE]);
251
+                            $data = $data['page'] ?? '';
252
+                            if (!$data) {
253
+                                throw new Exception('404');
254
+                            }
255
+                            if (!isset($ttl)) {
256
+                                $ttl = 24 * 3600;
257
+                            }
258
+                        } elseif (@is_dir($src)) {
259
+                            $data = $src;
260
+                        } elseif (@is_readable($src) && @is_file($src)) {
261
+                            $data = spip_file_get_contents($src);
262
+                        }
263
+                        if (!isset($ttl)) {
264
+                            $ttl = 10;
265
+                        }
266
+                    }
267
+                    if (
268
+                        !$this->err
269
+                        && ($data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true))
270
+                    ) {
271
+                        $args = $this->command['source'];
272
+                        $args[0] = $data;
273
+                        if (is_array($a = $data_to_array(...$args))) {
274
+                            $this->tableau = $a;
275
+                        }
276
+                    }
277
+                }
278
+
279
+                if (!is_array($this->tableau)) {
280
+                    $this->err = true;
281
+                }
282
+
283
+                if (!$this->err && isset($ttl) && $ttl > 0) {
284
+                    $this->cache_set($cle, $ttl);
285
+                }
286
+            } catch (Exception $e) {
287
+                $e = $e->getMessage();
288
+                $err = sprintf(
289
+                    "[%s, %s] $e",
290
+                    $src,
291
+                    $this->command['sourcemode']
292
+                );
293
+                erreur_squelette([$err, []]);
294
+                $this->err = true;
295
+            }
296
+        }
297
+
298
+        # en cas d'erreur, utiliser le cache si encore dispo
299
+        if ($this->err && $cache) {
300
+            $this->tableau = $cache['data'];
301
+            $this->err = false;
302
+        }
303
+    }
304
+
305
+
306
+    /**
307
+     * Retourne un tableau donne depuis un critère liste
308
+     *
309
+     * Critère `{liste X1, X2, X3}`
310
+     *
311
+     * @see critere_DATA_liste_dist()
312
+     *
313
+     **/
314
+    protected function select_liste() {
315
+        # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
316
+        if (!isset($this->command['liste'][1])) {
317
+            if (!is_array($this->command['liste'][0])) {
318
+                $this->command['liste'] = explode(',', $this->command['liste'][0]);
319
+            } else {
320
+                $this->command['liste'] = $this->command['liste'][0];
321
+            }
322
+        }
323
+        $this->tableau = $this->command['liste'];
324
+    }
325
+
326
+    /**
327
+     * Retourne un tableau donne depuis un critere liste
328
+     * Critere {enum Xmin, Xmax}
329
+     *
330
+     **/
331
+    protected function select_enum() {
332
+        # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
333
+        if (!isset($this->command['enum'][1])) {
334
+            if (!is_array($this->command['enum'][0])) {
335
+                $this->command['enum'] = explode(',', $this->command['enum'][0]);
336
+            } else {
337
+                $this->command['enum'] = $this->command['enum'][0];
338
+            }
339
+        }
340
+        if ((is_countable($this->command['enum']) ? count($this->command['enum']) : 0) >= 3) {
341
+            $enum = range(
342
+                array_shift($this->command['enum']),
343
+                array_shift($this->command['enum']),
344
+                array_shift($this->command['enum'])
345
+            );
346
+        } else {
347
+            $enum = range(array_shift($this->command['enum']), array_shift($this->command['enum']));
348
+        }
349
+        $this->tableau = $enum;
350
+    }
351
+
352
+
353
+    /**
354
+     * extraire le chemin "query.results" du tableau de donnees
355
+     * {datapath query.results}
356
+     *
357
+     **/
358
+    protected function select_datapath() {
359
+        $base = reset($this->command['datapath']);
360
+        if (strlen($base = ltrim(trim($base), '/'))) {
361
+            $results = table_valeur($this->tableau, $base);
362
+            if (is_array($results)) {
363
+                $this->tableau = $results;
364
+            } else {
365
+                $this->tableau = [];
366
+                $this->err = true;
367
+                spip_log("datapath '$base' absent");
368
+            }
369
+        }
370
+    }
371
+
372
+    /**
373
+     * Ordonner les resultats
374
+     * {par x}
375
+     *
376
+     **/
377
+    protected function select_orderby() {
378
+        $sortfunc = '';
379
+        $aleas = 0;
380
+        foreach ($this->command['orderby'] as $tri) {
381
+            // virer le / initial pour les criteres de la forme {par /xx}
382
+            if (preg_match(',^\.?([/\w:_-]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
383
+                $r = array_pad($r, 3, null);
384
+
385
+                // tri par cle
386
+                if ($r[1] == 'cle') {
387
+                    if (isset($r[2]) && $r[2]) {
388
+                        krsort($this->tableau);
389
+                    } else {
390
+                        ksort($this->tableau);
391
+                    }
392
+                } # {par hasard}
393
+                else {
394
+                    if ($r[1] == 'hasard') {
395
+                        $k = array_keys($this->tableau);
396
+                        shuffle($k);
397
+                        $v = [];
398
+                        foreach ($k as $cle) {
399
+                            $v[$cle] = $this->tableau[$cle];
400
+                        }
401
+                        $this->tableau = $v;
402
+                    } else {
403
+                        # {par valeur} ou {par valeur/xx/yy}
404
+                        $tv = $r[1] == 'valeur' ? '%s' : 'table_valeur(%s, ' . var_export($r[1], true) . ')';
405
+                        $sortfunc .= '
406 406
 					$a = ' . sprintf($tv, '$aa') . ';
407 407
 					$b = ' . sprintf($tv, '$bb') . ';
408 408
 					if ($a <> $b)
409 409
 						return ($a ' . (empty($r[2]) ? '<' : '>') . ' $b) ? -1 : 1;';
410
-					}
411
-				}
412
-			}
413
-		}
414
-
415
-		if ($sortfunc) {
416
-			$sortfunc .= "\n return 0;";
417
-			uasort($this->tableau, fn($aa, $bb) => eval($sortfunc));
418
-		}
419
-	}
420
-
421
-
422
-	/**
423
-	 * Grouper les resultats
424
-	 * {fusion /x/y/z}
425
-	 *
426
-	 **/
427
-	protected function select_groupby() {
428
-		// virer le / initial pour les criteres de la forme {fusion /xx}
429
-		if (strlen($fusion = ltrim($this->command['groupby'][0], '/'))) {
430
-			$vu = [];
431
-			foreach ($this->tableau as $k => $v) {
432
-				$val = table_valeur($v, $fusion);
433
-				if (isset($vu[$val])) {
434
-					unset($this->tableau[$k]);
435
-				} else {
436
-					$vu[$val] = true;
437
-				}
438
-			}
439
-		}
440
-	}
441
-
442
-
443
-	/**
444
-	 * L'iterateur est-il encore valide ?
445
-	 *
446
-	 * @return bool
447
-	 */
448
-	public function valid(): bool {
449
-		return !is_null($this->cle);
450
-	}
451
-
452
-	/**
453
-	 * Retourner la valeur
454
-	 *
455
-	 * @return mixed
456
-	 */
457
-	#[\ReturnTypeWillChange]
458
-	public function current() {
459
-		return $this->valeur;
460
-	}
461
-
462
-	/**
463
-	 * Retourner la cle
464
-	 *
465
-	 * @return mixed
466
-	 */
467
-	#[\ReturnTypeWillChange]
468
-	public function key() {
469
-		return $this->cle;
470
-	}
471
-
472
-	/**
473
-	 * Passer a la valeur suivante
474
-	 *
475
-	 * @return void
476
-	 */
477
-	public function next(): void {
478
-		if ($this->valid()) {
479
-			$this->cle = key($this->tableau);
480
-			$this->valeur = current($this->tableau);
481
-			next($this->tableau);
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Compter le nombre total de resultats
487
-	 *
488
-	 * @return int
489
-	 */
490
-	public function count() {
491
-		if (is_null($this->total)) {
492
-			$this->total = count($this->tableau);
493
-		}
494
-
495
-		return $this->total;
496
-	}
410
+                    }
411
+                }
412
+            }
413
+        }
414
+
415
+        if ($sortfunc) {
416
+            $sortfunc .= "\n return 0;";
417
+            uasort($this->tableau, fn($aa, $bb) => eval($sortfunc));
418
+        }
419
+    }
420
+
421
+
422
+    /**
423
+     * Grouper les resultats
424
+     * {fusion /x/y/z}
425
+     *
426
+     **/
427
+    protected function select_groupby() {
428
+        // virer le / initial pour les criteres de la forme {fusion /xx}
429
+        if (strlen($fusion = ltrim($this->command['groupby'][0], '/'))) {
430
+            $vu = [];
431
+            foreach ($this->tableau as $k => $v) {
432
+                $val = table_valeur($v, $fusion);
433
+                if (isset($vu[$val])) {
434
+                    unset($this->tableau[$k]);
435
+                } else {
436
+                    $vu[$val] = true;
437
+                }
438
+            }
439
+        }
440
+    }
441
+
442
+
443
+    /**
444
+     * L'iterateur est-il encore valide ?
445
+     *
446
+     * @return bool
447
+     */
448
+    public function valid(): bool {
449
+        return !is_null($this->cle);
450
+    }
451
+
452
+    /**
453
+     * Retourner la valeur
454
+     *
455
+     * @return mixed
456
+     */
457
+    #[\ReturnTypeWillChange]
458
+    public function current() {
459
+        return $this->valeur;
460
+    }
461
+
462
+    /**
463
+     * Retourner la cle
464
+     *
465
+     * @return mixed
466
+     */
467
+    #[\ReturnTypeWillChange]
468
+    public function key() {
469
+        return $this->cle;
470
+    }
471
+
472
+    /**
473
+     * Passer a la valeur suivante
474
+     *
475
+     * @return void
476
+     */
477
+    public function next(): void {
478
+        if ($this->valid()) {
479
+            $this->cle = key($this->tableau);
480
+            $this->valeur = current($this->tableau);
481
+            next($this->tableau);
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Compter le nombre total de resultats
487
+     *
488
+     * @return int
489
+     */
490
+    public function count() {
491
+        if (is_null($this->total)) {
492
+            $this->total = count($this->tableau);
493
+        }
494
+
495
+        return $this->total;
496
+    }
497 497
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		// Si a ce stade on n'a pas de table, il y a un bug
164 164
 		if (!is_array($this->tableau)) {
165 165
 			$this->err = true;
166
-			spip_log('erreur datasource ' . var_export($command, true));
166
+			spip_log('erreur datasource '.var_export($command, true));
167 167
 		}
168 168
 
169 169
 		// {datapath query.results}
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 			isset($this->command['sourcemode'])
206 206
 			&& !in_array($this->command['sourcemode'], ['table', 'array', 'tableau'])
207 207
 		) {
208
-			charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true);
208
+			charger_fonction($this->command['sourcemode'].'_to_array', 'inc', true);
209 209
 		}
210 210
 
211 211
 		# le premier argument peut etre un array, une URL etc.
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 		# avons-nous un cache dispo ?
215 215
 		$cle = null;
216 216
 		if (is_string($src)) {
217
-			$cle = 'datasource_' . md5($this->command['sourcemode'] . ':' . var_export($this->command['source'], true));
217
+			$cle = 'datasource_'.md5($this->command['sourcemode'].':'.var_export($this->command['source'], true));
218 218
 		}
219 219
 
220 220
 		$cache = $this->cache_get($cle);
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 					}
267 267
 					if (
268 268
 						!$this->err
269
-						&& ($data_to_array = charger_fonction($this->command['sourcemode'] . '_to_array', 'inc', true))
269
+						&& ($data_to_array = charger_fonction($this->command['sourcemode'].'_to_array', 'inc', true))
270 270
 					) {
271 271
 						$args = $this->command['source'];
272 272
 						$args[0] = $data;
@@ -401,12 +401,12 @@  discard block
 block discarded – undo
401 401
 						$this->tableau = $v;
402 402
 					} else {
403 403
 						# {par valeur} ou {par valeur/xx/yy}
404
-						$tv = $r[1] == 'valeur' ? '%s' : 'table_valeur(%s, ' . var_export($r[1], true) . ')';
404
+						$tv = $r[1] == 'valeur' ? '%s' : 'table_valeur(%s, '.var_export($r[1], true).')';
405 405
 						$sortfunc .= '
406
-					$a = ' . sprintf($tv, '$aa') . ';
407
-					$b = ' . sprintf($tv, '$bb') . ';
406
+					$a = ' . sprintf($tv, '$aa').';
407
+					$b = ' . sprintf($tv, '$bb').';
408 408
 					if ($a <> $b)
409
-						return ($a ' . (empty($r[2]) ? '<' : '>') . ' $b) ? -1 : 1;';
409
+						return ($a ' . (empty($r[2]) ? '<' : '>').' $b) ? -1 : 1;';
410 410
 					}
411 411
 				}
412 412
 			}
Please login to merge, or discard this patch.
ecrire/src/Compilateur/Iterateur/Sql.php 1 patch
Indentation   +182 added lines, -182 removed lines patch added patch discarded remove patch
@@ -11,193 +11,193 @@
 block discarded – undo
11 11
  */
12 12
 class Sql extends AbstractIterateur implements Iterator
13 13
 {
14
-	/**
15
-	 * Ressource sql.
16
-	 *
17
-	 * @var bool|object
18
-	 */
19
-	protected $sqlresult = false;
14
+    /**
15
+     * Ressource sql.
16
+     *
17
+     * @var bool|object
18
+     */
19
+    protected $sqlresult = false;
20 20
 
21
-	/**
22
-	 * row sql courante.
23
-	 *
24
-	 * @var null|array
25
-	 */
26
-	protected $row;
21
+    /**
22
+     * row sql courante.
23
+     *
24
+     * @var null|array
25
+     */
26
+    protected $row;
27 27
 
28
-	protected bool $firstseek = false;
28
+    protected bool $firstseek = false;
29 29
 
30
-	protected int $pos = -1;
30
+    protected int $pos = -1;
31 31
 
32
-	/*
32
+    /*
33 33
 	 * array command: les commandes d'initialisation
34 34
 	 * array info: les infos sur le squelette
35 35
 	 */
36
-	public function __construct(array $command, array $info = []) {
37
-		$this->type = 'SQL';
38
-		parent::__construct($command, $info);
39
-
40
-		$this->select();
41
-	}
42
-
43
-	/**
44
-	 * Rembobiner.
45
-	 *
46
-	 * @return bool
47
-	 */
48
-	public function rewind(): void {
49
-		if ($this->pos > 0) {
50
-			$this->seek(0);
51
-		}
52
-	}
53
-
54
-	/**
55
-	 * Verifier l'etat de l'iterateur.
56
-	 */
57
-	public function valid(): bool {
58
-		if ($this->err) {
59
-			return false;
60
-		}
61
-		if (!$this->firstseek) {
62
-			$this->next();
63
-		}
64
-
65
-		return is_array($this->row);
66
-	}
67
-
68
-	/**
69
-	 * Valeurs sur la position courante.
70
-	 *
71
-	 * @return array
72
-	 */
73
-	#[\ReturnTypeWillChange]
74
-	public function current() {
75
-		return $this->row;
76
-	}
77
-
78
-	#[\ReturnTypeWillChange]
79
-	public function key() {
80
-		return $this->pos;
81
-	}
82
-
83
-	/**
84
-	 * Sauter a une position absolue.
85
-	 *
86
-	 * @param int         $n
87
-	 * @param null|string $continue
88
-	 *
89
-	 * @return bool
90
-	 */
91
-	public function seek($n = 0, $continue = null) {
92
-		if (!sql_seek($this->sqlresult, $n, $this->command['connect'], $continue)) {
93
-			// SQLite ne sait pas seek(), il faut relancer la query
94
-			// si la position courante est apres la position visee
95
-			// il faut relancer la requete
96
-			if ($this->pos > $n) {
97
-				$this->free();
98
-				$this->select();
99
-				$this->valid();
100
-			}
101
-			// et utiliser la methode par defaut pour se deplacer au bon endroit
102
-			// (sera fait en cas d'echec de cette fonction)
103
-			return false;
104
-		}
105
-		$this->row = sql_fetch($this->sqlresult, $this->command['connect']);
106
-		$this->pos = min($n, $this->count());
107
-
108
-		return true;
109
-	}
110
-
111
-	/**
112
-	 * Avancer d'un cran.
113
-	 */
114
-	public function next(): void {
115
-		$this->row = sql_fetch($this->sqlresult, $this->command['connect']);
116
-		++$this->pos;
117
-		$this->firstseek |= true;
118
-	}
119
-
120
-	/**
121
-	 * Avancer et retourner les donnees pour le nouvel element.
122
-	 *
123
-	 * @return null|array|bool
124
-	 */
125
-	public function fetch() {
126
-		if ($this->valid()) {
127
-			$r = $this->current();
128
-			$this->next();
129
-		} else {
130
-			$r = false;
131
-		}
132
-
133
-		return $r;
134
-	}
135
-
136
-	/**
137
-	 * liberer les ressources.
138
-	 *
139
-	 * @return bool
140
-	 */
141
-	public function free() {
142
-		if (!$this->sqlresult) {
143
-			return true;
144
-		}
145
-		$a = sql_free($this->sqlresult, $this->command['connect']);
146
-		$this->sqlresult = null;
147
-
148
-		return $a;
149
-	}
150
-
151
-	/**
152
-	 * Compter le nombre de resultats.
153
-	 *
154
-	 * @return int
155
-	 */
156
-	public function count() {
157
-		if (is_null($this->total)) {
158
-			if (!$this->sqlresult) {
159
-				$this->total = 0;
160
-			} else {
161
-				// cas count(*)
162
-				if (in_array('count(*)', $this->command['select'])) {
163
-					$this->valid();
164
-					$s = $this->current();
165
-					$this->total = $s['count(*)'];
166
-				} else {
167
-					$this->total = sql_count($this->sqlresult, $this->command['connect']);
168
-				}
169
-			}
170
-		}
171
-
172
-		return $this->total;
173
-	}
174
-
175
-	/**
176
-	 * selectionner les donnees, ie faire la requete SQL.
177
-	 */
178
-	protected function select() {
179
-		$this->row = null;
180
-		$v = &$this->command;
181
-		$this->sqlresult = calculer_select(
182
-			$v['select'],
183
-			$v['from'],
184
-			$v['type'],
185
-			$v['where'],
186
-			$v['join'],
187
-			$v['groupby'],
188
-			$v['orderby'],
189
-			$v['limit'],
190
-			$v['having'],
191
-			$v['table'],
192
-			$v['id'],
193
-			$v['connect'],
194
-			$this->info
195
-		);
196
-		$this->err = !$this->sqlresult;
197
-		$this->firstseek = false;
198
-		$this->pos = -1;
199
-
200
-		// pas d'init a priori, le calcul ne sera fait qu'en cas de besoin (provoque une double requete souvent inutile en sqlite)
201
-		//$this->total = $this->count();
202
-	}
36
+    public function __construct(array $command, array $info = []) {
37
+        $this->type = 'SQL';
38
+        parent::__construct($command, $info);
39
+
40
+        $this->select();
41
+    }
42
+
43
+    /**
44
+     * Rembobiner.
45
+     *
46
+     * @return bool
47
+     */
48
+    public function rewind(): void {
49
+        if ($this->pos > 0) {
50
+            $this->seek(0);
51
+        }
52
+    }
53
+
54
+    /**
55
+     * Verifier l'etat de l'iterateur.
56
+     */
57
+    public function valid(): bool {
58
+        if ($this->err) {
59
+            return false;
60
+        }
61
+        if (!$this->firstseek) {
62
+            $this->next();
63
+        }
64
+
65
+        return is_array($this->row);
66
+    }
67
+
68
+    /**
69
+     * Valeurs sur la position courante.
70
+     *
71
+     * @return array
72
+     */
73
+    #[\ReturnTypeWillChange]
74
+    public function current() {
75
+        return $this->row;
76
+    }
77
+
78
+    #[\ReturnTypeWillChange]
79
+    public function key() {
80
+        return $this->pos;
81
+    }
82
+
83
+    /**
84
+     * Sauter a une position absolue.
85
+     *
86
+     * @param int         $n
87
+     * @param null|string $continue
88
+     *
89
+     * @return bool
90
+     */
91
+    public function seek($n = 0, $continue = null) {
92
+        if (!sql_seek($this->sqlresult, $n, $this->command['connect'], $continue)) {
93
+            // SQLite ne sait pas seek(), il faut relancer la query
94
+            // si la position courante est apres la position visee
95
+            // il faut relancer la requete
96
+            if ($this->pos > $n) {
97
+                $this->free();
98
+                $this->select();
99
+                $this->valid();
100
+            }
101
+            // et utiliser la methode par defaut pour se deplacer au bon endroit
102
+            // (sera fait en cas d'echec de cette fonction)
103
+            return false;
104
+        }
105
+        $this->row = sql_fetch($this->sqlresult, $this->command['connect']);
106
+        $this->pos = min($n, $this->count());
107
+
108
+        return true;
109
+    }
110
+
111
+    /**
112
+     * Avancer d'un cran.
113
+     */
114
+    public function next(): void {
115
+        $this->row = sql_fetch($this->sqlresult, $this->command['connect']);
116
+        ++$this->pos;
117
+        $this->firstseek |= true;
118
+    }
119
+
120
+    /**
121
+     * Avancer et retourner les donnees pour le nouvel element.
122
+     *
123
+     * @return null|array|bool
124
+     */
125
+    public function fetch() {
126
+        if ($this->valid()) {
127
+            $r = $this->current();
128
+            $this->next();
129
+        } else {
130
+            $r = false;
131
+        }
132
+
133
+        return $r;
134
+    }
135
+
136
+    /**
137
+     * liberer les ressources.
138
+     *
139
+     * @return bool
140
+     */
141
+    public function free() {
142
+        if (!$this->sqlresult) {
143
+            return true;
144
+        }
145
+        $a = sql_free($this->sqlresult, $this->command['connect']);
146
+        $this->sqlresult = null;
147
+
148
+        return $a;
149
+    }
150
+
151
+    /**
152
+     * Compter le nombre de resultats.
153
+     *
154
+     * @return int
155
+     */
156
+    public function count() {
157
+        if (is_null($this->total)) {
158
+            if (!$this->sqlresult) {
159
+                $this->total = 0;
160
+            } else {
161
+                // cas count(*)
162
+                if (in_array('count(*)', $this->command['select'])) {
163
+                    $this->valid();
164
+                    $s = $this->current();
165
+                    $this->total = $s['count(*)'];
166
+                } else {
167
+                    $this->total = sql_count($this->sqlresult, $this->command['connect']);
168
+                }
169
+            }
170
+        }
171
+
172
+        return $this->total;
173
+    }
174
+
175
+    /**
176
+     * selectionner les donnees, ie faire la requete SQL.
177
+     */
178
+    protected function select() {
179
+        $this->row = null;
180
+        $v = &$this->command;
181
+        $this->sqlresult = calculer_select(
182
+            $v['select'],
183
+            $v['from'],
184
+            $v['type'],
185
+            $v['where'],
186
+            $v['join'],
187
+            $v['groupby'],
188
+            $v['orderby'],
189
+            $v['limit'],
190
+            $v['having'],
191
+            $v['table'],
192
+            $v['id'],
193
+            $v['connect'],
194
+            $this->info
195
+        );
196
+        $this->err = !$this->sqlresult;
197
+        $this->firstseek = false;
198
+        $this->pos = -1;
199
+
200
+        // pas d'init a priori, le calcul ne sera fait qu'en cas de besoin (provoque une double requete souvent inutile en sqlite)
201
+        //$this->total = $this->count();
202
+    }
203 203
 }
Please login to merge, or discard this patch.
ecrire/src/Chiffrer/Chiffrement.php 2 patches
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -18,76 +18,76 @@
 block discarded – undo
18 18
  * @link https://www.php.net/manual/fr/book.sodium.php
19 19
  */
20 20
 class Chiffrement {
21
-	/** Chiffre un message en utilisant une clé ou un mot de passe */
22
-	public static function chiffrer(
23
-		string $message,
24
-		#[\SensitiveParameter]
25
-		string $key
26
-	): ?string {
27
-		// create a random salt for key derivation
28
-		$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);
29
-		$key = self::deriveKeyFromPassword($key, $salt);
30
-		$nonce = random_bytes(\SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
31
-		$padded_message = sodium_pad($message, 16);
32
-		$encrypted = sodium_crypto_secretbox($padded_message, $nonce, $key);
33
-		$encoded = base64_encode($salt . $nonce . $encrypted);
34
-		sodium_memzero($key);
35
-		sodium_memzero($nonce);
36
-		sodium_memzero($salt);
37
-		#spip_log("chiffrer($message)=$encoded", 'chiffrer' . _LOG_DEBUG);
38
-		return $encoded;
39
-	}
21
+    /** Chiffre un message en utilisant une clé ou un mot de passe */
22
+    public static function chiffrer(
23
+        string $message,
24
+        #[\SensitiveParameter]
25
+        string $key
26
+    ): ?string {
27
+        // create a random salt for key derivation
28
+        $salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);
29
+        $key = self::deriveKeyFromPassword($key, $salt);
30
+        $nonce = random_bytes(\SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
31
+        $padded_message = sodium_pad($message, 16);
32
+        $encrypted = sodium_crypto_secretbox($padded_message, $nonce, $key);
33
+        $encoded = base64_encode($salt . $nonce . $encrypted);
34
+        sodium_memzero($key);
35
+        sodium_memzero($nonce);
36
+        sodium_memzero($salt);
37
+        #spip_log("chiffrer($message)=$encoded", 'chiffrer' . _LOG_DEBUG);
38
+        return $encoded;
39
+    }
40 40
 
41
-	/** Déchiffre un message en utilisant une clé ou un mot de passe */
42
-	public static function dechiffrer(
43
-		string $encoded,
44
-		#[\SensitiveParameter]
45
-		string $key
46
-	): ?string {
47
-		$decoded = base64_decode($encoded);
48
-		$salt = substr($decoded, 0, \SODIUM_CRYPTO_PWHASH_SALTBYTES);
49
-		$nonce = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES, \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
50
-		$encrypted = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES + \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
51
-		$key = self::deriveKeyFromPassword($key, $salt);
52
-		$padded_message = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
53
-		sodium_memzero($key);
54
-		sodium_memzero($nonce);
55
-		sodium_memzero($salt);
56
-		if ($padded_message === false) {
57
-			spip_log("dechiffrer() chiffre corrompu `$encoded`", 'chiffrer' . _LOG_DEBUG);
58
-			return null;
59
-		}
60
-		return sodium_unpad($padded_message, 16);
61
-	}
41
+    /** Déchiffre un message en utilisant une clé ou un mot de passe */
42
+    public static function dechiffrer(
43
+        string $encoded,
44
+        #[\SensitiveParameter]
45
+        string $key
46
+    ): ?string {
47
+        $decoded = base64_decode($encoded);
48
+        $salt = substr($decoded, 0, \SODIUM_CRYPTO_PWHASH_SALTBYTES);
49
+        $nonce = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES, \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
50
+        $encrypted = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES + \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
51
+        $key = self::deriveKeyFromPassword($key, $salt);
52
+        $padded_message = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
53
+        sodium_memzero($key);
54
+        sodium_memzero($nonce);
55
+        sodium_memzero($salt);
56
+        if ($padded_message === false) {
57
+            spip_log("dechiffrer() chiffre corrompu `$encoded`", 'chiffrer' . _LOG_DEBUG);
58
+            return null;
59
+        }
60
+        return sodium_unpad($padded_message, 16);
61
+    }
62 62
 
63
-	/** Génère une clé de la taille attendue pour le chiffrement */
64
-	public static function keygen(): string {
65
-		return sodium_crypto_secretbox_keygen();
66
-	}
63
+    /** Génère une clé de la taille attendue pour le chiffrement */
64
+    public static function keygen(): string {
65
+        return sodium_crypto_secretbox_keygen();
66
+    }
67 67
 
68
-	/**
69
-	 * Retourne une clé de la taille attendue pour le chiffrement
70
-	 *
71
-	 * Notamment si on utilise un mot de passe comme clé, il faut le hacher
72
-	 * pour servir de clé à la taille correspondante.
73
-	 */
74
-	private static function deriveKeyFromPassword(
75
-		#[\SensitiveParameter]
76
-		string $password,
77
-		string $salt
78
-	): string {
79
-		if (strlen($password) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
80
-			return $password;
81
-		}
82
-		$key = sodium_crypto_pwhash(
83
-			\SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
84
-			$password,
85
-			$salt,
86
-			\SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
87
-			\SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
88
-		);
89
-		sodium_memzero($password);
68
+    /**
69
+     * Retourne une clé de la taille attendue pour le chiffrement
70
+     *
71
+     * Notamment si on utilise un mot de passe comme clé, il faut le hacher
72
+     * pour servir de clé à la taille correspondante.
73
+     */
74
+    private static function deriveKeyFromPassword(
75
+        #[\SensitiveParameter]
76
+        string $password,
77
+        string $salt
78
+    ): string {
79
+        if (strlen($password) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
80
+            return $password;
81
+        }
82
+        $key = sodium_crypto_pwhash(
83
+            \SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
84
+            $password,
85
+            $salt,
86
+            \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
87
+            \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
88
+        );
89
+        sodium_memzero($password);
90 90
 
91
-		return $key;
92
-	}
91
+        return $key;
92
+    }
93 93
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 		$nonce = random_bytes(\SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
31 31
 		$padded_message = sodium_pad($message, 16);
32 32
 		$encrypted = sodium_crypto_secretbox($padded_message, $nonce, $key);
33
-		$encoded = base64_encode($salt . $nonce . $encrypted);
33
+		$encoded = base64_encode($salt.$nonce.$encrypted);
34 34
 		sodium_memzero($key);
35 35
 		sodium_memzero($nonce);
36 36
 		sodium_memzero($salt);
@@ -47,14 +47,14 @@  discard block
 block discarded – undo
47 47
 		$decoded = base64_decode($encoded);
48 48
 		$salt = substr($decoded, 0, \SODIUM_CRYPTO_PWHASH_SALTBYTES);
49 49
 		$nonce = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES, \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
50
-		$encrypted = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES + \SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
50
+		$encrypted = substr($decoded, \SODIUM_CRYPTO_PWHASH_SALTBYTES +\SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
51 51
 		$key = self::deriveKeyFromPassword($key, $salt);
52 52
 		$padded_message = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
53 53
 		sodium_memzero($key);
54 54
 		sodium_memzero($nonce);
55 55
 		sodium_memzero($salt);
56 56
 		if ($padded_message === false) {
57
-			spip_log("dechiffrer() chiffre corrompu `$encoded`", 'chiffrer' . _LOG_DEBUG);
57
+			spip_log("dechiffrer() chiffre corrompu `$encoded`", 'chiffrer'._LOG_DEBUG);
58 58
 			return null;
59 59
 		}
60 60
 		return sodium_unpad($padded_message, 16);
Please login to merge, or discard this patch.
ecrire/src/Chiffrer/SpipCles.php 2 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -13,169 +13,169 @@
 block discarded – undo
13 13
 
14 14
 /** Gestion des clés d’authentification / chiffrement de SPIP */
15 15
 final class SpipCles {
16
-	private static array $instances = [];
17
-
18
-	private string $file = _DIR_ETC . 'cles.php';
19
-	private Cles $cles;
20
-
21
-	public static function instance(string $file = ''): self {
22
-		if (empty(self::$instances[$file])) {
23
-			self::$instances[$file] = new self($file);
24
-		}
25
-		return self::$instances[$file];
26
-	}
27
-
28
-	/**
29
-	 * Retourne le secret du site (shorthand)
30
-	 * @uses self::getSecretSite()
31
-	 */
32
-	public static function secret_du_site(): ?string {
33
-		return (self::instance())->getSecretSite();
34
-	}
35
-
36
-	private function __construct(string $file = '') {
37
-		if ($file) {
38
-			$this->file = $file;
39
-		}
40
-		$this->cles = new Cles($this->read());
41
-	}
42
-
43
-	/**
44
-	 * Renvoyer le secret du site
45
-	 *
46
-	 * Le secret du site doit rester aussi secret que possible, et est eternel
47
-	 * On ne doit pas l'exporter
48
-	 *
49
-	 * Le secret est partagé entre une clé disque et une clé bdd
50
-	 *
51
-	 * @return string
52
-	 */
53
-	public function getSecretSite(bool $autoInit = true): ?string {
54
-		$key = $this->getKey('secret_du_site', $autoInit);
55
-		$meta = $this->getMetaKey('secret_du_site', $autoInit);
56
-		// conserve la même longeur.
57
-		return $key ^ $meta;
58
-	}
59
-
60
-	/** Renvoyer le secret des authentifications */
61
-	public function getSecretAuth(bool $autoInit = false): ?string {
62
-		return $this->getKey('secret_des_auth', $autoInit);
63
-	}
64
-	public function save(): bool {
65
-		return ecrire_fichier_securise($this->file, $this->cles->toJson());
66
-	}
67
-
68
-	/**
69
-	 * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
70
-	 *
71
-	 * @param string $withKey Clé de chiffrage de la sauvegarde
72
-	 * @return string Contenu de la sauvegarde chiffrée générée
73
-	 */
74
-	public function backup(
75
-		#[\SensitiveParameter]
76
-		string $withKey
77
-	): string {
78
-		if (count($this->cles)) {
79
-			return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
80
-		}
81
-		return '';
82
-	}
83
-
84
-	/**
85
-	 * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
86
-	 * (si la sauvegarde est bien valide)
87
-	 */
88
-	public function restore(
89
-		/** Sauvegarde chiffrée (générée par backup()) */
90
-		string $backup,
91
-		#[\SensitiveParameter]
92
-		string $password_clair,
93
-		#[\SensitiveParameter]
94
-		string $password_hash,
95
-		int $id_auteur
96
-	): bool {
97
-		if (empty($backup)) {
98
-			return false;
99
-		}
100
-
101
-		$sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
102
-		$json = json_decode($sauvegarde, true);
103
-		if (!$json) {
104
-			return false;
105
-		}
106
-
107
-		// cela semble une sauvegarde valide
108
-		$cles_potentielles = array_map('base64_decode', $json);
109
-
110
-		// il faut faire une double verif sur secret_des_auth
111
-		// pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
112
-		// et par extension tous les passwords
113
-		if (
114
-			!empty($cles_potentielles['secret_des_auth'])
115
-			&& !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116
-		) {
117
-			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
118
-			unset($cles_potentielles['secret_des_auth']);
119
-		}
120
-
121
-		// on merge les cles pour recuperer les cles manquantes
122
-		$restauration = false;
123
-		foreach ($cles_potentielles as $name => $key) {
124
-			if (!$this->cles->has($name)) {
125
-				$this->cles->set($name, $key);
126
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
127
-				$restauration = true;
128
-			}
129
-		}
130
-		return $restauration;
131
-	}
132
-
133
-	private function getKey(string $name, bool $autoInit): ?string {
134
-		if ($this->cles->has($name)) {
135
-			return $this->cles->get($name);
136
-		}
137
-		if ($autoInit) {
138
-			$this->cles->generate($name);
139
-			// si l'ecriture de fichier a bien marche on peut utiliser la cle
140
-			if ($this->save()) {
141
-				return $this->cles->get($name);
142
-			}
143
-			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
145
-			$this->cles->delete($name);
146
-		}
147
-		return null;
148
-	}
149
-
150
-	private function getMetaKey(string $name, bool $autoInit = true): ?string {
151
-		if (!isset($GLOBALS['meta'][$name])) {
152
-			include_spip('base/abstract_sql');
153
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
154
-		}
155
-		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
156
-		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
157
-			return $key;
158
-		}
159
-		if (!$autoInit) {
160
-			return null;
161
-		}
162
-		$key = Chiffrement::keygen();
163
-		ecrire_meta($name, base64_encode($key), 'non');
164
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
165
-
166
-		return $key;
167
-	}
168
-
169
-	private function read(): array {
170
-		$json = null;
171
-		lire_fichier_securise($this->file, $json);
172
-		if (
173
-			$json
174
-			&& ($json = \json_decode($json, true))
175
-			&& is_array($json)
176
-		) {
177
-			return array_map('base64_decode', $json);
178
-		}
179
-		return [];
180
-	}
16
+    private static array $instances = [];
17
+
18
+    private string $file = _DIR_ETC . 'cles.php';
19
+    private Cles $cles;
20
+
21
+    public static function instance(string $file = ''): self {
22
+        if (empty(self::$instances[$file])) {
23
+            self::$instances[$file] = new self($file);
24
+        }
25
+        return self::$instances[$file];
26
+    }
27
+
28
+    /**
29
+     * Retourne le secret du site (shorthand)
30
+     * @uses self::getSecretSite()
31
+     */
32
+    public static function secret_du_site(): ?string {
33
+        return (self::instance())->getSecretSite();
34
+    }
35
+
36
+    private function __construct(string $file = '') {
37
+        if ($file) {
38
+            $this->file = $file;
39
+        }
40
+        $this->cles = new Cles($this->read());
41
+    }
42
+
43
+    /**
44
+     * Renvoyer le secret du site
45
+     *
46
+     * Le secret du site doit rester aussi secret que possible, et est eternel
47
+     * On ne doit pas l'exporter
48
+     *
49
+     * Le secret est partagé entre une clé disque et une clé bdd
50
+     *
51
+     * @return string
52
+     */
53
+    public function getSecretSite(bool $autoInit = true): ?string {
54
+        $key = $this->getKey('secret_du_site', $autoInit);
55
+        $meta = $this->getMetaKey('secret_du_site', $autoInit);
56
+        // conserve la même longeur.
57
+        return $key ^ $meta;
58
+    }
59
+
60
+    /** Renvoyer le secret des authentifications */
61
+    public function getSecretAuth(bool $autoInit = false): ?string {
62
+        return $this->getKey('secret_des_auth', $autoInit);
63
+    }
64
+    public function save(): bool {
65
+        return ecrire_fichier_securise($this->file, $this->cles->toJson());
66
+    }
67
+
68
+    /**
69
+     * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
70
+     *
71
+     * @param string $withKey Clé de chiffrage de la sauvegarde
72
+     * @return string Contenu de la sauvegarde chiffrée générée
73
+     */
74
+    public function backup(
75
+        #[\SensitiveParameter]
76
+        string $withKey
77
+    ): string {
78
+        if (count($this->cles)) {
79
+            return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
80
+        }
81
+        return '';
82
+    }
83
+
84
+    /**
85
+     * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
86
+     * (si la sauvegarde est bien valide)
87
+     */
88
+    public function restore(
89
+        /** Sauvegarde chiffrée (générée par backup()) */
90
+        string $backup,
91
+        #[\SensitiveParameter]
92
+        string $password_clair,
93
+        #[\SensitiveParameter]
94
+        string $password_hash,
95
+        int $id_auteur
96
+    ): bool {
97
+        if (empty($backup)) {
98
+            return false;
99
+        }
100
+
101
+        $sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
102
+        $json = json_decode($sauvegarde, true);
103
+        if (!$json) {
104
+            return false;
105
+        }
106
+
107
+        // cela semble une sauvegarde valide
108
+        $cles_potentielles = array_map('base64_decode', $json);
109
+
110
+        // il faut faire une double verif sur secret_des_auth
111
+        // pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
112
+        // et par extension tous les passwords
113
+        if (
114
+            !empty($cles_potentielles['secret_des_auth'])
115
+            && !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116
+        ) {
117
+            spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
118
+            unset($cles_potentielles['secret_des_auth']);
119
+        }
120
+
121
+        // on merge les cles pour recuperer les cles manquantes
122
+        $restauration = false;
123
+        foreach ($cles_potentielles as $name => $key) {
124
+            if (!$this->cles->has($name)) {
125
+                $this->cles->set($name, $key);
126
+                spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
127
+                $restauration = true;
128
+            }
129
+        }
130
+        return $restauration;
131
+    }
132
+
133
+    private function getKey(string $name, bool $autoInit): ?string {
134
+        if ($this->cles->has($name)) {
135
+            return $this->cles->get($name);
136
+        }
137
+        if ($autoInit) {
138
+            $this->cles->generate($name);
139
+            // si l'ecriture de fichier a bien marche on peut utiliser la cle
140
+            if ($this->save()) {
141
+                return $this->cles->get($name);
142
+            }
143
+            // sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
+            spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
145
+            $this->cles->delete($name);
146
+        }
147
+        return null;
148
+    }
149
+
150
+    private function getMetaKey(string $name, bool $autoInit = true): ?string {
151
+        if (!isset($GLOBALS['meta'][$name])) {
152
+            include_spip('base/abstract_sql');
153
+            $GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
154
+        }
155
+        $key = base64_decode($GLOBALS['meta'][$name] ?? '');
156
+        if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
157
+            return $key;
158
+        }
159
+        if (!$autoInit) {
160
+            return null;
161
+        }
162
+        $key = Chiffrement::keygen();
163
+        ecrire_meta($name, base64_encode($key), 'non');
164
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
165
+
166
+        return $key;
167
+    }
168
+
169
+    private function read(): array {
170
+        $json = null;
171
+        lire_fichier_securise($this->file, $json);
172
+        if (
173
+            $json
174
+            && ($json = \json_decode($json, true))
175
+            && is_array($json)
176
+        ) {
177
+            return array_map('base64_decode', $json);
178
+        }
179
+        return [];
180
+    }
181 181
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 final class SpipCles {
16 16
 	private static array $instances = [];
17 17
 
18
-	private string $file = _DIR_ETC . 'cles.php';
18
+	private string $file = _DIR_ETC.'cles.php';
19 19
 	private Cles $cles;
20 20
 
21 21
 	public static function instance(string $file = ''): self {
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			!empty($cles_potentielles['secret_des_auth'])
115 115
 			&& !Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])
116 116
 		) {
117
-			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
117
+			spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer'._LOG_INFO_IMPORTANTE);
118 118
 			unset($cles_potentielles['secret_des_auth']);
119 119
 		}
120 120
 
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 		foreach ($cles_potentielles as $name => $key) {
124 124
 			if (!$this->cles->has($name)) {
125 125
 				$this->cles->set($name, $key);
126
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
126
+				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer'._LOG_INFO_IMPORTANTE);
127 127
 				$restauration = true;
128 128
 			}
129 129
 		}
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 				return $this->cles->get($name);
142 142
 			}
143 143
 			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
144
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
144
+			spip_log('Echec ecriture du fichier cle '.$this->file." ; impossible de generer une cle $name", 'chiffrer'._LOG_ERREUR);
145 145
 			$this->cles->delete($name);
146 146
 		}
147 147
 		return null;
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	private function getMetaKey(string $name, bool $autoInit = true): ?string {
151 151
 		if (!isset($GLOBALS['meta'][$name])) {
152 152
 			include_spip('base/abstract_sql');
153
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
153
+			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = '.sql_quote($name, '', 'string'));
154 154
 		}
155 155
 		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
156 156
 		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
Please login to merge, or discard this patch.
ecrire/src/Admin/Bouton.php 2 patches
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -7,32 +7,32 @@
 block discarded – undo
7 7
  * privée ou dans un de ses sous menus
8 8
  */
9 9
 class Bouton {
10
-	/** Sous-barre de boutons / onglets */
11
-	public array $sousmenu = [];
10
+    /** Sous-barre de boutons / onglets */
11
+    public array $sousmenu = [];
12 12
 
13
-	/** Position dans le menu */
14
-	public int $position = 0;
13
+    /** Position dans le menu */
14
+    public int $position = 0;
15 15
 
16
-	/** Entrée favorite (sa position dans les favoris) ? */
17
-	public int $favori = 0;
16
+    /** Entrée favorite (sa position dans les favoris) ? */
17
+    public int $favori = 0;
18 18
 
19 19
 
20
-	/**
21
-	 * Définit un bouton
22
-	 */
23
-	public function __construct(
24
-		/** L'icone à mettre dans le bouton */
25
-		public string $icone,
26
-		/** Le nom de l'entrée d'i18n associé */
27
-		public string $libelle,
28
-		/** L'URL de la page (null => ?exec=nom) */
29
-		public ?string $url = null,
30
-		/** Arguments supplémentaires de l'URL */
31
-		public string|array|null $urlArg = null,
32
-		/** URL du javascript */
33
-		public ?string $url2 = null,
34
-		/** Pour ouvrir une fenêtre à part */
35
-		public ?string $target = null
36
-	) {
37
-	}
20
+    /**
21
+     * Définit un bouton
22
+     */
23
+    public function __construct(
24
+        /** L'icone à mettre dans le bouton */
25
+        public string $icone,
26
+        /** Le nom de l'entrée d'i18n associé */
27
+        public string $libelle,
28
+        /** L'URL de la page (null => ?exec=nom) */
29
+        public ?string $url = null,
30
+        /** Arguments supplémentaires de l'URL */
31
+        public string|array|null $urlArg = null,
32
+        /** URL du javascript */
33
+        public ?string $url2 = null,
34
+        /** Pour ouvrir une fenêtre à part */
35
+        public ?string $target = null
36
+    ) {
37
+    }
38 38
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@
 block discarded – undo
28 28
 		/** L'URL de la page (null => ?exec=nom) */
29 29
 		public ?string $url = null,
30 30
 		/** Arguments supplémentaires de l'URL */
31
-		public string|array|null $urlArg = null,
31
+		public string | array | null $urlArg = null,
32 32
 		/** URL du javascript */
33 33
 		public ?string $url2 = null,
34 34
 		/** Pour ouvrir une fenêtre à part */
Please login to merge, or discard this patch.
ecrire/src/Css/Vars/Collection.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -7,21 +7,21 @@
 block discarded – undo
7 7
  * @internal
8 8
  */
9 9
 class Collection implements \Stringable {
10
-	private array $vars = [];
10
+    private array $vars = [];
11 11
 
12
-	public function add(string $var, string $value) {
13
-		$this->vars[$var] = $value;
14
-	}
12
+    public function add(string $var, string $value) {
13
+        $this->vars[$var] = $value;
14
+    }
15 15
 
16
-	public function getString(): string {
17
-		$string = '';
18
-		foreach ($this->vars as $key => $value) {
19
-			$string .= "$key: $value;\n";
20
-		}
21
-		return $string;
22
-	}
16
+    public function getString(): string {
17
+        $string = '';
18
+        foreach ($this->vars as $key => $value) {
19
+            $string .= "$key: $value;\n";
20
+        }
21
+        return $string;
22
+    }
23 23
 
24
-	public function __toString(): string {
25
-		return $this->getString();
26
-	}
24
+    public function __toString(): string {
25
+        return $this->getString();
26
+    }
27 27
 }
Please login to merge, or discard this patch.
ecrire/plugins/afficher_repertoires.php 2 patches
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -10,110 +10,110 @@
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 function plugins_afficher_repertoires_dist($url_page, $liste_plugins, $liste_plugins_actifs) {
17
-	$ligne_plug = charger_fonction('afficher_plugin', 'plugins');
18
-	$racine = basename(_DIR_PLUGINS);
19
-	$init_dir = $current_dir = '';
20
-	// liste des repertoires deplies : construit en remontant l'arbo de chaque plugin actif
21
-	// des qu'un path est deja note deplie on s'arrete
22
-	$deplie = [$racine => true];
23
-	$fast_liste_plugins_actifs = [];
24
-	foreach ($liste_plugins_actifs as $key => $plug) {
25
-		$chemin_plug = chemin_plug($racine, $plug);
26
-		$fast_liste_plugins_actifs[$chemin_plug] = true;
27
-		$dir = dirname($chemin_plug);
28
-		$maxiter = 100;
29
-		while (strlen($dir) && !isset($deplie[$dir]) && $dir !== $racine && $maxiter-- > 0) {
30
-			$deplie[$dir] = true;
31
-			$dir = dirname($dir);
32
-		}
33
-	}
17
+    $ligne_plug = charger_fonction('afficher_plugin', 'plugins');
18
+    $racine = basename(_DIR_PLUGINS);
19
+    $init_dir = $current_dir = '';
20
+    // liste des repertoires deplies : construit en remontant l'arbo de chaque plugin actif
21
+    // des qu'un path est deja note deplie on s'arrete
22
+    $deplie = [$racine => true];
23
+    $fast_liste_plugins_actifs = [];
24
+    foreach ($liste_plugins_actifs as $key => $plug) {
25
+        $chemin_plug = chemin_plug($racine, $plug);
26
+        $fast_liste_plugins_actifs[$chemin_plug] = true;
27
+        $dir = dirname($chemin_plug);
28
+        $maxiter = 100;
29
+        while (strlen($dir) && !isset($deplie[$dir]) && $dir !== $racine && $maxiter-- > 0) {
30
+            $deplie[$dir] = true;
31
+            $dir = dirname($dir);
32
+        }
33
+    }
34 34
 
35
-	// index repertoires --> plugin
36
-	$dir_index = [];
37
-	foreach ($liste_plugins as $key => $plug) {
38
-		$liste_plugins[$key] = chemin_plug($racine, $plug);
39
-		$dir_index[dirname($liste_plugins[$key])][] = $key;
40
-	}
35
+    // index repertoires --> plugin
36
+    $dir_index = [];
37
+    foreach ($liste_plugins as $key => $plug) {
38
+        $liste_plugins[$key] = chemin_plug($racine, $plug);
39
+        $dir_index[dirname($liste_plugins[$key])][] = $key;
40
+    }
41 41
 
42
-	$visible = @isset($deplie[$current_dir]);
43
-	$maxiter = 1000;
42
+    $visible = @isset($deplie[$current_dir]);
43
+    $maxiter = 1000;
44 44
 
45
-	$res = '';
46
-	while ((is_countable($liste_plugins) ? count($liste_plugins) : 0) && $maxiter--) {
47
-		// le rep suivant
48
-		$dir = dirname(reset($liste_plugins));
49
-		if ($dir != $current_dir) {
50
-			$res .= tree_open_close_dir($current_dir, $dir, $deplie);
51
-		}
45
+    $res = '';
46
+    while ((is_countable($liste_plugins) ? count($liste_plugins) : 0) && $maxiter--) {
47
+        // le rep suivant
48
+        $dir = dirname(reset($liste_plugins));
49
+        if ($dir != $current_dir) {
50
+            $res .= tree_open_close_dir($current_dir, $dir, $deplie);
51
+        }
52 52
 
53
-		// d'abord tous les plugins du rep courant
54
-		if (isset($dir_index[$current_dir])) {
55
-			foreach ($dir_index[$current_dir] as $key) {
56
-				$plug = $liste_plugins[$key];
57
-				$actif = @isset($fast_liste_plugins_actifs[$plug]);
58
-				$id = substr(md5($plug), 0, 16);
59
-				$res .= $ligne_plug(
60
-					$url_page,
61
-					str_replace(_DIR_PLUGINS, '', _DIR_RACINE . $plug),
62
-					$actif,
63
-					'menu-entree'
64
-				) . "\n";
65
-				unset($liste_plugins[$key]);
66
-			}
67
-		}
68
-	}
69
-	$res .= tree_open_close_dir($current_dir, $init_dir, true);
53
+        // d'abord tous les plugins du rep courant
54
+        if (isset($dir_index[$current_dir])) {
55
+            foreach ($dir_index[$current_dir] as $key) {
56
+                $plug = $liste_plugins[$key];
57
+                $actif = @isset($fast_liste_plugins_actifs[$plug]);
58
+                $id = substr(md5($plug), 0, 16);
59
+                $res .= $ligne_plug(
60
+                    $url_page,
61
+                    str_replace(_DIR_PLUGINS, '', _DIR_RACINE . $plug),
62
+                    $actif,
63
+                    'menu-entree'
64
+                ) . "\n";
65
+                unset($liste_plugins[$key]);
66
+            }
67
+        }
68
+    }
69
+    $res .= tree_open_close_dir($current_dir, $init_dir, true);
70 70
 
71
-	return "<ul class='menu-liste plugins'>"
72
-	. $res
73
-	. '</ul>';
71
+    return "<ul class='menu-liste plugins'>"
72
+    . $res
73
+    . '</ul>';
74 74
 }
75 75
 
76 76
 
77 77
 // vraiment n'importe quoi la gestion des chemins des plugins
78 78
 // une fonction pour aider...
79 79
 function chemin_plug($racine, $plug) {
80
-	return preg_replace(',[^/]+/\.\./,', '', "$racine/$plug");
80
+    return preg_replace(',[^/]+/\.\./,', '', "$racine/$plug");
81 81
 }
82 82
 
83 83
 function tree_open_close_dir(&$current, $target, $deplie = []) {
84
-	if ($current == $target) {
85
-		return '';
86
-	}
87
-	$tcur = explode('/', $current);
88
-	$ttarg = explode('/', $target);
89
-	$tcom = [];
90
-	$output = '';
91
-	// la partie commune
92
-	while (reset($tcur) === reset($ttarg)) {
93
-		$tcom[] = array_shift($tcur);
94
-		array_shift($ttarg);
95
-	}
96
-	// fermer les repertoires courant jusqu'au point de fork
97
-	while ($close = array_pop($tcur)) {
98
-		$output .= "</ul>\n";
99
-		$output .= fin_block();
100
-		$output .= "</li>\n";
101
-	}
102
-	$chemin = '';
103
-	if ($tcom !== []) {
104
-		$chemin .= implode('/', $tcom) . '/';
105
-	}
106
-	// ouvrir les repertoires jusqu'a la cible
107
-	while ($open = array_shift($ttarg)) {
108
-		$visible = @isset($deplie[$chemin . $open]);
109
-		$chemin .= $open . '/';
110
-		$output .= '<li>';
111
-		$output .= bouton_block_depliable($chemin, $visible);
112
-		$output .= debut_block_depliable($visible);
84
+    if ($current == $target) {
85
+        return '';
86
+    }
87
+    $tcur = explode('/', $current);
88
+    $ttarg = explode('/', $target);
89
+    $tcom = [];
90
+    $output = '';
91
+    // la partie commune
92
+    while (reset($tcur) === reset($ttarg)) {
93
+        $tcom[] = array_shift($tcur);
94
+        array_shift($ttarg);
95
+    }
96
+    // fermer les repertoires courant jusqu'au point de fork
97
+    while ($close = array_pop($tcur)) {
98
+        $output .= "</ul>\n";
99
+        $output .= fin_block();
100
+        $output .= "</li>\n";
101
+    }
102
+    $chemin = '';
103
+    if ($tcom !== []) {
104
+        $chemin .= implode('/', $tcom) . '/';
105
+    }
106
+    // ouvrir les repertoires jusqu'a la cible
107
+    while ($open = array_shift($ttarg)) {
108
+        $visible = @isset($deplie[$chemin . $open]);
109
+        $chemin .= $open . '/';
110
+        $output .= '<li>';
111
+        $output .= bouton_block_depliable($chemin, $visible);
112
+        $output .= debut_block_depliable($visible);
113 113
 
114
-		$output .= "<ul>\n";
115
-	}
116
-	$current = $target;
114
+        $output .= "<ul>\n";
115
+    }
116
+    $current = $target;
117 117
 
118
-	return $output;
118
+    return $output;
119 119
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -58,10 +58,10 @@  discard block
 block discarded – undo
58 58
 				$id = substr(md5($plug), 0, 16);
59 59
 				$res .= $ligne_plug(
60 60
 					$url_page,
61
-					str_replace(_DIR_PLUGINS, '', _DIR_RACINE . $plug),
61
+					str_replace(_DIR_PLUGINS, '', _DIR_RACINE.$plug),
62 62
 					$actif,
63 63
 					'menu-entree'
64
-				) . "\n";
64
+				)."\n";
65 65
 				unset($liste_plugins[$key]);
66 66
 			}
67 67
 		}
@@ -101,12 +101,12 @@  discard block
 block discarded – undo
101 101
 	}
102 102
 	$chemin = '';
103 103
 	if ($tcom !== []) {
104
-		$chemin .= implode('/', $tcom) . '/';
104
+		$chemin .= implode('/', $tcom).'/';
105 105
 	}
106 106
 	// ouvrir les repertoires jusqu'a la cible
107 107
 	while ($open = array_shift($ttarg)) {
108
-		$visible = @isset($deplie[$chemin . $open]);
109
-		$chemin .= $open . '/';
108
+		$visible = @isset($deplie[$chemin.$open]);
109
+		$chemin .= $open.'/';
110 110
 		$output .= '<li>';
111 111
 		$output .= bouton_block_depliable($chemin, $visible);
112 112
 		$output .= debut_block_depliable($visible);
Please login to merge, or discard this patch.
ecrire/plugins/get_infos.php 2 patches
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  **/
17 17
 
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -32,110 +32,110 @@  discard block
 block discarded – undo
32 32
  * @return array
33 33
  */
34 34
 function plugins_get_infos_dist($plug = false, $reload = false, $dir = _DIR_PLUGINS, $clean_old = false) {
35
-	$contenu = null;
36
-	$res = null;
37
-	static $cache = '';
38
-	static $filecache = '';
39
-
40
-	if ($cache === '') {
41
-		$filecache = _DIR_TMP . 'plugin_xml_cache.gz';
42
-		if (is_file($filecache)) {
43
-			lire_fichier($filecache, $contenu);
44
-			$cache = unserialize($contenu);
45
-		}
46
-		if (!is_array($cache)) {
47
-			$cache = [];
48
-		}
49
-	}
50
-
51
-	if (defined('_VAR_MODE') && _VAR_MODE == 'recalcul') {
52
-		$reload = true;
53
-	}
54
-
55
-	if ($plug === false) {
56
-		ecrire_fichier($filecache, serialize($cache));
57
-
58
-		return $cache;
59
-	} elseif (is_string($plug)) {
60
-		$res = plugins_get_infos_un($plug, $reload, $dir, $cache);
61
-	} elseif (is_array($plug)) {
62
-		$res = false;
63
-		if (!$reload) {
64
-			$reload = -1;
65
-		}
66
-		foreach ($plug as $nom) {
67
-			$res |= plugins_get_infos_un($nom, $reload, $dir, $cache);
68
-		}
69
-
70
-		// Nettoyer le cache des vieux plugins qui ne sont plus la
71
-		if ($clean_old && isset($cache[$dir]) && (is_countable($cache[$dir]) ? count($cache[$dir]) : 0)) {
72
-			foreach (array_keys($cache[$dir]) as $p) {
73
-				if (!in_array($p, $plug)) {
74
-					unset($cache[$dir][$p]);
75
-				}
76
-			}
77
-		}
78
-	}
79
-	if ($res) {
80
-		ecrire_fichier($filecache, serialize($cache));
81
-	}
82
-	if (!isset($cache[$dir])) {
83
-		return [];
84
-	}
85
-	if (is_string($plug)) {
86
-		return $cache[$dir][$plug] ?? [];
87
-	} else {
88
-		return $cache[$dir];
89
-	}
35
+    $contenu = null;
36
+    $res = null;
37
+    static $cache = '';
38
+    static $filecache = '';
39
+
40
+    if ($cache === '') {
41
+        $filecache = _DIR_TMP . 'plugin_xml_cache.gz';
42
+        if (is_file($filecache)) {
43
+            lire_fichier($filecache, $contenu);
44
+            $cache = unserialize($contenu);
45
+        }
46
+        if (!is_array($cache)) {
47
+            $cache = [];
48
+        }
49
+    }
50
+
51
+    if (defined('_VAR_MODE') && _VAR_MODE == 'recalcul') {
52
+        $reload = true;
53
+    }
54
+
55
+    if ($plug === false) {
56
+        ecrire_fichier($filecache, serialize($cache));
57
+
58
+        return $cache;
59
+    } elseif (is_string($plug)) {
60
+        $res = plugins_get_infos_un($plug, $reload, $dir, $cache);
61
+    } elseif (is_array($plug)) {
62
+        $res = false;
63
+        if (!$reload) {
64
+            $reload = -1;
65
+        }
66
+        foreach ($plug as $nom) {
67
+            $res |= plugins_get_infos_un($nom, $reload, $dir, $cache);
68
+        }
69
+
70
+        // Nettoyer le cache des vieux plugins qui ne sont plus la
71
+        if ($clean_old && isset($cache[$dir]) && (is_countable($cache[$dir]) ? count($cache[$dir]) : 0)) {
72
+            foreach (array_keys($cache[$dir]) as $p) {
73
+                if (!in_array($p, $plug)) {
74
+                    unset($cache[$dir][$p]);
75
+                }
76
+            }
77
+        }
78
+    }
79
+    if ($res) {
80
+        ecrire_fichier($filecache, serialize($cache));
81
+    }
82
+    if (!isset($cache[$dir])) {
83
+        return [];
84
+    }
85
+    if (is_string($plug)) {
86
+        return $cache[$dir][$plug] ?? [];
87
+    } else {
88
+        return $cache[$dir];
89
+    }
90 90
 }
91 91
 
92 92
 
93 93
 function plugins_get_infos_un($plug, $reload, $dir, &$cache) {
94
-	if (!is_readable($file = "$dir$plug/paquet.xml")) {
95
-		return false;
96
-	}
97
-	$time = (int) @filemtime($file);
98
-	if ($time < 0) {
99
-		return false;
100
-	}
101
-	$md5 = md5_file($file);
102
-
103
-	$pcache = $cache[$dir][$plug] ?? ['filemtime' => 0, 'md5_file' => ''];
104
-
105
-	// si le cache est valide
106
-	if (
107
-		(int) $reload <= 0
108
-		&& $time > 0
109
-		&& $time <= $pcache['filemtime']
110
-		&& $md5 == $pcache['md5_file']
111
-	) {
112
-		return false;
113
-	}
114
-
115
-	// si on arrive pas a lire le fichier, se contenter du cache
116
-	if (!($texte = spip_file_get_contents($file))) {
117
-		return false;
118
-	}
119
-
120
-	$f = charger_fonction('infos_paquet', 'plugins');
121
-	$ret = $f($texte, $plug, $dir);
122
-	$ret['filemtime'] = $time;
123
-	$ret['md5_file'] = $md5;
124
-	// Si on lit le paquet.xml de SPIP, on rajoute un procure php afin que les plugins puissent
125
-	// utiliser un necessite php. SPIP procure donc la version php courante du serveur.
126
-	// chaque librairie php est aussi procurée, par exemple 'php:curl'.
127
-	if (isset($ret['prefix']) && $ret['prefix'] == 'spip') {
128
-		$ret['procure']['php'] = ['nom' => 'php', 'version' => phpversion()];
129
-		foreach (get_loaded_extensions() as $ext) {
130
-			$ret['procure']['php:' . $ext] = ['nom' => 'php:' . $ext, 'version' => phpversion($ext)];
131
-		}
132
-	}
133
-	$diff = ($ret != $pcache);
134
-
135
-	if ($diff) {
136
-		$cache[$dir][$plug] = $ret;
94
+    if (!is_readable($file = "$dir$plug/paquet.xml")) {
95
+        return false;
96
+    }
97
+    $time = (int) @filemtime($file);
98
+    if ($time < 0) {
99
+        return false;
100
+    }
101
+    $md5 = md5_file($file);
102
+
103
+    $pcache = $cache[$dir][$plug] ?? ['filemtime' => 0, 'md5_file' => ''];
104
+
105
+    // si le cache est valide
106
+    if (
107
+        (int) $reload <= 0
108
+        && $time > 0
109
+        && $time <= $pcache['filemtime']
110
+        && $md5 == $pcache['md5_file']
111
+    ) {
112
+        return false;
113
+    }
114
+
115
+    // si on arrive pas a lire le fichier, se contenter du cache
116
+    if (!($texte = spip_file_get_contents($file))) {
117
+        return false;
118
+    }
119
+
120
+    $f = charger_fonction('infos_paquet', 'plugins');
121
+    $ret = $f($texte, $plug, $dir);
122
+    $ret['filemtime'] = $time;
123
+    $ret['md5_file'] = $md5;
124
+    // Si on lit le paquet.xml de SPIP, on rajoute un procure php afin que les plugins puissent
125
+    // utiliser un necessite php. SPIP procure donc la version php courante du serveur.
126
+    // chaque librairie php est aussi procurée, par exemple 'php:curl'.
127
+    if (isset($ret['prefix']) && $ret['prefix'] == 'spip') {
128
+        $ret['procure']['php'] = ['nom' => 'php', 'version' => phpversion()];
129
+        foreach (get_loaded_extensions() as $ext) {
130
+            $ret['procure']['php:' . $ext] = ['nom' => 'php:' . $ext, 'version' => phpversion($ext)];
131
+        }
132
+    }
133
+    $diff = ($ret != $pcache);
134
+
135
+    if ($diff) {
136
+        $cache[$dir][$plug] = $ret;
137 137
 #       echo count($cache[$dir]), $dir,$plug, " $reloadc<br>";
138
-	}
138
+    }
139 139
 
140
-	return $diff;
140
+    return $diff;
141 141
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	static $filecache = '';
39 39
 
40 40
 	if ($cache === '') {
41
-		$filecache = _DIR_TMP . 'plugin_xml_cache.gz';
41
+		$filecache = _DIR_TMP.'plugin_xml_cache.gz';
42 42
 		if (is_file($filecache)) {
43 43
 			lire_fichier($filecache, $contenu);
44 44
 			$cache = unserialize($contenu);
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	if (isset($ret['prefix']) && $ret['prefix'] == 'spip') {
128 128
 		$ret['procure']['php'] = ['nom' => 'php', 'version' => phpversion()];
129 129
 		foreach (get_loaded_extensions() as $ext) {
130
-			$ret['procure']['php:' . $ext] = ['nom' => 'php:' . $ext, 'version' => phpversion($ext)];
130
+			$ret['procure']['php:'.$ext] = ['nom' => 'php:'.$ext, 'version' => phpversion($ext)];
131 131
 		}
132 132
 	}
133 133
 	$diff = ($ret != $pcache);
Please login to merge, or discard this patch.
ecrire/plugins/installer.php 2 patches
Indentation   +130 added lines, -130 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
 /**
@@ -53,92 +53,92 @@  discard block
 block discarded – undo
53 53
  */
54 54
 function plugins_installer_dist($plug, $action, $dir_type = '_DIR_PLUGINS') {
55 55
 
56
-	// Charger les informations du XML du plugin et vérification de l'existence d'une installation
57
-	$get_infos = charger_fonction('get_infos', 'plugins');
58
-	$infos = $get_infos($plug, false, constant($dir_type));
59
-	if (!isset($infos['install']) || !$infos['install']) {
60
-		return false;
61
-	}
62
-
63
-	// Passer en chemin absolu si possible, c'est plus efficace
64
-	$dir = str_replace('_DIR_', '_ROOT_', $dir_type);
65
-	if (!defined($dir)) {
66
-		$dir = $dir_type;
67
-	}
68
-	$dir = constant($dir);
69
-	foreach ($infos['install'] as $file) {
70
-		$file = $dir . $plug . '/' . trim($file);
71
-		if (file_exists($file)) {
72
-			include_once($file);
73
-		}
74
-	}
75
-
76
-	// Détermination de la table meta et du nom de la meta plugin
77
-	$table = 'meta';
78
-	if (isset($infos['meta']) && $infos['meta'] !== 'meta') {
79
-		$table = $infos['meta'];
80
-		// S'assurer que les metas de la table spécifique sont bien accessibles dans la globale
81
-		lire_metas($table);
82
-	}
83
-	$nom_meta = $infos['prefix'] . '_base_version';
84
-
85
-	// Détermination de la fonction à appeler et de ses arguments
86
-	$f = $infos['prefix'] . '_install';
87
-	if (!function_exists($f)) {
88
-		$f = isset($infos['schema']) ? 'spip_plugin_install' : '';
89
-		$arg = $infos;
90
-		// On passe la table et la meta pour éviter de les recalculer dans la fonction appelée
91
-		$arg['meta'] = $table;
92
-		$arg['nom_meta'] = $nom_meta;
93
-	} else {
94
-		// Ancienne méthode d'installation - TODO à supprimer à terme
95
-		// stupide: info deja dans le nom
96
-		$arg = $infos['prefix'];
97
-	}
98
-	$version = $infos['schema'] ?? '';
99
-
100
-	if (!$f) {
101
-		// installation sans operation particuliere
102
-		$infos['install_test'] = [true, ''];
103
-		return $infos;
104
-	}
105
-
106
-	// Tester si l'action demandée est nécessaire ou pas.
107
-	$test = $f('test', $arg, $version);
108
-	if ($action == 'uninstall') {
109
-		$test = !$test;
110
-	}
111
-	// Si deja fait, on ne fait rien et on ne dit rien
112
-	if ($test) {
113
-		return true;
114
-	}
115
-
116
-	// Si install et que l'on a la meta d'installation, c'est un upgrade. On le consigne dans $infos
117
-	// pour renvoyer le bon message en retour de la fonction.
118
-	if ($action == 'install' && !empty($GLOBALS[$table][$nom_meta])) {
119
-		$infos['upgrade'] = true;
120
-	}
121
-
122
-	// executer l'installation ou l'inverse
123
-	// et renvoyer la trace (mais il faudrait passer en AJAX plutot)
124
-	ob_start();
125
-	$f($action, $arg, $version);
126
-	$aff = ob_get_contents();
127
-	ob_end_clean();
128
-
129
-	// vider le cache des descriptions de tables a chaque (de)installation
130
-	$trouver_table = charger_fonction('trouver_table', 'base');
131
-	$trouver_table('');
132
-	$infos['install_test'] = [$f('test', $arg, $version), $aff];
133
-
134
-	// Si la table meta n'est pas spip_meta et qu'on est dans la première installation du plugin
135
-	// on force la création du fichier cache à la date du moment.
136
-	// On relit les metas de la table pour être sur que la globale soit à jour pour touch_meta.
137
-	if ($table !== 'meta' && $action == 'install' && empty($infos['upgrade'])) {
138
-		touch_meta(false, $table);
139
-	}
140
-
141
-	return $infos;
56
+    // Charger les informations du XML du plugin et vérification de l'existence d'une installation
57
+    $get_infos = charger_fonction('get_infos', 'plugins');
58
+    $infos = $get_infos($plug, false, constant($dir_type));
59
+    if (!isset($infos['install']) || !$infos['install']) {
60
+        return false;
61
+    }
62
+
63
+    // Passer en chemin absolu si possible, c'est plus efficace
64
+    $dir = str_replace('_DIR_', '_ROOT_', $dir_type);
65
+    if (!defined($dir)) {
66
+        $dir = $dir_type;
67
+    }
68
+    $dir = constant($dir);
69
+    foreach ($infos['install'] as $file) {
70
+        $file = $dir . $plug . '/' . trim($file);
71
+        if (file_exists($file)) {
72
+            include_once($file);
73
+        }
74
+    }
75
+
76
+    // Détermination de la table meta et du nom de la meta plugin
77
+    $table = 'meta';
78
+    if (isset($infos['meta']) && $infos['meta'] !== 'meta') {
79
+        $table = $infos['meta'];
80
+        // S'assurer que les metas de la table spécifique sont bien accessibles dans la globale
81
+        lire_metas($table);
82
+    }
83
+    $nom_meta = $infos['prefix'] . '_base_version';
84
+
85
+    // Détermination de la fonction à appeler et de ses arguments
86
+    $f = $infos['prefix'] . '_install';
87
+    if (!function_exists($f)) {
88
+        $f = isset($infos['schema']) ? 'spip_plugin_install' : '';
89
+        $arg = $infos;
90
+        // On passe la table et la meta pour éviter de les recalculer dans la fonction appelée
91
+        $arg['meta'] = $table;
92
+        $arg['nom_meta'] = $nom_meta;
93
+    } else {
94
+        // Ancienne méthode d'installation - TODO à supprimer à terme
95
+        // stupide: info deja dans le nom
96
+        $arg = $infos['prefix'];
97
+    }
98
+    $version = $infos['schema'] ?? '';
99
+
100
+    if (!$f) {
101
+        // installation sans operation particuliere
102
+        $infos['install_test'] = [true, ''];
103
+        return $infos;
104
+    }
105
+
106
+    // Tester si l'action demandée est nécessaire ou pas.
107
+    $test = $f('test', $arg, $version);
108
+    if ($action == 'uninstall') {
109
+        $test = !$test;
110
+    }
111
+    // Si deja fait, on ne fait rien et on ne dit rien
112
+    if ($test) {
113
+        return true;
114
+    }
115
+
116
+    // Si install et que l'on a la meta d'installation, c'est un upgrade. On le consigne dans $infos
117
+    // pour renvoyer le bon message en retour de la fonction.
118
+    if ($action == 'install' && !empty($GLOBALS[$table][$nom_meta])) {
119
+        $infos['upgrade'] = true;
120
+    }
121
+
122
+    // executer l'installation ou l'inverse
123
+    // et renvoyer la trace (mais il faudrait passer en AJAX plutot)
124
+    ob_start();
125
+    $f($action, $arg, $version);
126
+    $aff = ob_get_contents();
127
+    ob_end_clean();
128
+
129
+    // vider le cache des descriptions de tables a chaque (de)installation
130
+    $trouver_table = charger_fonction('trouver_table', 'base');
131
+    $trouver_table('');
132
+    $infos['install_test'] = [$f('test', $arg, $version), $aff];
133
+
134
+    // Si la table meta n'est pas spip_meta et qu'on est dans la première installation du plugin
135
+    // on force la création du fichier cache à la date du moment.
136
+    // On relit les metas de la table pour être sur que la globale soit à jour pour touch_meta.
137
+    if ($table !== 'meta' && $action == 'install' && empty($infos['upgrade'])) {
138
+        touch_meta(false, $table);
139
+    }
140
+
141
+    return $infos;
142 142
 }
143 143
 
144 144
 /**
@@ -154,24 +154,24 @@  discard block
 block discarded – undo
154 154
  * @return bool|void
155 155
  */
156 156
 function spip_plugin_install($action, $infos, $version_cible) {
157
-	$nom_meta = $infos['nom_meta'];
158
-	$table = $infos['meta'];
159
-	switch ($action) {
160
-		case 'test':
161
-			return (isset($GLOBALS[$table])
162
-				&& isset($GLOBALS[$table][$nom_meta])
163
-				&& spip_version_compare($GLOBALS[$table][$nom_meta], $version_cible, '>='));
164
-		case 'install':
165
-			if (function_exists($upgrade = $infos['prefix'] . '_upgrade')) {
166
-				$upgrade($nom_meta, $version_cible, $table);
167
-			}
168
-			break;
169
-		case 'uninstall':
170
-			if (function_exists($vider_tables = $infos['prefix'] . '_vider_tables')) {
171
-				$vider_tables($nom_meta, $table);
172
-			}
173
-			break;
174
-	}
157
+    $nom_meta = $infos['nom_meta'];
158
+    $table = $infos['meta'];
159
+    switch ($action) {
160
+        case 'test':
161
+            return (isset($GLOBALS[$table])
162
+                && isset($GLOBALS[$table][$nom_meta])
163
+                && spip_version_compare($GLOBALS[$table][$nom_meta], $version_cible, '>='));
164
+        case 'install':
165
+            if (function_exists($upgrade = $infos['prefix'] . '_upgrade')) {
166
+                $upgrade($nom_meta, $version_cible, $table);
167
+            }
168
+            break;
169
+        case 'uninstall':
170
+            if (function_exists($vider_tables = $infos['prefix'] . '_vider_tables')) {
171
+                $vider_tables($nom_meta, $table);
172
+            }
173
+            break;
174
+    }
175 175
 }
176 176
 
177 177
 
@@ -190,29 +190,29 @@  discard block
 block discarded – undo
190 190
  * @return array Tableau des plugins actifs
191 191
  **/
192 192
 function liste_plugin_actifs() {
193
-	$liste = $GLOBALS['meta']['plugin'] ?? '';
194
-	if (!$liste) {
195
-		return [];
196
-	}
197
-	if (!is_array($liste = unserialize($liste))) {
198
-		// compatibilite pre 1.9.2, mettre a jour la meta
199
-		spip_log("MAJ meta plugin vieille version : $liste", 'plugin');
200
-		$new = true;
201
-		[, $liste] = liste_plugin_valides(explode(',', $liste));
202
-	} else {
203
-		$new = false;
204
-		// compat au moment d'une migration depuis version anterieure
205
-		// si pas de dir_type, alors c'est _DIR_PLUGINS
206
-		foreach ($liste as $prefix => $infos) {
207
-			if (!isset($infos['dir_type'])) {
208
-				$liste[$prefix]['dir_type'] = '_DIR_PLUGINS';
209
-				$new = true;
210
-			}
211
-		}
212
-	}
213
-	if ($new) {
214
-		ecrire_meta('plugin', serialize($liste));
215
-	}
216
-
217
-	return $liste;
193
+    $liste = $GLOBALS['meta']['plugin'] ?? '';
194
+    if (!$liste) {
195
+        return [];
196
+    }
197
+    if (!is_array($liste = unserialize($liste))) {
198
+        // compatibilite pre 1.9.2, mettre a jour la meta
199
+        spip_log("MAJ meta plugin vieille version : $liste", 'plugin');
200
+        $new = true;
201
+        [, $liste] = liste_plugin_valides(explode(',', $liste));
202
+    } else {
203
+        $new = false;
204
+        // compat au moment d'une migration depuis version anterieure
205
+        // si pas de dir_type, alors c'est _DIR_PLUGINS
206
+        foreach ($liste as $prefix => $infos) {
207
+            if (!isset($infos['dir_type'])) {
208
+                $liste[$prefix]['dir_type'] = '_DIR_PLUGINS';
209
+                $new = true;
210
+            }
211
+        }
212
+    }
213
+    if ($new) {
214
+        ecrire_meta('plugin', serialize($liste));
215
+    }
216
+
217
+    return $liste;
218 218
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 	}
68 68
 	$dir = constant($dir);
69 69
 	foreach ($infos['install'] as $file) {
70
-		$file = $dir . $plug . '/' . trim($file);
70
+		$file = $dir.$plug.'/'.trim($file);
71 71
 		if (file_exists($file)) {
72 72
 			include_once($file);
73 73
 		}
@@ -80,10 +80,10 @@  discard block
 block discarded – undo
80 80
 		// S'assurer que les metas de la table spécifique sont bien accessibles dans la globale
81 81
 		lire_metas($table);
82 82
 	}
83
-	$nom_meta = $infos['prefix'] . '_base_version';
83
+	$nom_meta = $infos['prefix'].'_base_version';
84 84
 
85 85
 	// Détermination de la fonction à appeler et de ses arguments
86
-	$f = $infos['prefix'] . '_install';
86
+	$f = $infos['prefix'].'_install';
87 87
 	if (!function_exists($f)) {
88 88
 		$f = isset($infos['schema']) ? 'spip_plugin_install' : '';
89 89
 		$arg = $infos;
@@ -162,12 +162,12 @@  discard block
 block discarded – undo
162 162
 				&& isset($GLOBALS[$table][$nom_meta])
163 163
 				&& spip_version_compare($GLOBALS[$table][$nom_meta], $version_cible, '>='));
164 164
 		case 'install':
165
-			if (function_exists($upgrade = $infos['prefix'] . '_upgrade')) {
165
+			if (function_exists($upgrade = $infos['prefix'].'_upgrade')) {
166 166
 				$upgrade($nom_meta, $version_cible, $table);
167 167
 			}
168 168
 			break;
169 169
 		case 'uninstall':
170
-			if (function_exists($vider_tables = $infos['prefix'] . '_vider_tables')) {
170
+			if (function_exists($vider_tables = $infos['prefix'].'_vider_tables')) {
171 171
 				$vider_tables($nom_meta, $table);
172 172
 			}
173 173
 			break;
Please login to merge, or discard this patch.