Completed
Push — master ( 2056af...6c9939 )
by cam
01:09
created
ecrire/inc/distant.php 2 patches
Indentation   +1044 added lines, -1044 removed lines patch added patch discarded remove patch
@@ -16,32 +16,32 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Distant
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
23
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
23
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
24 24
 }
25 25
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
26
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
26
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32
-	define('_INC_DISTANT_MAX_SIZE', 2097152);
32
+    define('_INC_DISTANT_MAX_SIZE', 2097152);
33 33
 }
34 34
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
35
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
35
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38 38
 define('_REGEXP_COPIE_LOCALE', ',' 	.
39
-	preg_replace(
40
-		'@^https?:@',
41
-		'https?:',
42
-		(isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
-	)
44
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
39
+    preg_replace(
40
+        '@^https?:@',
41
+        'https?:',
42
+        (isset($GLOBALS['meta']['adresse_site']) ? $GLOBALS['meta']['adresse_site'] : '')
43
+    )
44
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
45 45
 
46 46
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
47 47
 
@@ -68,89 +68,89 @@  discard block
 block discarded – undo
68 68
  */
69 69
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null) {
70 70
 
71
-	// si c'est la protection de soi-meme, retourner le path
72
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
-
75
-		return @file_exists($source) ? $source : false;
76
-	}
77
-
78
-	if (is_null($local)) {
79
-		$local = fichier_copie_locale($source);
80
-	} else {
81
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
-			$local = substr($local, strlen(_DIR_RACINE));
83
-		}
84
-	}
85
-
86
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
-	// par exemple un fichier qui ne figure pas dans nos documents ;
88
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
-	if (!$local) {
90
-		return false;
91
-	}
92
-
93
-	$localrac = _DIR_RACINE . $local;
94
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
95
-
96
-	// test d'existence du fichier
97
-	if ($mode === 'test') {
98
-		return $t ? $local : '';
99
-	}
100
-
101
-	// sinon voir si on doit/peut le telecharger
102
-	if ($local === $source or !tester_url_absolue($source)) {
103
-		return $local;
104
-	}
105
-
106
-	if ($mode === 'modif' or !$t) {
107
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
-		// et des eventuelles recuperations concurantes
109
-		include_spip('inc/acces');
110
-		if (!$taille_max) {
111
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
112
-		}
113
-		$res = recuperer_url(
114
-			$source,
115
-			['file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
116
-		);
117
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
119
-		}
120
-		else {
121
-			spip_log("copie_locale : recuperation $source sur $localrac OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
122
-		}
123
-		if (!$res or !$res['length']) {
124
-			// si $t c'est sans doute juste un not-modified-since
125
-			return $t ? $local : false;
126
-		}
127
-
128
-		// si on retrouve l'extension
129
-		if (
130
-			!empty($res['headers'])
131
-			and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
132
-		) {
133
-			if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
134
-				$sanitizer($localrac);
135
-			}
136
-		}
137
-
138
-		// pour une eventuelle indexation
139
-		pipeline(
140
-			'post_edition',
141
-			[
142
-				'args' => [
143
-					'operation' => 'copie_locale',
144
-					'source' => $source,
145
-					'fichier' => $local,
146
-					'http_res' => $res['length'],
147
-				],
148
-				'data' => null
149
-			]
150
-		);
151
-	}
152
-
153
-	return $local;
71
+    // si c'est la protection de soi-meme, retourner le path
72
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
74
+
75
+        return @file_exists($source) ? $source : false;
76
+    }
77
+
78
+    if (is_null($local)) {
79
+        $local = fichier_copie_locale($source);
80
+    } else {
81
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
82
+            $local = substr($local, strlen(_DIR_RACINE));
83
+        }
84
+    }
85
+
86
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
87
+    // par exemple un fichier qui ne figure pas dans nos documents ;
88
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
89
+    if (!$local) {
90
+        return false;
91
+    }
92
+
93
+    $localrac = _DIR_RACINE . $local;
94
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
95
+
96
+    // test d'existence du fichier
97
+    if ($mode === 'test') {
98
+        return $t ? $local : '';
99
+    }
100
+
101
+    // sinon voir si on doit/peut le telecharger
102
+    if ($local === $source or !tester_url_absolue($source)) {
103
+        return $local;
104
+    }
105
+
106
+    if ($mode === 'modif' or !$t) {
107
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
108
+        // et des eventuelles recuperations concurantes
109
+        include_spip('inc/acces');
110
+        if (!$taille_max) {
111
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
112
+        }
113
+        $res = recuperer_url(
114
+            $source,
115
+            ['file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
116
+        );
117
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
+            spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
119
+        }
120
+        else {
121
+            spip_log("copie_locale : recuperation $source sur $localrac OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
122
+        }
123
+        if (!$res or !$res['length']) {
124
+            // si $t c'est sans doute juste un not-modified-since
125
+            return $t ? $local : false;
126
+        }
127
+
128
+        // si on retrouve l'extension
129
+        if (
130
+            !empty($res['headers'])
131
+            and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
132
+        ) {
133
+            if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
134
+                $sanitizer($localrac);
135
+            }
136
+        }
137
+
138
+        // pour une eventuelle indexation
139
+        pipeline(
140
+            'post_edition',
141
+            [
142
+                'args' => [
143
+                    'operation' => 'copie_locale',
144
+                    'source' => $source,
145
+                    'fichier' => $local,
146
+                    'http_res' => $res['length'],
147
+                ],
148
+                'data' => null
149
+            ]
150
+        );
151
+    }
152
+
153
+    return $local;
154 154
 }
155 155
 
156 156
 /**
@@ -165,99 +165,99 @@  discard block
 block discarded – undo
165 165
  *   url ou false en cas d'echec
166 166
  */
167 167
 function valider_url_distante($url, $known_hosts = []) {
168
-	if (!function_exists('protocole_verifier')) {
169
-		include_spip('inc/filtres_mini');
170
-	}
171
-
172
-	if (!protocole_verifier($url, ['http', 'https'])) {
173
-		return false;
174
-	}
175
-
176
-	$parsed_url = parse_url($url);
177
-	if (!$parsed_url or empty($parsed_url['host'])) {
178
-		return false;
179
-	}
180
-
181
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
182
-		return false;
183
-	}
184
-
185
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
186
-		return false;
187
-	}
188
-
189
-	if (!is_array($known_hosts)) {
190
-		$known_hosts = [$known_hosts];
191
-	}
192
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
193
-	$known_hosts[] = url_de_base();
194
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
195
-
196
-	$is_known_host = false;
197
-	foreach ($known_hosts as $known_host) {
198
-		$parse_known = parse_url($known_host);
199
-		if (
200
-			$parse_known
201
-			and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
202
-		) {
203
-			$is_known_host = true;
204
-			break;
205
-		}
206
-	}
207
-
208
-	if (!$is_known_host) {
209
-		$host = trim($parsed_url['host'], '.');
210
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
211
-			$ip = gethostbyname($host);
212
-			if ($ip === $host) {
213
-				// Error condition for gethostbyname()
214
-				$ip = false;
215
-			}
216
-			if ($records = dns_get_record($host)) {
217
-				foreach ($records as $record) {
218
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
219
-					// se fasse sur la meme IP
220
-					if ($record['ttl'] < 10) {
221
-						$ip = false;
222
-						break;
223
-					}
224
-				}
225
-			}
226
-			else {
227
-				$ip = false;
228
-			}
229
-		}
230
-		if ($ip) {
231
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
232
-				return false;
233
-			}
234
-		}
235
-	}
236
-
237
-	if (empty($parsed_url['port'])) {
238
-		return $url;
239
-	}
240
-
241
-	$port = $parsed_url['port'];
242
-	if ($port === 80  or $port === 443  or $port === 8080) {
243
-		return $url;
244
-	}
245
-
246
-	if ($is_known_host) {
247
-		foreach ($known_hosts as $known_host) {
248
-			$parse_known = parse_url($known_host);
249
-			if (
250
-				$parse_known
251
-				and !empty($parse_known['port'])
252
-				and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
253
-				and $parse_known['port'] == $port
254
-			) {
255
-				return $url;
256
-			}
257
-		}
258
-	}
259
-
260
-	return false;
168
+    if (!function_exists('protocole_verifier')) {
169
+        include_spip('inc/filtres_mini');
170
+    }
171
+
172
+    if (!protocole_verifier($url, ['http', 'https'])) {
173
+        return false;
174
+    }
175
+
176
+    $parsed_url = parse_url($url);
177
+    if (!$parsed_url or empty($parsed_url['host'])) {
178
+        return false;
179
+    }
180
+
181
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
182
+        return false;
183
+    }
184
+
185
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
186
+        return false;
187
+    }
188
+
189
+    if (!is_array($known_hosts)) {
190
+        $known_hosts = [$known_hosts];
191
+    }
192
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
193
+    $known_hosts[] = url_de_base();
194
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
195
+
196
+    $is_known_host = false;
197
+    foreach ($known_hosts as $known_host) {
198
+        $parse_known = parse_url($known_host);
199
+        if (
200
+            $parse_known
201
+            and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
202
+        ) {
203
+            $is_known_host = true;
204
+            break;
205
+        }
206
+    }
207
+
208
+    if (!$is_known_host) {
209
+        $host = trim($parsed_url['host'], '.');
210
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
211
+            $ip = gethostbyname($host);
212
+            if ($ip === $host) {
213
+                // Error condition for gethostbyname()
214
+                $ip = false;
215
+            }
216
+            if ($records = dns_get_record($host)) {
217
+                foreach ($records as $record) {
218
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
219
+                    // se fasse sur la meme IP
220
+                    if ($record['ttl'] < 10) {
221
+                        $ip = false;
222
+                        break;
223
+                    }
224
+                }
225
+            }
226
+            else {
227
+                $ip = false;
228
+            }
229
+        }
230
+        if ($ip) {
231
+            if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
232
+                return false;
233
+            }
234
+        }
235
+    }
236
+
237
+    if (empty($parsed_url['port'])) {
238
+        return $url;
239
+    }
240
+
241
+    $port = $parsed_url['port'];
242
+    if ($port === 80  or $port === 443  or $port === 8080) {
243
+        return $url;
244
+    }
245
+
246
+    if ($is_known_host) {
247
+        foreach ($known_hosts as $known_host) {
248
+            $parse_known = parse_url($known_host);
249
+            if (
250
+                $parse_known
251
+                and !empty($parse_known['port'])
252
+                and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
253
+                and $parse_known['port'] == $port
254
+            ) {
255
+                return $url;
256
+            }
257
+        }
258
+    }
259
+
260
+    return false;
261 261
 }
262 262
 
263 263
 /**
@@ -277,86 +277,86 @@  discard block
 block discarded – undo
277 277
  */
278 278
 function prepare_donnees_post($donnees, $boundary = '') {
279 279
 
280
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
281
-	// pour un appel soap par exemple
282
-	// l'entete est separe des donnees par un double retour a la ligne
283
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
284
-	if (is_string($donnees) && strlen($donnees)) {
285
-		$entete = '';
286
-		// on repasse tous les \r\n et \r en simples \n
287
-		$donnees = str_replace("\r\n", "\n", $donnees);
288
-		$donnees = str_replace("\r", "\n", $donnees);
289
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
290
-		$p = strpos($donnees, "\n\n");
291
-		if ($p !== false) {
292
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
293
-			$donnees = substr($donnees, $p + 2);
294
-		}
295
-		$chaine = str_replace("\n", "\r\n", $donnees);
296
-	} else {
297
-		/* boundary automatique */
298
-		// Si on a plus de 500 octects de donnees, on "boundarise"
299
-		if ($boundary === '') {
300
-			$taille = 0;
301
-			foreach ($donnees as $cle => $valeur) {
302
-				if (is_array($valeur)) {
303
-					foreach ($valeur as $val2) {
304
-						$taille += strlen($val2);
305
-					}
306
-				} else {
307
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
308
-					$taille += strlen($valeur);
309
-				}
310
-			}
311
-			if ($taille > 500) {
312
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
313
-			}
314
-		}
315
-
316
-		if (is_string($boundary) and strlen($boundary)) {
317
-			// fabrique une chaine HTTP pour un POST avec boundary
318
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
319
-			$chaine = '';
320
-			if (is_array($donnees)) {
321
-				foreach ($donnees as $cle => $valeur) {
322
-					if (is_array($valeur)) {
323
-						foreach ($valeur as $val2) {
324
-							$chaine .= "\r\n--$boundary\r\n";
325
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
326
-							$chaine .= "\r\n";
327
-							$chaine .= $val2;
328
-						}
329
-					} else {
330
-						$chaine .= "\r\n--$boundary\r\n";
331
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
332
-						$chaine .= "\r\n";
333
-						$chaine .= $valeur;
334
-					}
335
-				}
336
-				$chaine .= "\r\n--$boundary\r\n";
337
-			}
338
-		} else {
339
-			// fabrique une chaine HTTP simple pour un POST
340
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
341
-			$chaine = [];
342
-			if (is_array($donnees)) {
343
-				foreach ($donnees as $cle => $valeur) {
344
-					if (is_array($valeur)) {
345
-						foreach ($valeur as $val2) {
346
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
347
-						}
348
-					} else {
349
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
350
-					}
351
-				}
352
-				$chaine = implode('&', $chaine);
353
-			} else {
354
-				$chaine = $donnees;
355
-			}
356
-		}
357
-	}
358
-
359
-	return [$entete, $chaine];
280
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
281
+    // pour un appel soap par exemple
282
+    // l'entete est separe des donnees par un double retour a la ligne
283
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
284
+    if (is_string($donnees) && strlen($donnees)) {
285
+        $entete = '';
286
+        // on repasse tous les \r\n et \r en simples \n
287
+        $donnees = str_replace("\r\n", "\n", $donnees);
288
+        $donnees = str_replace("\r", "\n", $donnees);
289
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
290
+        $p = strpos($donnees, "\n\n");
291
+        if ($p !== false) {
292
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
293
+            $donnees = substr($donnees, $p + 2);
294
+        }
295
+        $chaine = str_replace("\n", "\r\n", $donnees);
296
+    } else {
297
+        /* boundary automatique */
298
+        // Si on a plus de 500 octects de donnees, on "boundarise"
299
+        if ($boundary === '') {
300
+            $taille = 0;
301
+            foreach ($donnees as $cle => $valeur) {
302
+                if (is_array($valeur)) {
303
+                    foreach ($valeur as $val2) {
304
+                        $taille += strlen($val2);
305
+                    }
306
+                } else {
307
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
308
+                    $taille += strlen($valeur);
309
+                }
310
+            }
311
+            if ($taille > 500) {
312
+                $boundary = substr(md5(rand() . 'spip'), 0, 8);
313
+            }
314
+        }
315
+
316
+        if (is_string($boundary) and strlen($boundary)) {
317
+            // fabrique une chaine HTTP pour un POST avec boundary
318
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
319
+            $chaine = '';
320
+            if (is_array($donnees)) {
321
+                foreach ($donnees as $cle => $valeur) {
322
+                    if (is_array($valeur)) {
323
+                        foreach ($valeur as $val2) {
324
+                            $chaine .= "\r\n--$boundary\r\n";
325
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
326
+                            $chaine .= "\r\n";
327
+                            $chaine .= $val2;
328
+                        }
329
+                    } else {
330
+                        $chaine .= "\r\n--$boundary\r\n";
331
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
332
+                        $chaine .= "\r\n";
333
+                        $chaine .= $valeur;
334
+                    }
335
+                }
336
+                $chaine .= "\r\n--$boundary\r\n";
337
+            }
338
+        } else {
339
+            // fabrique une chaine HTTP simple pour un POST
340
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
341
+            $chaine = [];
342
+            if (is_array($donnees)) {
343
+                foreach ($donnees as $cle => $valeur) {
344
+                    if (is_array($valeur)) {
345
+                        foreach ($valeur as $val2) {
346
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
347
+                        }
348
+                    } else {
349
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
350
+                    }
351
+                }
352
+                $chaine = implode('&', $chaine);
353
+            } else {
354
+                $chaine = $donnees;
355
+            }
356
+        }
357
+    }
358
+
359
+    return [$entete, $chaine];
360 360
 }
361 361
 
362 362
 /**
@@ -370,22 +370,22 @@  discard block
 block discarded – undo
370 370
  */
371 371
 function url_to_ascii($url_idn) {
372 372
 
373
-	if ($parts = parse_url($url_idn)) {
374
-		$host = $parts['host'];
375
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
376
-			include_spip('inc/idna_convert.class');
377
-			$IDN = new idna_convert();
378
-			$host_ascii = $IDN->encode($host);
379
-			$url_idn = explode($host, $url_idn, 2);
380
-			$url_idn = implode($host_ascii, $url_idn);
381
-		}
382
-		// et on urlencode les char utf si besoin dans le path
383
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function ($match) {
384
- return urlencode($match[0]);
385
-		}, $url_idn);
386
-	}
387
-
388
-	return $url_idn;
373
+    if ($parts = parse_url($url_idn)) {
374
+        $host = $parts['host'];
375
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
376
+            include_spip('inc/idna_convert.class');
377
+            $IDN = new idna_convert();
378
+            $host_ascii = $IDN->encode($host);
379
+            $url_idn = explode($host, $url_idn, 2);
380
+            $url_idn = implode($host_ascii, $url_idn);
381
+        }
382
+        // et on urlencode les char utf si besoin dans le path
383
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', function ($match) {
384
+    return urlencode($match[0]);
385
+        }, $url_idn);
386
+    }
387
+
388
+    return $url_idn;
389 389
 }
390 390
 
391 391
 /**
@@ -426,197 +426,197 @@  discard block
 block discarded – undo
426 426
  *     string file : nom du fichier si enregistre dans un fichier
427 427
  */
428 428
 function recuperer_url($url, $options = []) {
429
-	// Conserve la mémoire de la méthode fournit éventuellement
430
-	$methode_demandee = $options['methode'] ?? '';
431
-	$default = [
432
-		'transcoder' => false,
433
-		'methode' => 'GET',
434
-		'taille_max' => null,
435
-		'headers' => [],
436
-		'datas' => '',
437
-		'boundary' => '',
438
-		'refuser_gz' => false,
439
-		'if_modified_since' => '',
440
-		'uri_referer' => '',
441
-		'file' => '',
442
-		'follow_location' => 10,
443
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
444
-	];
445
-	$options = array_merge($default, $options);
446
-	// copier directement dans un fichier ?
447
-	$copy = $options['file'];
448
-
449
-	if ($options['methode'] == 'HEAD') {
450
-		$options['taille_max'] = 0;
451
-	}
452
-	if (is_null($options['taille_max'])) {
453
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
454
-	}
455
-
456
-
457
-	// Ajout des en-têtes spécifiques si besoin
458
-	$head_add = '';
459
-	if (!empty($options['headers'])) {
460
-		foreach ($options['headers'] as $champ => $valeur) {
461
-			$head_add .= $champ . ': ' . $valeur . "\r\n";
462
-		}
463
-		// ne pas le repasser a recuperer_url si on follow un location, car ils seront dans datas
464
-		unset($options['headers']);
465
-	}
466
-
467
-	if (!empty($options['datas'])) {
468
-		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
469
-		$head .= $head_add;
470
-		if (stripos($head, 'Content-Length:') === false) {
471
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
472
-		}
473
-		$options['datas'] = $head . "\r\n" . $postdata;
474
-		if (
475
-			strlen($postdata)
476
-			and !$methode_demandee
477
-		) {
478
-			$options['methode'] = 'POST';
479
-		}
480
-	} elseif ($head_add) {
481
-		$options['datas'] = $head_add . "\r\n";
482
-	}
483
-
484
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
485
-	$url = preg_replace(',^feed://,i', 'http://', $url);
486
-	if (!tester_url_absolue($url)) {
487
-		$url = 'http://' . $url;
488
-	} elseif (strncmp($url, '//', 2) == 0) {
489
-		$url = 'http:' . $url;
490
-	}
491
-
492
-	$url = url_to_ascii($url);
493
-
494
-	$result = [
495
-		'status' => 0,
496
-		'headers' => '',
497
-		'page' => '',
498
-		'length' => 0,
499
-		'last_modified' => '',
500
-		'location' => '',
501
-		'url' => $url
502
-	];
503
-
504
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
505
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
506
-
507
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
508
-	list($handle, $fopen) = init_http(
509
-		$options['methode'],
510
-		$url,
511
-		$refuser_gz,
512
-		$options['uri_referer'],
513
-		$options['datas'],
514
-		$options['version_http'],
515
-		$options['if_modified_since']
516
-	);
517
-	if (!$handle) {
518
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
519
-
520
-		return false;
521
-	}
522
-
523
-	// Sauf en fopen, envoyer le flux d'entree
524
-	// et recuperer les en-tetes de reponses
525
-	if (!$fopen) {
526
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
527
-		if (!$res) {
528
-			fclose($handle);
529
-			$t = @parse_url($url);
530
-			$host = $t['host'];
531
-			// Chinoisierie inexplicable pour contrer
532
-			// les actions liberticides de l'empire du milieu
533
-			if (
534
-				!need_proxy($host)
535
-				and $res = @file_get_contents($url)
536
-			) {
537
-				$result['length'] = strlen($res);
538
-				if ($copy) {
539
-					ecrire_fichier($copy, $res);
540
-					$result['file'] = $copy;
541
-				} else {
542
-					$result['page'] = $res;
543
-				}
544
-				$res = [
545
-					'status' => 200,
546
-				];
547
-			} else {
548
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
549
-				return false;
550
-			}
551
-		} elseif ($res['location'] and $options['follow_location']) {
552
-			$options['follow_location']--;
553
-			fclose($handle);
554
-			include_spip('inc/filtres');
555
-			$url = suivre_lien($url, $res['location']);
556
-			spip_log("recuperer_url recommence sur $url", 'distant');
557
-
558
-			return recuperer_url($url, $options);
559
-		} elseif ($res['status'] !== 200) {
560
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
561
-		}
562
-		$result['status'] = $res['status'];
563
-		if (isset($res['headers'])) {
564
-			$result['headers'] = $res['headers'];
565
-		}
566
-		if (isset($res['last_modified'])) {
567
-			$result['last_modified'] = $res['last_modified'];
568
-		}
569
-		if (isset($res['location'])) {
570
-			$result['location'] = $res['location'];
571
-		}
572
-	}
573
-
574
-	// on ne veut que les entetes
575
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
576
-		return $result;
577
-	}
578
-
579
-
580
-	// s'il faut deballer, le faire via un fichier temporaire
581
-	// sinon la memoire explose pour les gros flux
582
-
583
-	$gz = false;
584
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
585
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
586
-	}
587
-
588
-	// si on a pas deja recuperer le contenu par une methode detournee
589
-	if (!$result['length']) {
590
-		$res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
591
-		fclose($handle);
592
-		if ($copy) {
593
-			$result['length'] = $res;
594
-			$result['file'] = $copy;
595
-		} elseif ($res) {
596
-			$result['page'] = &$res;
597
-			$result['length'] = strlen($result['page']);
598
-		}
599
-		if (!$result['status']) {
600
-			$result['status'] = 200; // on a reussi, donc !
601
-		}
602
-	}
603
-	if (!$result['page']) {
604
-		return $result;
605
-	}
606
-
607
-	// Decompresser au besoin
608
-	if ($gz) {
609
-		$result['page'] = implode('', gzfile($gz));
610
-		supprimer_fichier($gz);
611
-	}
612
-
613
-	// Faut-il l'importer dans notre charset local ?
614
-	if ($options['transcoder']) {
615
-		include_spip('inc/charsets');
616
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
617
-	}
618
-
619
-	return $result;
429
+    // Conserve la mémoire de la méthode fournit éventuellement
430
+    $methode_demandee = $options['methode'] ?? '';
431
+    $default = [
432
+        'transcoder' => false,
433
+        'methode' => 'GET',
434
+        'taille_max' => null,
435
+        'headers' => [],
436
+        'datas' => '',
437
+        'boundary' => '',
438
+        'refuser_gz' => false,
439
+        'if_modified_since' => '',
440
+        'uri_referer' => '',
441
+        'file' => '',
442
+        'follow_location' => 10,
443
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
444
+    ];
445
+    $options = array_merge($default, $options);
446
+    // copier directement dans un fichier ?
447
+    $copy = $options['file'];
448
+
449
+    if ($options['methode'] == 'HEAD') {
450
+        $options['taille_max'] = 0;
451
+    }
452
+    if (is_null($options['taille_max'])) {
453
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
454
+    }
455
+
456
+
457
+    // Ajout des en-têtes spécifiques si besoin
458
+    $head_add = '';
459
+    if (!empty($options['headers'])) {
460
+        foreach ($options['headers'] as $champ => $valeur) {
461
+            $head_add .= $champ . ': ' . $valeur . "\r\n";
462
+        }
463
+        // ne pas le repasser a recuperer_url si on follow un location, car ils seront dans datas
464
+        unset($options['headers']);
465
+    }
466
+
467
+    if (!empty($options['datas'])) {
468
+        list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
469
+        $head .= $head_add;
470
+        if (stripos($head, 'Content-Length:') === false) {
471
+            $head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
472
+        }
473
+        $options['datas'] = $head . "\r\n" . $postdata;
474
+        if (
475
+            strlen($postdata)
476
+            and !$methode_demandee
477
+        ) {
478
+            $options['methode'] = 'POST';
479
+        }
480
+    } elseif ($head_add) {
481
+        $options['datas'] = $head_add . "\r\n";
482
+    }
483
+
484
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
485
+    $url = preg_replace(',^feed://,i', 'http://', $url);
486
+    if (!tester_url_absolue($url)) {
487
+        $url = 'http://' . $url;
488
+    } elseif (strncmp($url, '//', 2) == 0) {
489
+        $url = 'http:' . $url;
490
+    }
491
+
492
+    $url = url_to_ascii($url);
493
+
494
+    $result = [
495
+        'status' => 0,
496
+        'headers' => '',
497
+        'page' => '',
498
+        'length' => 0,
499
+        'last_modified' => '',
500
+        'location' => '',
501
+        'url' => $url
502
+    ];
503
+
504
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
505
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
506
+
507
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
508
+    list($handle, $fopen) = init_http(
509
+        $options['methode'],
510
+        $url,
511
+        $refuser_gz,
512
+        $options['uri_referer'],
513
+        $options['datas'],
514
+        $options['version_http'],
515
+        $options['if_modified_since']
516
+    );
517
+    if (!$handle) {
518
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
519
+
520
+        return false;
521
+    }
522
+
523
+    // Sauf en fopen, envoyer le flux d'entree
524
+    // et recuperer les en-tetes de reponses
525
+    if (!$fopen) {
526
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
527
+        if (!$res) {
528
+            fclose($handle);
529
+            $t = @parse_url($url);
530
+            $host = $t['host'];
531
+            // Chinoisierie inexplicable pour contrer
532
+            // les actions liberticides de l'empire du milieu
533
+            if (
534
+                !need_proxy($host)
535
+                and $res = @file_get_contents($url)
536
+            ) {
537
+                $result['length'] = strlen($res);
538
+                if ($copy) {
539
+                    ecrire_fichier($copy, $res);
540
+                    $result['file'] = $copy;
541
+                } else {
542
+                    $result['page'] = $res;
543
+                }
544
+                $res = [
545
+                    'status' => 200,
546
+                ];
547
+            } else {
548
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
549
+                return false;
550
+            }
551
+        } elseif ($res['location'] and $options['follow_location']) {
552
+            $options['follow_location']--;
553
+            fclose($handle);
554
+            include_spip('inc/filtres');
555
+            $url = suivre_lien($url, $res['location']);
556
+            spip_log("recuperer_url recommence sur $url", 'distant');
557
+
558
+            return recuperer_url($url, $options);
559
+        } elseif ($res['status'] !== 200) {
560
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
561
+        }
562
+        $result['status'] = $res['status'];
563
+        if (isset($res['headers'])) {
564
+            $result['headers'] = $res['headers'];
565
+        }
566
+        if (isset($res['last_modified'])) {
567
+            $result['last_modified'] = $res['last_modified'];
568
+        }
569
+        if (isset($res['location'])) {
570
+            $result['location'] = $res['location'];
571
+        }
572
+    }
573
+
574
+    // on ne veut que les entetes
575
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
576
+        return $result;
577
+    }
578
+
579
+
580
+    // s'il faut deballer, le faire via un fichier temporaire
581
+    // sinon la memoire explose pour les gros flux
582
+
583
+    $gz = false;
584
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
585
+        $gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
586
+    }
587
+
588
+    // si on a pas deja recuperer le contenu par une methode detournee
589
+    if (!$result['length']) {
590
+        $res = recuperer_body($handle, $options['taille_max'], $gz ? $gz : $copy);
591
+        fclose($handle);
592
+        if ($copy) {
593
+            $result['length'] = $res;
594
+            $result['file'] = $copy;
595
+        } elseif ($res) {
596
+            $result['page'] = &$res;
597
+            $result['length'] = strlen($result['page']);
598
+        }
599
+        if (!$result['status']) {
600
+            $result['status'] = 200; // on a reussi, donc !
601
+        }
602
+    }
603
+    if (!$result['page']) {
604
+        return $result;
605
+    }
606
+
607
+    // Decompresser au besoin
608
+    if ($gz) {
609
+        $result['page'] = implode('', gzfile($gz));
610
+        supprimer_fichier($gz);
611
+    }
612
+
613
+    // Faut-il l'importer dans notre charset local ?
614
+    if ($options['transcoder']) {
615
+        include_spip('inc/charsets');
616
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
617
+    }
618
+
619
+    return $result;
620 620
 }
621 621
 
622 622
 /**
@@ -632,73 +632,73 @@  discard block
 block discarded – undo
632 632
  * @return array|bool|mixed
633 633
  */
634 634
 function recuperer_url_cache($url, $options = []) {
635
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
636
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
637
-	}
638
-	$default = [
639
-		'transcoder' => false,
640
-		'methode' => 'GET',
641
-		'taille_max' => null,
642
-		'datas' => '',
643
-		'boundary' => '',
644
-		'refuser_gz' => false,
645
-		'if_modified_since' => '',
646
-		'uri_referer' => '',
647
-		'file' => '',
648
-		'follow_location' => 10,
649
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
650
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
651
-	];
652
-	$options = array_merge($default, $options);
653
-
654
-	// cas ou il n'est pas possible de cacher
655
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
656
-		return recuperer_url($url, $options);
657
-	}
658
-
659
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
660
-	static $errors = [];
661
-	if (isset($errors[$url])) {
662
-		return $errors[$url];
663
-	}
664
-
665
-	$sig = $options;
666
-	unset($sig['if_modified_since']);
667
-	unset($sig['delai_cache']);
668
-	$sig['url'] = $url;
669
-
670
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
671
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
672
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
673
-	$cache = "$sub$cache";
674
-
675
-	$res = false;
676
-	$is_cached = file_exists($cache);
677
-	if (
678
-		$is_cached
679
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
680
-	) {
681
-		lire_fichier($cache, $res);
682
-		if ($res = unserialize($res)) {
683
-			// mettre le last_modified et le status=304 ?
684
-		}
685
-	}
686
-	if (!$res) {
687
-		$res = recuperer_url($url, $options);
688
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
689
-		if (!$res) {
690
-			if ($is_cached) {
691
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
692
-				lire_fichier($cache, $res);
693
-				$res = unserialize($res);
694
-			}
695
-
696
-			return $errors[$url] = $res;
697
-		}
698
-		ecrire_fichier($cache, serialize($res));
699
-	}
700
-
701
-	return $res;
635
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
636
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
637
+    }
638
+    $default = [
639
+        'transcoder' => false,
640
+        'methode' => 'GET',
641
+        'taille_max' => null,
642
+        'datas' => '',
643
+        'boundary' => '',
644
+        'refuser_gz' => false,
645
+        'if_modified_since' => '',
646
+        'uri_referer' => '',
647
+        'file' => '',
648
+        'follow_location' => 10,
649
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
650
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
651
+    ];
652
+    $options = array_merge($default, $options);
653
+
654
+    // cas ou il n'est pas possible de cacher
655
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
656
+        return recuperer_url($url, $options);
657
+    }
658
+
659
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
660
+    static $errors = [];
661
+    if (isset($errors[$url])) {
662
+        return $errors[$url];
663
+    }
664
+
665
+    $sig = $options;
666
+    unset($sig['if_modified_since']);
667
+    unset($sig['delai_cache']);
668
+    $sig['url'] = $url;
669
+
670
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
671
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
672
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
673
+    $cache = "$sub$cache";
674
+
675
+    $res = false;
676
+    $is_cached = file_exists($cache);
677
+    if (
678
+        $is_cached
679
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
680
+    ) {
681
+        lire_fichier($cache, $res);
682
+        if ($res = unserialize($res)) {
683
+            // mettre le last_modified et le status=304 ?
684
+        }
685
+    }
686
+    if (!$res) {
687
+        $res = recuperer_url($url, $options);
688
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
689
+        if (!$res) {
690
+            if ($is_cached) {
691
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
692
+                lire_fichier($cache, $res);
693
+                $res = unserialize($res);
694
+            }
695
+
696
+            return $errors[$url] = $res;
697
+        }
698
+        ecrire_fichier($cache, serialize($res));
699
+    }
700
+
701
+    return $res;
702 702
 }
703 703
 
704 704
 /**
@@ -716,41 +716,41 @@  discard block
 block discarded – undo
716 716
  *   string contenu de la resource
717 717
  */
718 718
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
719
-	$taille = 0;
720
-	$result = '';
721
-	$fp = false;
722
-	if ($fichier) {
723
-		include_spip('inc/acces');
724
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
725
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
726
-		if (!$fp and file_exists($fichier)) {
727
-			return filesize($fichier);
728
-		}
729
-		if (!$fp) {
730
-			return false;
731
-		}
732
-		$result = 0; // on renvoie la taille du fichier
733
-	}
734
-	while (!feof($handle) and $taille < $taille_max) {
735
-		$res = fread($handle, 16384);
736
-		$taille += strlen($res);
737
-		if ($fp) {
738
-			fwrite($fp, $res);
739
-			$result = $taille;
740
-		} else {
741
-			$result .= $res;
742
-		}
743
-	}
744
-	if ($fp) {
745
-		spip_fclose_unlock($fp);
746
-		spip_unlink($fichier);
747
-		@rename($tmpfile, $fichier);
748
-		if (!file_exists($fichier)) {
749
-			return false;
750
-		}
751
-	}
752
-
753
-	return $result;
719
+    $taille = 0;
720
+    $result = '';
721
+    $fp = false;
722
+    if ($fichier) {
723
+        include_spip('inc/acces');
724
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
725
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
726
+        if (!$fp and file_exists($fichier)) {
727
+            return filesize($fichier);
728
+        }
729
+        if (!$fp) {
730
+            return false;
731
+        }
732
+        $result = 0; // on renvoie la taille du fichier
733
+    }
734
+    while (!feof($handle) and $taille < $taille_max) {
735
+        $res = fread($handle, 16384);
736
+        $taille += strlen($res);
737
+        if ($fp) {
738
+            fwrite($fp, $res);
739
+            $result = $taille;
740
+        } else {
741
+            $result .= $res;
742
+        }
743
+    }
744
+    if ($fp) {
745
+        spip_fclose_unlock($fp);
746
+        spip_unlink($fichier);
747
+        @rename($tmpfile, $fichier);
748
+        if (!file_exists($fichier)) {
749
+            return false;
750
+        }
751
+    }
752
+
753
+    return $result;
754 754
 }
755 755
 
756 756
 /**
@@ -772,35 +772,35 @@  discard block
 block discarded – undo
772 772
  *   string location
773 773
  */
774 774
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
775
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
776
-
777
-	$s = @trim(fgets($handle, 16384));
778
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
779
-		return false;
780
-	}
781
-	$result['status'] = intval($r[1]);
782
-	while ($s = trim(fgets($handle, 16384))) {
783
-		$result['headers'][] = $s . "\n";
784
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
785
-		list(, $d, $v) = $r;
786
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
787
-			$result['location'] = $v;
788
-		} elseif ($d == 'Last-Modified') {
789
-			$result['last_modified'] = strtotime($v);
790
-		}
791
-	}
792
-	if (
793
-		$if_modified_since
794
-		and $result['last_modified']
795
-		and $if_modified_since > $result['last_modified']
796
-		and $result['status'] == 200
797
-	) {
798
-		$result['status'] = 304;
799
-	}
800
-
801
-	$result['headers'] = implode('', $result['headers']);
802
-
803
-	return $result;
775
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
776
+
777
+    $s = @trim(fgets($handle, 16384));
778
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
779
+        return false;
780
+    }
781
+    $result['status'] = intval($r[1]);
782
+    while ($s = trim(fgets($handle, 16384))) {
783
+        $result['headers'][] = $s . "\n";
784
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
785
+        list(, $d, $v) = $r;
786
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
787
+            $result['location'] = $v;
788
+        } elseif ($d == 'Last-Modified') {
789
+            $result['last_modified'] = strtotime($v);
790
+        }
791
+    }
792
+    if (
793
+        $if_modified_since
794
+        and $result['last_modified']
795
+        and $if_modified_since > $result['last_modified']
796
+        and $result['status'] == 200
797
+    ) {
798
+        $result['status'] = 304;
799
+    }
800
+
801
+    $result['headers'] = implode('', $result['headers']);
802
+
803
+    return $result;
804 804
 }
805 805
 
806 806
 /**
@@ -822,22 +822,22 @@  discard block
 block discarded – undo
822 822
  *     Nom du fichier pour copie locale
823 823
  **/
824 824
 function nom_fichier_copie_locale($source, $extension) {
825
-	include_spip('inc/documents');
825
+    include_spip('inc/documents');
826 826
 
827
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
828
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
827
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
828
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
829 829
 
830
-	// on se place tout le temps comme si on etait a la racine
831
-	if (_DIR_RACINE) {
832
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
833
-	}
830
+    // on se place tout le temps comme si on etait a la racine
831
+    if (_DIR_RACINE) {
832
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
833
+    }
834 834
 
835
-	$m = md5($source);
835
+    $m = md5($source);
836 836
 
837
-	return $d
838
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
839
-	. substr($m, 0, 4)
840
-	. ".$extension";
837
+    return $d
838
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
839
+    . substr($m, 0, 4)
840
+    . ".$extension";
841 841
 }
842 842
 
843 843
 /**
@@ -855,70 +855,70 @@  discard block
 block discarded – undo
855 855
  *      Nom du fichier calculé
856 856
  **/
857 857
 function fichier_copie_locale($source) {
858
-	// Si c'est deja local pas de souci
859
-	if (!tester_url_absolue($source)) {
860
-		if (_DIR_RACINE) {
861
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
862
-		}
863
-
864
-		return $source;
865
-	}
866
-
867
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
868
-	// a deja ete copie en local avec cette extension
869
-	// dans ce cas elle est fiable, pas la peine de requeter en base
870
-	$path_parts = pathinfo($source);
871
-	if (!isset($path_parts['extension'])) {
872
-		$path_parts['extension'] = '';
873
-	}
874
-	$ext = $path_parts ? $path_parts['extension'] : '';
875
-	if (
876
-		$ext
877
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
878
-		and $f = nom_fichier_copie_locale($source, $ext)
879
-		and file_exists(_DIR_RACINE . $f)
880
-	) {
881
-		return $f;
882
-	}
883
-
884
-
885
-	// Si c'est deja dans la table des documents,
886
-	// ramener le nom de sa copie potentielle
887
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
888
-
889
-	if ($ext) {
890
-		return nom_fichier_copie_locale($source, $ext);
891
-	}
892
-
893
-	// voir si l'extension indiquee dans le nom du fichier est ok
894
-	// et si il n'aurait pas deja ete rapatrie
895
-
896
-	$ext = $path_parts ? $path_parts['extension'] : '';
897
-
898
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
899
-		$f = nom_fichier_copie_locale($source, $ext);
900
-		if (file_exists(_DIR_RACINE . $f)) {
901
-			return $f;
902
-		}
903
-	}
904
-
905
-	// Ping  pour voir si son extension est connue et autorisee
906
-	// avec mise en cache du resultat du ping
907
-
908
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
909
-	if (
910
-		!@file_exists($cache)
911
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
912
-		or _request('var_mode') === 'recalcul'
913
-	) {
914
-		$path_parts = recuperer_infos_distantes($source, 0, false);
915
-		ecrire_fichier($cache, serialize($path_parts));
916
-	}
917
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
918
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
919
-		return nom_fichier_copie_locale($source, $ext);
920
-	}
921
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
858
+    // Si c'est deja local pas de souci
859
+    if (!tester_url_absolue($source)) {
860
+        if (_DIR_RACINE) {
861
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
862
+        }
863
+
864
+        return $source;
865
+    }
866
+
867
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
868
+    // a deja ete copie en local avec cette extension
869
+    // dans ce cas elle est fiable, pas la peine de requeter en base
870
+    $path_parts = pathinfo($source);
871
+    if (!isset($path_parts['extension'])) {
872
+        $path_parts['extension'] = '';
873
+    }
874
+    $ext = $path_parts ? $path_parts['extension'] : '';
875
+    if (
876
+        $ext
877
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
878
+        and $f = nom_fichier_copie_locale($source, $ext)
879
+        and file_exists(_DIR_RACINE . $f)
880
+    ) {
881
+        return $f;
882
+    }
883
+
884
+
885
+    // Si c'est deja dans la table des documents,
886
+    // ramener le nom de sa copie potentielle
887
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
888
+
889
+    if ($ext) {
890
+        return nom_fichier_copie_locale($source, $ext);
891
+    }
892
+
893
+    // voir si l'extension indiquee dans le nom du fichier est ok
894
+    // et si il n'aurait pas deja ete rapatrie
895
+
896
+    $ext = $path_parts ? $path_parts['extension'] : '';
897
+
898
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
899
+        $f = nom_fichier_copie_locale($source, $ext);
900
+        if (file_exists(_DIR_RACINE . $f)) {
901
+            return $f;
902
+        }
903
+    }
904
+
905
+    // Ping  pour voir si son extension est connue et autorisee
906
+    // avec mise en cache du resultat du ping
907
+
908
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
909
+    if (
910
+        !@file_exists($cache)
911
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
912
+        or _request('var_mode') === 'recalcul'
913
+    ) {
914
+        $path_parts = recuperer_infos_distantes($source, 0, false);
915
+        ecrire_fichier($cache, serialize($path_parts));
916
+    }
917
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
918
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
919
+        return nom_fichier_copie_locale($source, $ext);
920
+    }
921
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
922 922
 }
923 923
 
924 924
 
@@ -946,97 +946,97 @@  discard block
 block discarded – undo
946 946
  **/
947 947
 function recuperer_infos_distantes($source, $max = 0, $charger_si_petite_image = true) {
948 948
 
949
-	// pas la peine de perdre son temps
950
-	if (!tester_url_absolue($source)) {
951
-		return false;
952
-	}
953
-
954
-	# charger les alias des types mime
955
-	include_spip('base/typedoc');
956
-
957
-	$a = [];
958
-	$mime_type = '';
959
-	// On va directement charger le debut des images et des fichiers html,
960
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
961
-	// ca echoue l'utilisateur devra les entrer...
962
-	$reponse = recuperer_url($source, ['taille_max' => $max, 'refuser_gz' => true]);
963
-	$headers = $reponse['headers'] ?? '';
964
-	$a['body'] = $reponse['page'] ?? '';
965
-	if ($headers) {
966
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
967
-			return false;
968
-		}
969
-
970
-		$a['extension'] = $extension;
971
-
972
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
973
-			$a['taille'] = intval($regs[1]);
974
-		}
975
-	}
976
-
977
-	// Echec avec HEAD, on tente avec GET
978
-	if (!$a and !$max) {
979
-		spip_log("tenter GET $source", 'distant');
980
-		$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
981
-	}
982
-
983
-	// si on a rien trouve pas la peine d'insister
984
-	if (!$a) {
985
-		return false;
986
-	}
987
-
988
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
989
-	// recharger le document en GET et recuperer des donnees supplementaires...
990
-	include_spip('inc/filtres_images_lib_mini');
991
-	if (
992
-		strpos($mime_type, 'image/') === 0
993
-		and $extension = _image_trouver_extension_depuis_mime($mime_type)
994
-	) {
995
-		if (
996
-			$max == 0
997
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
998
-			and in_array($extension, formats_image_acceptables())
999
-			and $charger_si_petite_image
1000
-		) {
1001
-			$a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1002
-		} else {
1003
-			if ($a['body']) {
1004
-				$a['extension'] = $extension;
1005
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1006
-				ecrire_fichier($a['fichier'], $a['body']);
1007
-				$size_image = @spip_getimagesize($a['fichier']);
1008
-				$a['largeur'] = intval($size_image[0]);
1009
-				$a['hauteur'] = intval($size_image[1]);
1010
-				$a['type_image'] = true;
1011
-			}
1012
-		}
1013
-	}
1014
-
1015
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1016
-	// ce sera mieux que 0x0
1017
-	// Flash is dead!
1018
-	if (
1019
-		$a and isset($a['extension']) and $a['extension'] == 'swf'
1020
-		and empty($a['largeur'])
1021
-	) {
1022
-		$a['largeur'] = 425;
1023
-		$a['hauteur'] = 350;
1024
-	}
1025
-
1026
-	if ($mime_type == 'text/html') {
1027
-		include_spip('inc/filtres');
1028
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1029
-		$page = $page['page'] ?? '';
1030
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1031
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1032
-		}
1033
-		if (!isset($a['taille']) or !$a['taille']) {
1034
-			$a['taille'] = strlen($page); # a peu pres
1035
-		}
1036
-	}
1037
-	$a['mime_type'] = $mime_type;
1038
-
1039
-	return $a;
949
+    // pas la peine de perdre son temps
950
+    if (!tester_url_absolue($source)) {
951
+        return false;
952
+    }
953
+
954
+    # charger les alias des types mime
955
+    include_spip('base/typedoc');
956
+
957
+    $a = [];
958
+    $mime_type = '';
959
+    // On va directement charger le debut des images et des fichiers html,
960
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
961
+    // ca echoue l'utilisateur devra les entrer...
962
+    $reponse = recuperer_url($source, ['taille_max' => $max, 'refuser_gz' => true]);
963
+    $headers = $reponse['headers'] ?? '';
964
+    $a['body'] = $reponse['page'] ?? '';
965
+    if ($headers) {
966
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
967
+            return false;
968
+        }
969
+
970
+        $a['extension'] = $extension;
971
+
972
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
973
+            $a['taille'] = intval($regs[1]);
974
+        }
975
+    }
976
+
977
+    // Echec avec HEAD, on tente avec GET
978
+    if (!$a and !$max) {
979
+        spip_log("tenter GET $source", 'distant');
980
+        $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
981
+    }
982
+
983
+    // si on a rien trouve pas la peine d'insister
984
+    if (!$a) {
985
+        return false;
986
+    }
987
+
988
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
989
+    // recharger le document en GET et recuperer des donnees supplementaires...
990
+    include_spip('inc/filtres_images_lib_mini');
991
+    if (
992
+        strpos($mime_type, 'image/') === 0
993
+        and $extension = _image_trouver_extension_depuis_mime($mime_type)
994
+    ) {
995
+        if (
996
+            $max == 0
997
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
998
+            and in_array($extension, formats_image_acceptables())
999
+            and $charger_si_petite_image
1000
+        ) {
1001
+            $a = recuperer_infos_distantes($source, _INC_DISTANT_MAX_SIZE);
1002
+        } else {
1003
+            if ($a['body']) {
1004
+                $a['extension'] = $extension;
1005
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1006
+                ecrire_fichier($a['fichier'], $a['body']);
1007
+                $size_image = @spip_getimagesize($a['fichier']);
1008
+                $a['largeur'] = intval($size_image[0]);
1009
+                $a['hauteur'] = intval($size_image[1]);
1010
+                $a['type_image'] = true;
1011
+            }
1012
+        }
1013
+    }
1014
+
1015
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1016
+    // ce sera mieux que 0x0
1017
+    // Flash is dead!
1018
+    if (
1019
+        $a and isset($a['extension']) and $a['extension'] == 'swf'
1020
+        and empty($a['largeur'])
1021
+    ) {
1022
+        $a['largeur'] = 425;
1023
+        $a['hauteur'] = 350;
1024
+    }
1025
+
1026
+    if ($mime_type == 'text/html') {
1027
+        include_spip('inc/filtres');
1028
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1029
+        $page = $page['page'] ?? '';
1030
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1031
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1032
+        }
1033
+        if (!isset($a['taille']) or !$a['taille']) {
1034
+            $a['taille'] = strlen($page); # a peu pres
1035
+        }
1036
+    }
1037
+    $a['mime_type'] = $mime_type;
1038
+
1039
+    return $a;
1040 1040
 }
1041 1041
 
1042 1042
 /**
@@ -1045,70 +1045,70 @@  discard block
 block discarded – undo
1045 1045
  * @return false|mixed
1046 1046
  */
1047 1047
 function distant_trouver_extension_selon_headers($source, $headers) {
1048
-	if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1049
-		$mime_type = (trim($regs[1]));
1050
-	} else {
1051
-		$mime_type = '';
1052
-	} // inconnu
1053
-
1054
-	// Appliquer les alias
1055
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1056
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1057
-	}
1058
-
1059
-	// pour corriger_extension()
1060
-	include_spip('inc/documents');
1061
-
1062
-	// Si on a un mime-type insignifiant
1063
-	// text/plain,application/octet-stream ou vide
1064
-	// c'est peut-etre que le serveur ne sait pas
1065
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1066
-	// ou le Content-Disposition: attachment; filename=...
1067
-	$t = null;
1068
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1069
-		if (
1070
-			!$t
1071
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1072
-		) {
1073
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1074
-		}
1075
-		if (
1076
-			!$t
1077
-			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1078
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1079
-		) {
1080
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1081
-		}
1082
-	}
1083
-
1084
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1085
-	if (!$t) {
1086
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1087
-	}
1088
-
1089
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1090
-	// On essaie de nouveau avec l'extension
1091
-	if (
1092
-		!$t
1093
-		and $mime_type != 'text/plain'
1094
-		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1095
-	) {
1096
-		# eviter xxx.3 => 3gp (> SPIP 3)
1097
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1098
-	}
1099
-
1100
-	if ($t) {
1101
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1102
-		return $t['extension'];
1103
-	} else {
1104
-		# par defaut on retombe sur '.bin' si c'est autorise
1105
-		spip_log("mime-type $mime_type inconnu", 'distant');
1106
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1107
-		if (!$t) {
1108
-			return false;
1109
-		}
1110
-		return $t['extension'];
1111
-	}
1048
+    if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1049
+        $mime_type = (trim($regs[1]));
1050
+    } else {
1051
+        $mime_type = '';
1052
+    } // inconnu
1053
+
1054
+    // Appliquer les alias
1055
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1056
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1057
+    }
1058
+
1059
+    // pour corriger_extension()
1060
+    include_spip('inc/documents');
1061
+
1062
+    // Si on a un mime-type insignifiant
1063
+    // text/plain,application/octet-stream ou vide
1064
+    // c'est peut-etre que le serveur ne sait pas
1065
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1066
+    // ou le Content-Disposition: attachment; filename=...
1067
+    $t = null;
1068
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1069
+        if (
1070
+            !$t
1071
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1072
+        ) {
1073
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1074
+        }
1075
+        if (
1076
+            !$t
1077
+            and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1078
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1079
+        ) {
1080
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1081
+        }
1082
+    }
1083
+
1084
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1085
+    if (!$t) {
1086
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1087
+    }
1088
+
1089
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1090
+    // On essaie de nouveau avec l'extension
1091
+    if (
1092
+        !$t
1093
+        and $mime_type != 'text/plain'
1094
+        and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1095
+    ) {
1096
+        # eviter xxx.3 => 3gp (> SPIP 3)
1097
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1098
+    }
1099
+
1100
+    if ($t) {
1101
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1102
+        return $t['extension'];
1103
+    } else {
1104
+        # par defaut on retombe sur '.bin' si c'est autorise
1105
+        spip_log("mime-type $mime_type inconnu", 'distant');
1106
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1107
+        if (!$t) {
1108
+            return false;
1109
+        }
1110
+        return $t['extension'];
1111
+    }
1112 1112
 }
1113 1113
 
1114 1114
 /**
@@ -1124,45 +1124,45 @@  discard block
 block discarded – undo
1124 1124
  */
1125 1125
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1126 1126
 
1127
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1127
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1128 1128
 	
1129
-	// rien a faire si pas de proxy :)
1130
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1131
-		return '';
1132
-	}
1133
-
1134
-	if (is_null($http_noproxy)) {
1135
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1136
-	}
1137
-	// si pas d'exception, on retourne le proxy
1138
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1139
-		return $http_proxy;
1140
-	}
1141
-
1142
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1143
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1144
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1145
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1146
-	$http_noproxy = " $http_noproxy ";
1147
-	$domain = $host;
1148
-	// si le domaine exact www.example.org est dans les exceptions
1149
-	if (strpos($http_noproxy, " $domain ") !== false) {
1150
-		return '';
1151
-	}
1152
-
1153
-	while (strpos($domain, '.') !== false) {
1154
-		$domain = explode('.', $domain);
1155
-		array_shift($domain);
1156
-		$domain = implode('.', $domain);
1157
-
1158
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1159
-		if (strpos($http_noproxy, " .$domain ") !== false) {
1160
-			return '';
1161
-		}
1162
-	}
1163
-
1164
-	// ok c'est pas une exception
1165
-	return $http_proxy;
1129
+    // rien a faire si pas de proxy :)
1130
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1131
+        return '';
1132
+    }
1133
+
1134
+    if (is_null($http_noproxy)) {
1135
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1136
+    }
1137
+    // si pas d'exception, on retourne le proxy
1138
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1139
+        return $http_proxy;
1140
+    }
1141
+
1142
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1143
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1144
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1145
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1146
+    $http_noproxy = " $http_noproxy ";
1147
+    $domain = $host;
1148
+    // si le domaine exact www.example.org est dans les exceptions
1149
+    if (strpos($http_noproxy, " $domain ") !== false) {
1150
+        return '';
1151
+    }
1152
+
1153
+    while (strpos($domain, '.') !== false) {
1154
+        $domain = explode('.', $domain);
1155
+        array_shift($domain);
1156
+        $domain = implode('.', $domain);
1157
+
1158
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1159
+        if (strpos($http_noproxy, " .$domain ") !== false) {
1160
+            return '';
1161
+        }
1162
+    }
1163
+
1164
+    // ok c'est pas une exception
1165
+    return $http_proxy;
1166 1166
 }
1167 1167
 
1168 1168
 
@@ -1185,59 +1185,59 @@  discard block
 block discarded – undo
1185 1185
  * @return array
1186 1186
  */
1187 1187
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1188
-	$user = $via_proxy = $proxy_user = '';
1189
-	$fopen = false;
1190
-
1191
-	$t = @parse_url($url);
1192
-	$host = $t['host'];
1193
-	if ($t['scheme'] == 'http') {
1194
-		$scheme = 'http';
1195
-		$noproxy = '';
1196
-	} elseif ($t['scheme'] == 'https') {
1197
-		$scheme = 'ssl';
1198
-		$noproxy = 'ssl://';
1199
-		if (!isset($t['port']) || !($port = $t['port'])) {
1200
-			$t['port'] = 443;
1201
-		}
1202
-	} else {
1203
-		$scheme = $t['scheme'];
1204
-		$noproxy = $scheme . '://';
1205
-	}
1206
-	if (isset($t['user'])) {
1207
-		$user = [$t['user'], $t['pass']];
1208
-	}
1209
-
1210
-	if (!isset($t['port']) || !($port = $t['port'])) {
1211
-		$port = 80;
1212
-	}
1213
-	if (!isset($t['path']) || !($path = $t['path'])) {
1214
-		$path = '/';
1215
-	}
1216
-
1217
-	if (!empty($t['query'])) {
1218
-		$path .= '?' . $t['query'];
1219
-	}
1220
-
1221
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1222
-	if (!$f or !is_resource($f)) {
1223
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1224
-		// ce qui correspond a $f===110
1225
-		if (
1226
-			$f !== 110
1227
-			and !need_proxy($host)
1228
-			and !_request('tester_proxy')
1229
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1230
-		) {
1231
-			$f = @fopen($url, 'rb');
1232
-			spip_log("connexion vers $url par simple fopen", 'distant');
1233
-			$fopen = true;
1234
-		} else {
1235
-			// echec total
1236
-			$f = false;
1237
-		}
1238
-	}
1239
-
1240
-	return [$f, $fopen];
1188
+    $user = $via_proxy = $proxy_user = '';
1189
+    $fopen = false;
1190
+
1191
+    $t = @parse_url($url);
1192
+    $host = $t['host'];
1193
+    if ($t['scheme'] == 'http') {
1194
+        $scheme = 'http';
1195
+        $noproxy = '';
1196
+    } elseif ($t['scheme'] == 'https') {
1197
+        $scheme = 'ssl';
1198
+        $noproxy = 'ssl://';
1199
+        if (!isset($t['port']) || !($port = $t['port'])) {
1200
+            $t['port'] = 443;
1201
+        }
1202
+    } else {
1203
+        $scheme = $t['scheme'];
1204
+        $noproxy = $scheme . '://';
1205
+    }
1206
+    if (isset($t['user'])) {
1207
+        $user = [$t['user'], $t['pass']];
1208
+    }
1209
+
1210
+    if (!isset($t['port']) || !($port = $t['port'])) {
1211
+        $port = 80;
1212
+    }
1213
+    if (!isset($t['path']) || !($path = $t['path'])) {
1214
+        $path = '/';
1215
+    }
1216
+
1217
+    if (!empty($t['query'])) {
1218
+        $path .= '?' . $t['query'];
1219
+    }
1220
+
1221
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1222
+    if (!$f or !is_resource($f)) {
1223
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1224
+        // ce qui correspond a $f===110
1225
+        if (
1226
+            $f !== 110
1227
+            and !need_proxy($host)
1228
+            and !_request('tester_proxy')
1229
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1230
+        ) {
1231
+            $f = @fopen($url, 'rb');
1232
+            spip_log("connexion vers $url par simple fopen", 'distant');
1233
+            $fopen = true;
1234
+        } else {
1235
+            // echec total
1236
+            $f = false;
1237
+        }
1238
+    }
1239
+
1240
+    return [$f, $fopen];
1241 1241
 }
1242 1242
 
1243 1243
 /**
@@ -1272,125 +1272,125 @@  discard block
 block discarded – undo
1272 1272
  *   resource socket vers l'url demandee
1273 1273
  */
1274 1274
 function lance_requete(
1275
-	$method,
1276
-	$scheme,
1277
-	$user,
1278
-	$host,
1279
-	$path,
1280
-	$port,
1281
-	$noproxy,
1282
-	$refuse_gz = false,
1283
-	$referer = '',
1284
-	$datas = '',
1285
-	$vers = 'HTTP/1.0',
1286
-	$date = ''
1275
+    $method,
1276
+    $scheme,
1277
+    $user,
1278
+    $host,
1279
+    $path,
1280
+    $port,
1281
+    $noproxy,
1282
+    $refuse_gz = false,
1283
+    $referer = '',
1284
+    $datas = '',
1285
+    $vers = 'HTTP/1.0',
1286
+    $date = ''
1287 1287
 ) {
1288 1288
 
1289
-	$proxy_user = '';
1290
-	$http_proxy = need_proxy($host);
1291
-	if ($user) {
1292
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1293
-	}
1294
-
1295
-	$connect = '';
1296
-	if ($http_proxy) {
1297
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1298
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1299
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1300
-				. "Host: $path_host\r\n"
1301
-				. "Proxy-Connection: Keep-Alive\r\n";
1302
-		} else {
1303
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1304
-				. (!$user ? '' : "$user@")
1305
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1306
-		}
1307
-		$t2 = @parse_url($http_proxy);
1308
-		$first_host = $t2['host'];
1309
-		if (!($port = $t2['port'])) {
1310
-			$port = 80;
1311
-		}
1312
-		if ($t2['user']) {
1313
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1314
-		}
1315
-	} else {
1316
-		$first_host = $noproxy . $host;
1317
-	}
1318
-
1319
-	if ($connect) {
1320
-		$streamContext = stream_context_create([
1321
-			'ssl' => [
1322
-				'verify_peer' => false,
1323
-				'allow_self_signed' => true,
1324
-				'SNI_enabled' => true,
1325
-				'peer_name' => $host,
1326
-			]
1327
-		]);
1328
-		$f = @stream_socket_client(
1329
-			"tcp://$first_host:$port",
1330
-			$errno,
1331
-			$errstr,
1332
-			_INC_DISTANT_CONNECT_TIMEOUT,
1333
-			STREAM_CLIENT_CONNECT,
1334
-			$streamContext
1335
-		);
1336
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1337
-		if (!$f) {
1338
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1339
-			return $errno;
1340
-		}
1341
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1342
-
1343
-		fputs($f, $connect);
1344
-		fputs($f, "\r\n");
1345
-		$res = fread($f, 1024);
1346
-		if (
1347
-			!$res
1348
-			or !count($res = explode(' ', $res))
1349
-			or $res[1] !== '200'
1350
-		) {
1351
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1352
-			fclose($f);
1353
-
1354
-			return false;
1355
-		}
1356
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1357
-		stream_set_blocking($f, true);
1358
-		// envoyer le handshake
1359
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1360
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1361
-	} else {
1362
-		$ntry = 3;
1363
-		do {
1364
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1365
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1366
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1367
-		if (!$f) {
1368
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1369
-
1370
-			return $errno;
1371
-		}
1372
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1373
-	}
1374
-
1375
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1376
-
1377
-	$host_port = $host;
1378
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1379
-		$host_port .= ":$port";
1380
-	}
1381
-	$req = "$method $path $vers\r\n"
1382
-		. "Host: $host_port\r\n"
1383
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1384
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1385
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1386
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1387
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1388
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1389
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1289
+    $proxy_user = '';
1290
+    $http_proxy = need_proxy($host);
1291
+    if ($user) {
1292
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1293
+    }
1294
+
1295
+    $connect = '';
1296
+    if ($http_proxy) {
1297
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1298
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1299
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1300
+                . "Host: $path_host\r\n"
1301
+                . "Proxy-Connection: Keep-Alive\r\n";
1302
+        } else {
1303
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1304
+                . (!$user ? '' : "$user@")
1305
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1306
+        }
1307
+        $t2 = @parse_url($http_proxy);
1308
+        $first_host = $t2['host'];
1309
+        if (!($port = $t2['port'])) {
1310
+            $port = 80;
1311
+        }
1312
+        if ($t2['user']) {
1313
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1314
+        }
1315
+    } else {
1316
+        $first_host = $noproxy . $host;
1317
+    }
1318
+
1319
+    if ($connect) {
1320
+        $streamContext = stream_context_create([
1321
+            'ssl' => [
1322
+                'verify_peer' => false,
1323
+                'allow_self_signed' => true,
1324
+                'SNI_enabled' => true,
1325
+                'peer_name' => $host,
1326
+            ]
1327
+        ]);
1328
+        $f = @stream_socket_client(
1329
+            "tcp://$first_host:$port",
1330
+            $errno,
1331
+            $errstr,
1332
+            _INC_DISTANT_CONNECT_TIMEOUT,
1333
+            STREAM_CLIENT_CONNECT,
1334
+            $streamContext
1335
+        );
1336
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1337
+        if (!$f) {
1338
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1339
+            return $errno;
1340
+        }
1341
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1342
+
1343
+        fputs($f, $connect);
1344
+        fputs($f, "\r\n");
1345
+        $res = fread($f, 1024);
1346
+        if (
1347
+            !$res
1348
+            or !count($res = explode(' ', $res))
1349
+            or $res[1] !== '200'
1350
+        ) {
1351
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1352
+            fclose($f);
1353
+
1354
+            return false;
1355
+        }
1356
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1357
+        stream_set_blocking($f, true);
1358
+        // envoyer le handshake
1359
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1360
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1361
+    } else {
1362
+        $ntry = 3;
1363
+        do {
1364
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1365
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1366
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1367
+        if (!$f) {
1368
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1369
+
1370
+            return $errno;
1371
+        }
1372
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1373
+    }
1374
+
1375
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1376
+
1377
+    $host_port = $host;
1378
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1379
+        $host_port .= ":$port";
1380
+    }
1381
+    $req = "$method $path $vers\r\n"
1382
+        . "Host: $host_port\r\n"
1383
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1384
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1385
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1386
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1387
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1388
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1389
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1390 1390
 
1391 1391
 #	spip_log("Requete\n$req", 'distant');
1392
-	fputs($f, $req);
1393
-	fputs($f, $datas ? $datas : "\r\n");
1392
+    fputs($f, $req);
1393
+    fputs($f, $datas ? $datas : "\r\n");
1394 1394
 
1395
-	return $f;
1395
+    return $f;
1396 1396
 }
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
27 27
 }
28 28
 if (!defined('_INC_DISTANT_USER_AGENT')) {
29
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
29
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
30 30
 }
31 31
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
32 32
 	define('_INC_DISTANT_MAX_SIZE', 2097152);
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
36 36
 }
37 37
 
38
-define('_REGEXP_COPIE_LOCALE', ',' 	.
38
+define('_REGEXP_COPIE_LOCALE', ','.
39 39
 	preg_replace(
40 40
 		'@^https?:@',
41 41
 		'https?:',
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 
71 71
 	// si c'est la protection de soi-meme, retourner le path
72 72
 	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
73
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
73
+		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)).urldecode($match[1]);
74 74
 
75 75
 		return @file_exists($source) ? $source : false;
76 76
 	}
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 		return false;
91 91
 	}
92 92
 
93
-	$localrac = _DIR_RACINE . $local;
93
+	$localrac = _DIR_RACINE.$local;
94 94
 	$t = ($mode === 'force') ? false : @file_exists($localrac);
95 95
 
96 96
 	// test d'existence du fichier
@@ -115,10 +115,10 @@  discard block
 block discarded – undo
115 115
 			['file' => $localrac, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
116 116
 		);
117 117
 		if (!$res or (!$res['length'] and $res['status'] != 304)) {
118
-			spip_log("copie_locale : Echec recuperation $source sur $localrac status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
118
+			spip_log("copie_locale : Echec recuperation $source sur $localrac status : ".($res ? $res['status'] : '-'), 'distant'._LOG_INFO_IMPORTANTE);
119 119
 		}
120 120
 		else {
121
-			spip_log("copie_locale : recuperation $source sur $localrac OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
121
+			spip_log("copie_locale : recuperation $source sur $localrac OK | taille ".$res['length'].' status '.$res['status'], 'distant');
122 122
 		}
123 123
 		if (!$res or !$res['length']) {
124 124
 			// si $t c'est sans doute juste un not-modified-since
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 
208 208
 	if (!$is_known_host) {
209 209
 		$host = trim($parsed_url['host'], '.');
210
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
210
+		if (!$ip = filter_var($host, FILTER_VALIDATE_IP)) {
211 211
 			$ip = gethostbyname($host);
212 212
 			if ($ip === $host) {
213 213
 				// Error condition for gethostbyname()
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 			}
229 229
 		}
230 230
 		if ($ip) {
231
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
231
+			if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
232 232
 				return false;
233 233
 			}
234 234
 		}
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	}
240 240
 
241 241
 	$port = $parsed_url['port'];
242
-	if ($port === 80  or $port === 443  or $port === 8080) {
242
+	if ($port === 80 or $port === 443 or $port === 8080) {
243 243
 		return $url;
244 244
 	}
245 245
 
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 				}
310 310
 			}
311 311
 			if ($taille > 500) {
312
-				$boundary = substr(md5(rand() . 'spip'), 0, 8);
312
+				$boundary = substr(md5(rand().'spip'), 0, 8);
313 313
 			}
314 314
 		}
315 315
 
@@ -337,16 +337,16 @@  discard block
 block discarded – undo
337 337
 			}
338 338
 		} else {
339 339
 			// fabrique une chaine HTTP simple pour un POST
340
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
340
+			$entete = 'Content-Type: application/x-www-form-urlencoded'."\r\n";
341 341
 			$chaine = [];
342 342
 			if (is_array($donnees)) {
343 343
 				foreach ($donnees as $cle => $valeur) {
344 344
 					if (is_array($valeur)) {
345 345
 						foreach ($valeur as $val2) {
346
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
346
+							$chaine[] = rawurlencode($cle).'[]='.rawurlencode($val2);
347 347
 						}
348 348
 					} else {
349
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
349
+						$chaine[] = rawurlencode($cle).'='.rawurlencode($valeur);
350 350
 					}
351 351
 				}
352 352
 				$chaine = implode('&', $chaine);
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 			$url_idn = implode($host_ascii, $url_idn);
381 381
 		}
382 382
 		// et on urlencode les char utf si besoin dans le path
383
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function ($match) {
383
+		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', function($match) {
384 384
  return urlencode($match[0]);
385 385
 		}, $url_idn);
386 386
 	}
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 	$head_add = '';
459 459
 	if (!empty($options['headers'])) {
460 460
 		foreach ($options['headers'] as $champ => $valeur) {
461
-			$head_add .= $champ . ': ' . $valeur . "\r\n";
461
+			$head_add .= $champ.': '.$valeur."\r\n";
462 462
 		}
463 463
 		// ne pas le repasser a recuperer_url si on follow un location, car ils seront dans datas
464 464
 		unset($options['headers']);
@@ -468,9 +468,9 @@  discard block
 block discarded – undo
468 468
 		list($head, $postdata) = prepare_donnees_post($options['datas'], $options['boundary']);
469 469
 		$head .= $head_add;
470 470
 		if (stripos($head, 'Content-Length:') === false) {
471
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
471
+			$head .= 'Content-Length: '.strlen($postdata)."\r\n";
472 472
 		}
473
-		$options['datas'] = $head . "\r\n" . $postdata;
473
+		$options['datas'] = $head."\r\n".$postdata;
474 474
 		if (
475 475
 			strlen($postdata)
476 476
 			and !$methode_demandee
@@ -478,15 +478,15 @@  discard block
 block discarded – undo
478 478
 			$options['methode'] = 'POST';
479 479
 		}
480 480
 	} elseif ($head_add) {
481
-		$options['datas'] = $head_add . "\r\n";
481
+		$options['datas'] = $head_add."\r\n";
482 482
 	}
483 483
 
484 484
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
485 485
 	$url = preg_replace(',^feed://,i', 'http://', $url);
486 486
 	if (!tester_url_absolue($url)) {
487
-		$url = 'http://' . $url;
487
+		$url = 'http://'.$url;
488 488
 	} elseif (strncmp($url, '//', 2) == 0) {
489
-		$url = 'http:' . $url;
489
+		$url = 'http:'.$url;
490 490
 	}
491 491
 
492 492
 	$url = url_to_ascii($url);
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 		$options['if_modified_since']
516 516
 	);
517 517
 	if (!$handle) {
518
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
518
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
519 519
 
520 520
 		return false;
521 521
 	}
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 					'status' => 200,
546 546
 				];
547 547
 			} else {
548
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
548
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
549 549
 				return false;
550 550
 			}
551 551
 		} elseif ($res['location'] and $options['follow_location']) {
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 
558 558
 			return recuperer_url($url, $options);
559 559
 		} elseif ($res['status'] !== 200) {
560
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
560
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
561 561
 		}
562 562
 		$result['status'] = $res['status'];
563 563
 		if (isset($res['headers'])) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 
583 583
 	$gz = false;
584 584
 	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
585
-		$gz = (_DIR_TMP . md5(uniqid(mt_rand())) . '.tmp.gz');
585
+		$gz = (_DIR_TMP.md5(uniqid(mt_rand())).'.tmp.gz');
586 586
 	}
587 587
 
588 588
 	// si on a pas deja recuperer le contenu par une methode detournee
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 	$sig['url'] = $url;
669 669
 
670 670
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
671
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
671
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
672 672
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
673 673
 	$cache = "$sub$cache";
674 674
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 	$fp = false;
722 722
 	if ($fichier) {
723 723
 		include_spip('inc/acces');
724
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
724
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
725 725
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
726 726
 		if (!$fp and file_exists($fichier)) {
727 727
 			return filesize($fichier);
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 	}
781 781
 	$result['status'] = intval($r[1]);
782 782
 	while ($s = trim(fgets($handle, 16384))) {
783
-		$result['headers'][] = $s . "\n";
783
+		$result['headers'][] = $s."\n";
784 784
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
785 785
 		list(, $d, $v) = $r;
786 786
 		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
@@ -829,13 +829,13 @@  discard block
 block discarded – undo
829 829
 
830 830
 	// on se place tout le temps comme si on etait a la racine
831 831
 	if (_DIR_RACINE) {
832
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
832
+		$d = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $d);
833 833
 	}
834 834
 
835 835
 	$m = md5($source);
836 836
 
837 837
 	return $d
838
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
838
+	. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
839 839
 	. substr($m, 0, 4)
840 840
 	. ".$extension";
841 841
 }
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
 	// Si c'est deja local pas de souci
859 859
 	if (!tester_url_absolue($source)) {
860 860
 		if (_DIR_RACINE) {
861
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
861
+			$source = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $source);
862 862
 		}
863 863
 
864 864
 		return $source;
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 		$ext
877 877
 		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
878 878
 		and $f = nom_fichier_copie_locale($source, $ext)
879
-		and file_exists(_DIR_RACINE . $f)
879
+		and file_exists(_DIR_RACINE.$f)
880 880
 	) {
881 881
 		return $f;
882 882
 	}
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
 
885 885
 	// Si c'est deja dans la table des documents,
886 886
 	// ramener le nom de sa copie potentielle
887
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
887
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
888 888
 
889 889
 	if ($ext) {
890 890
 		return nom_fichier_copie_locale($source, $ext);
@@ -895,9 +895,9 @@  discard block
 block discarded – undo
895 895
 
896 896
 	$ext = $path_parts ? $path_parts['extension'] : '';
897 897
 
898
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
898
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
899 899
 		$f = nom_fichier_copie_locale($source, $ext);
900
-		if (file_exists(_DIR_RACINE . $f)) {
900
+		if (file_exists(_DIR_RACINE.$f)) {
901 901
 			return $f;
902 902
 		}
903 903
 	}
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
 	// Ping  pour voir si son extension est connue et autorisee
906 906
 	// avec mise en cache du resultat du ping
907 907
 
908
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
908
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
909 909
 	if (
910 910
 		!@file_exists($cache)
911 911
 		or !$path_parts = @unserialize(spip_file_get_contents($cache))
@@ -915,10 +915,10 @@  discard block
 block discarded – undo
915 915
 		ecrire_fichier($cache, serialize($path_parts));
916 916
 	}
917 917
 	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
918
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
918
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
919 919
 		return nom_fichier_copie_locale($source, $ext);
920 920
 	}
921
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
921
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
922 922
 }
923 923
 
924 924
 
@@ -1002,7 +1002,7 @@  discard block
 block discarded – undo
1002 1002
 		} else {
1003 1003
 			if ($a['body']) {
1004 1004
 				$a['extension'] = $extension;
1005
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1005
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1006 1006
 				ecrire_fichier($a['fichier'], $a['body']);
1007 1007
 				$size_image = @spip_getimagesize($a['fichier']);
1008 1008
 				$a['largeur'] = intval($size_image[0]);
@@ -1070,20 +1070,20 @@  discard block
 block discarded – undo
1070 1070
 			!$t
1071 1071
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1072 1072
 		) {
1073
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1073
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1074 1074
 		}
1075 1075
 		if (
1076 1076
 			!$t
1077 1077
 			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1078 1078
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1079 1079
 		) {
1080
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1080
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1081 1081
 		}
1082 1082
 	}
1083 1083
 
1084 1084
 	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1085 1085
 	if (!$t) {
1086
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1086
+		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1087 1087
 	}
1088 1088
 
1089 1089
 	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1094,11 +1094,11 @@  discard block
 block discarded – undo
1094 1094
 		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1095 1095
 	) {
1096 1096
 		# eviter xxx.3 => 3gp (> SPIP 3)
1097
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1097
+		$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1098 1098
 	}
1099 1099
 
1100 1100
 	if ($t) {
1101
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1101
+		spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1102 1102
 		return $t['extension'];
1103 1103
 	} else {
1104 1104
 		# par defaut on retombe sur '.bin' si c'est autorise
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
 		}
1202 1202
 	} else {
1203 1203
 		$scheme = $t['scheme'];
1204
-		$noproxy = $scheme . '://';
1204
+		$noproxy = $scheme.'://';
1205 1205
 	}
1206 1206
 	if (isset($t['user'])) {
1207 1207
 		$user = [$t['user'], $t['pass']];
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
 	}
1216 1216
 
1217 1217
 	if (!empty($t['query'])) {
1218
-		$path .= '?' . $t['query'];
1218
+		$path .= '?'.$t['query'];
1219 1219
 	}
1220 1220
 
1221 1221
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1289,20 +1289,20 @@  discard block
 block discarded – undo
1289 1289
 	$proxy_user = '';
1290 1290
 	$http_proxy = need_proxy($host);
1291 1291
 	if ($user) {
1292
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1292
+		$user = urlencode($user[0]).':'.urlencode($user[1]);
1293 1293
 	}
1294 1294
 
1295 1295
 	$connect = '';
1296 1296
 	if ($http_proxy) {
1297
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1298
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1299
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1297
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls', 'ssl'])) {
1298
+			$path_host = (!$user ? '' : "$user@").$host.(($port != 80) ? ":$port" : '');
1299
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1300 1300
 				. "Host: $path_host\r\n"
1301 1301
 				. "Proxy-Connection: Keep-Alive\r\n";
1302 1302
 		} else {
1303
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1303
+			$path = (in_array($scheme, ['tls', 'ssl']) ? 'https://' : "$scheme://")
1304 1304
 				. (!$user ? '' : "$user@")
1305
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1305
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1306 1306
 		}
1307 1307
 		$t2 = @parse_url($http_proxy);
1308 1308
 		$first_host = $t2['host'];
@@ -1310,10 +1310,10 @@  discard block
 block discarded – undo
1310 1310
 			$port = 80;
1311 1311
 		}
1312 1312
 		if ($t2['user']) {
1313
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1313
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1314 1314
 		}
1315 1315
 	} else {
1316
-		$first_host = $noproxy . $host;
1316
+		$first_host = $noproxy.$host;
1317 1317
 	}
1318 1318
 
1319 1319
 	if ($connect) {
@@ -1335,7 +1335,7 @@  discard block
 block discarded – undo
1335 1335
 		);
1336 1336
 		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1337 1337
 		if (!$f) {
1338
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1338
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1339 1339
 			return $errno;
1340 1340
 		}
1341 1341
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1348,7 +1348,7 @@  discard block
 block discarded – undo
1348 1348
 			or !count($res = explode(' ', $res))
1349 1349
 			or $res[1] !== '200'
1350 1350
 		) {
1351
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1351
+			spip_log("Echec CONNECT sur $first_host:$port", 'connect'._LOG_INFO_IMPORTANTE);
1352 1352
 			fclose($f);
1353 1353
 
1354 1354
 			return false;
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
 		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1366 1366
 		spip_log("Recuperer $path sur $first_host:$port par $f");
1367 1367
 		if (!$f) {
1368
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1368
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1369 1369
 
1370 1370
 			return $errno;
1371 1371
 		}
@@ -1375,16 +1375,16 @@  discard block
 block discarded – undo
1375 1375
 	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1376 1376
 
1377 1377
 	$host_port = $host;
1378
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1378
+	if ($port != (in_array($scheme, ['tls', 'ssl']) ? 443 : 80)) {
1379 1379
 		$host_port .= ":$port";
1380 1380
 	}
1381 1381
 	$req = "$method $path $vers\r\n"
1382 1382
 		. "Host: $host_port\r\n"
1383
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1384
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1383
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1384
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1385 1385
 		. (!$site ? '' : "Referer: $site/$referer\r\n")
1386
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1387
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1386
+		. (!$date ? '' : 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n"))
1387
+		. (!$user ? '' : ('Authorization: Basic '.base64_encode($user)."\r\n"))
1388 1388
 		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1389 1389
 		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1390 1390
 
Please login to merge, or discard this patch.
ecrire/base/connect_sql.php 2 patches
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\SQL
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 require_once _ROOT_RESTREINT . 'base/objets.php';
22 22
 
@@ -42,119 +42,119 @@  discard block
 block discarded – undo
42 42
  **/
43 43
 function spip_connect($serveur = '', $version = '') {
44 44
 
45
-	$serveur = !is_string($serveur) ? '' : strtolower($serveur);
46
-	$index = $serveur ? $serveur : 0;
47
-	if (!$version) {
48
-		$version = $GLOBALS['spip_sql_version'];
49
-	}
50
-	if (isset($GLOBALS['connexions'][$index][$version])) {
51
-		return $GLOBALS['connexions'][$index];
52
-	}
53
-
54
-	include_spip('base/abstract_sql');
55
-	$install = (_request('exec') == 'install');
56
-
57
-	// Premiere connexion ?
58
-	if (!($old = isset($GLOBALS['connexions'][$index]))) {
59
-		$f = (!preg_match('/^[\w\.]*$/', $serveur))
60
-			? '' // nom de serveur mal ecrit
61
-			: ($serveur ?
62
-				(_DIR_CONNECT . $serveur . '.php') // serveur externe
63
-				: (_FILE_CONNECT ? _FILE_CONNECT // serveur principal ok
64
-					: ($install ? _FILE_CONNECT_TMP // init du serveur principal
65
-						: ''))); // installation pas faite
66
-
67
-		unset($GLOBALS['db_ok']);
68
-		unset($GLOBALS['spip_connect_version']);
69
-		if ($f) {
70
-			if (is_readable($f)) {
71
-				include($f);
72
-			} elseif ($serveur and !$install) {
73
-				// chercher une declaration de serveur dans le path
74
-				// qui pourra un jour servir a declarer des bases sqlite
75
-				// par des plugins. Et sert aussi aux boucles POUR.
76
-				find_in_path("$serveur.php", 'connect/', true);
77
-			}
78
-		}
79
-		if (!isset($GLOBALS['db_ok'])) {
80
-			// fera mieux la prochaine fois
81
-			if ($install) {
82
-				return false;
83
-			}
84
-			if ($f and is_readable($f)) {
85
-				spip_log("spip_connect: fichier de connexion '$f' OK.", _LOG_INFO_IMPORTANTE);
86
-			} else {
87
-				spip_log("spip_connect: fichier de connexion '$f' non trouve", _LOG_INFO_IMPORTANTE);
88
-			}
89
-			spip_log("spip_connect: echec connexion ou serveur $index mal defini dans '$f'.", _LOG_HS);
90
-
91
-			// ne plus reessayer si ce n'est pas l'install
92
-			return $GLOBALS['connexions'][$index] = false;
93
-		}
94
-		$GLOBALS['connexions'][$index] = $GLOBALS['db_ok'];
95
-	}
96
-	// si la connexion a deja ete tentee mais a echoue, le dire!
97
-	if (!$GLOBALS['connexions'][$index]) {
98
-		return false;
99
-	}
100
-
101
-	// la connexion a reussi ou etait deja faite.
102
-	// chargement de la version du jeu de fonctions
103
-	// si pas dans le fichier par defaut
104
-	$type = $GLOBALS['db_ok']['type'];
105
-	$jeu = 'spip_' . $type . '_functions_' . $version;
106
-	if (!isset($GLOBALS[$jeu])) {
107
-		if (!find_in_path($type . '_' . $version . '.php', 'req/', true)) {
108
-			spip_log("spip_connect: serveur $index version '$version' non defini pour '$type'", _LOG_HS);
109
-
110
-			// ne plus reessayer
111
-			return $GLOBALS['connexions'][$index][$version] = [];
112
-		}
113
-	}
114
-	$GLOBALS['connexions'][$index][$version] = $GLOBALS[$jeu];
115
-	if ($old) {
116
-		return $GLOBALS['connexions'][$index];
117
-	}
118
-
119
-	$GLOBALS['connexions'][$index]['spip_connect_version'] = $GLOBALS['spip_connect_version'] ?? 0;
120
-
121
-	// initialisation de l'alphabet utilise dans les connexions SQL
122
-	// si l'installation l'a determine.
123
-	// Celui du serveur principal l'impose aux serveurs secondaires
124
-	// s'ils le connaissent
125
-
126
-	if (!$serveur) {
127
-		$charset = spip_connect_main($GLOBALS[$jeu], $GLOBALS['db_ok']['charset']);
128
-		if (!$charset) {
129
-			unset($GLOBALS['connexions'][$index]);
130
-			spip_log('spip_connect: absence de charset', _LOG_AVERTISSEMENT);
131
-
132
-			return false;
133
-		}
134
-	} else {
135
-		if ($GLOBALS['db_ok']['charset']) {
136
-			$charset = $GLOBALS['db_ok']['charset'];
137
-		}
138
-		// spip_meta n'existe pas toujours dans la base
139
-		// C'est le cas d'un dump sqlite par exemple
140
-		elseif (
141
-			$GLOBALS['connexions'][$index]['spip_connect_version']
142
-			and sql_showtable('spip_meta', true, $serveur)
143
-			and $r = sql_getfetsel('valeur', 'spip_meta', "nom='charset_sql_connexion'", '', '', '', '', $serveur)
144
-		) {
145
-			$charset = $r;
146
-		} else {
147
-			$charset = -1;
148
-		}
149
-	}
150
-	if ($charset != -1) {
151
-		$f = $GLOBALS[$jeu]['set_charset'];
152
-		if (function_exists($f)) {
153
-			$f($charset, $serveur);
154
-		}
155
-	}
156
-
157
-	return $GLOBALS['connexions'][$index];
45
+    $serveur = !is_string($serveur) ? '' : strtolower($serveur);
46
+    $index = $serveur ? $serveur : 0;
47
+    if (!$version) {
48
+        $version = $GLOBALS['spip_sql_version'];
49
+    }
50
+    if (isset($GLOBALS['connexions'][$index][$version])) {
51
+        return $GLOBALS['connexions'][$index];
52
+    }
53
+
54
+    include_spip('base/abstract_sql');
55
+    $install = (_request('exec') == 'install');
56
+
57
+    // Premiere connexion ?
58
+    if (!($old = isset($GLOBALS['connexions'][$index]))) {
59
+        $f = (!preg_match('/^[\w\.]*$/', $serveur))
60
+            ? '' // nom de serveur mal ecrit
61
+            : ($serveur ?
62
+                (_DIR_CONNECT . $serveur . '.php') // serveur externe
63
+                : (_FILE_CONNECT ? _FILE_CONNECT // serveur principal ok
64
+                    : ($install ? _FILE_CONNECT_TMP // init du serveur principal
65
+                        : ''))); // installation pas faite
66
+
67
+        unset($GLOBALS['db_ok']);
68
+        unset($GLOBALS['spip_connect_version']);
69
+        if ($f) {
70
+            if (is_readable($f)) {
71
+                include($f);
72
+            } elseif ($serveur and !$install) {
73
+                // chercher une declaration de serveur dans le path
74
+                // qui pourra un jour servir a declarer des bases sqlite
75
+                // par des plugins. Et sert aussi aux boucles POUR.
76
+                find_in_path("$serveur.php", 'connect/', true);
77
+            }
78
+        }
79
+        if (!isset($GLOBALS['db_ok'])) {
80
+            // fera mieux la prochaine fois
81
+            if ($install) {
82
+                return false;
83
+            }
84
+            if ($f and is_readable($f)) {
85
+                spip_log("spip_connect: fichier de connexion '$f' OK.", _LOG_INFO_IMPORTANTE);
86
+            } else {
87
+                spip_log("spip_connect: fichier de connexion '$f' non trouve", _LOG_INFO_IMPORTANTE);
88
+            }
89
+            spip_log("spip_connect: echec connexion ou serveur $index mal defini dans '$f'.", _LOG_HS);
90
+
91
+            // ne plus reessayer si ce n'est pas l'install
92
+            return $GLOBALS['connexions'][$index] = false;
93
+        }
94
+        $GLOBALS['connexions'][$index] = $GLOBALS['db_ok'];
95
+    }
96
+    // si la connexion a deja ete tentee mais a echoue, le dire!
97
+    if (!$GLOBALS['connexions'][$index]) {
98
+        return false;
99
+    }
100
+
101
+    // la connexion a reussi ou etait deja faite.
102
+    // chargement de la version du jeu de fonctions
103
+    // si pas dans le fichier par defaut
104
+    $type = $GLOBALS['db_ok']['type'];
105
+    $jeu = 'spip_' . $type . '_functions_' . $version;
106
+    if (!isset($GLOBALS[$jeu])) {
107
+        if (!find_in_path($type . '_' . $version . '.php', 'req/', true)) {
108
+            spip_log("spip_connect: serveur $index version '$version' non defini pour '$type'", _LOG_HS);
109
+
110
+            // ne plus reessayer
111
+            return $GLOBALS['connexions'][$index][$version] = [];
112
+        }
113
+    }
114
+    $GLOBALS['connexions'][$index][$version] = $GLOBALS[$jeu];
115
+    if ($old) {
116
+        return $GLOBALS['connexions'][$index];
117
+    }
118
+
119
+    $GLOBALS['connexions'][$index]['spip_connect_version'] = $GLOBALS['spip_connect_version'] ?? 0;
120
+
121
+    // initialisation de l'alphabet utilise dans les connexions SQL
122
+    // si l'installation l'a determine.
123
+    // Celui du serveur principal l'impose aux serveurs secondaires
124
+    // s'ils le connaissent
125
+
126
+    if (!$serveur) {
127
+        $charset = spip_connect_main($GLOBALS[$jeu], $GLOBALS['db_ok']['charset']);
128
+        if (!$charset) {
129
+            unset($GLOBALS['connexions'][$index]);
130
+            spip_log('spip_connect: absence de charset', _LOG_AVERTISSEMENT);
131
+
132
+            return false;
133
+        }
134
+    } else {
135
+        if ($GLOBALS['db_ok']['charset']) {
136
+            $charset = $GLOBALS['db_ok']['charset'];
137
+        }
138
+        // spip_meta n'existe pas toujours dans la base
139
+        // C'est le cas d'un dump sqlite par exemple
140
+        elseif (
141
+            $GLOBALS['connexions'][$index]['spip_connect_version']
142
+            and sql_showtable('spip_meta', true, $serveur)
143
+            and $r = sql_getfetsel('valeur', 'spip_meta', "nom='charset_sql_connexion'", '', '', '', '', $serveur)
144
+        ) {
145
+            $charset = $r;
146
+        } else {
147
+            $charset = -1;
148
+        }
149
+    }
150
+    if ($charset != -1) {
151
+        $f = $GLOBALS[$jeu]['set_charset'];
152
+        if (function_exists($f)) {
153
+            $f($charset, $serveur);
154
+        }
155
+    }
156
+
157
+    return $GLOBALS['connexions'][$index];
158 158
 }
159 159
 
160 160
 /**
@@ -163,12 +163,12 @@  discard block
 block discarded – undo
163 163
  * @param string $serveur Nom du connecteur de bdd utilisé
164 164
  **/
165 165
 function spip_sql_erreur($serveur = '') {
166
-	$connexion = spip_connect($serveur);
167
-	$e = sql_errno($serveur);
168
-	$t = (isset($connexion['type']) ? $connexion['type'] : 'sql');
169
-	$m = "Erreur $e de $t: " . sql_error($serveur) . "\nin " . sql_error_backtrace() . "\n" . trim($connexion['last']);
170
-	$f = $t . $serveur;
171
-	spip_log($m, $f . '.' . _LOG_ERREUR);
166
+    $connexion = spip_connect($serveur);
167
+    $e = sql_errno($serveur);
168
+    $t = (isset($connexion['type']) ? $connexion['type'] : 'sql');
169
+    $m = "Erreur $e de $t: " . sql_error($serveur) . "\nin " . sql_error_backtrace() . "\n" . trim($connexion['last']);
170
+    $f = $t . $serveur;
171
+    spip_log($m, $f . '.' . _LOG_ERREUR);
172 172
 }
173 173
 
174 174
 /**
@@ -190,23 +190,23 @@  discard block
 block discarded – undo
190 190
  *     - array : description de la connexion, si l'instruction sql est indisponible pour cette connexion
191 191
  **/
192 192
 function spip_connect_sql($version, $ins = '', $serveur = '', $continue = false) {
193
-	$desc = spip_connect($serveur, $version);
194
-	if (
195
-		$desc 
196
-		and $f = ($desc[$version][$ins] ?? '')
197
-		and function_exists($f)
198
-	 ) {
199
-		return $f;
200
-	}
201
-	if ($continue) {
202
-		return $desc;
203
-	}
204
-	if ($ins) {
205
-		spip_log("Le serveur '$serveur' version $version n'a pas '$ins'", _LOG_ERREUR);
206
-	}
207
-	include_spip('inc/minipres');
208
-	echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
209
-	exit;
193
+    $desc = spip_connect($serveur, $version);
194
+    if (
195
+        $desc 
196
+        and $f = ($desc[$version][$ins] ?? '')
197
+        and function_exists($f)
198
+        ) {
199
+        return $f;
200
+    }
201
+    if ($continue) {
202
+        return $desc;
203
+    }
204
+    if ($ins) {
205
+        spip_log("Le serveur '$serveur' version $version n'a pas '$ins'", _LOG_ERREUR);
206
+    }
207
+    include_spip('inc/minipres');
208
+    echo minipres(_T('info_travaux_titre'), _T('titre_probleme_technique'), ['status' => 503]);
209
+    exit;
210 210
 }
211 211
 
212 212
 /**
@@ -232,69 +232,69 @@  discard block
 block discarded – undo
232 232
  * @return array          Description de la connexion
233 233
  */
234 234
 function spip_connect_db(
235
-	$host,
236
-	$port,
237
-	$login,
238
-	$pass,
239
-	$db = '',
240
-	$type = 'mysql',
241
-	$prefixe = '',
242
-	$auth = '',
243
-	$charset = ''
235
+    $host,
236
+    $port,
237
+    $login,
238
+    $pass,
239
+    $db = '',
240
+    $type = 'mysql',
241
+    $prefixe = '',
242
+    $auth = '',
243
+    $charset = ''
244 244
 ) {
245
-	// temps avant nouvelle tentative de connexion
246
-	// suite a une connection echouee
247
-	if (!defined('_CONNECT_RETRY_DELAY')) {
248
-		define('_CONNECT_RETRY_DELAY', 30);
249
-	}
250
-
251
-	$f = '';
252
-	// un fichier de identifiant par combinaison (type,host,port,db)
253
-	// pour ne pas declarer tout indisponible d'un coup
254
-	// si en cours d'installation ou si db=@test@ on ne pose rien
255
-	// car c'est un test de connexion
256
-	if (!defined('_ECRIRE_INSTALL') and $db !== '@test@') {
257
-		$f = _DIR_TMP . $type . '.' . substr(md5($host . $port . $db), 0, 8) . '.out';
258
-	} elseif ($db == '@test@') {
259
-		$db = '';
260
-	}
261
-
262
-	if (
263
-		$f
264
-		and @file_exists($f)
265
-		and (time() - @filemtime($f) < _CONNECT_RETRY_DELAY)
266
-	) {
267
-		spip_log("Echec : $f recent. Pas de tentative de connexion", _LOG_HS);
268
-
269
-		return;
270
-	}
271
-
272
-	if (!$prefixe) {
273
-		$prefixe = $GLOBALS['table_prefix'] ?? $db;
274
-	}
275
-	$h = charger_fonction($type, 'req', true);
276
-	if (!$h) {
277
-		spip_log("les requetes $type ne sont pas fournies", _LOG_HS);
278
-
279
-		return;
280
-	}
281
-	if ($g = $h($host, $port, $login, $pass, $db, $prefixe)) {
282
-		if (!is_array($auth)) {
283
-			// compatibilite version 0.7 initiale
284
-			$g['ldap'] = $auth;
285
-			$auth = ['ldap' => $auth];
286
-		}
287
-		$g['authentification'] = $auth;
288
-		$g['type'] = $type;
289
-		$g['charset'] = $charset;
290
-
291
-		return $GLOBALS['db_ok'] = $g;
292
-	}
293
-	// En cas d'indisponibilite du serveur, eviter de le bombarder
294
-	if ($f) {
295
-		@touch($f);
296
-		spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type . '.' . _LOG_HS);
297
-	}
245
+    // temps avant nouvelle tentative de connexion
246
+    // suite a une connection echouee
247
+    if (!defined('_CONNECT_RETRY_DELAY')) {
248
+        define('_CONNECT_RETRY_DELAY', 30);
249
+    }
250
+
251
+    $f = '';
252
+    // un fichier de identifiant par combinaison (type,host,port,db)
253
+    // pour ne pas declarer tout indisponible d'un coup
254
+    // si en cours d'installation ou si db=@test@ on ne pose rien
255
+    // car c'est un test de connexion
256
+    if (!defined('_ECRIRE_INSTALL') and $db !== '@test@') {
257
+        $f = _DIR_TMP . $type . '.' . substr(md5($host . $port . $db), 0, 8) . '.out';
258
+    } elseif ($db == '@test@') {
259
+        $db = '';
260
+    }
261
+
262
+    if (
263
+        $f
264
+        and @file_exists($f)
265
+        and (time() - @filemtime($f) < _CONNECT_RETRY_DELAY)
266
+    ) {
267
+        spip_log("Echec : $f recent. Pas de tentative de connexion", _LOG_HS);
268
+
269
+        return;
270
+    }
271
+
272
+    if (!$prefixe) {
273
+        $prefixe = $GLOBALS['table_prefix'] ?? $db;
274
+    }
275
+    $h = charger_fonction($type, 'req', true);
276
+    if (!$h) {
277
+        spip_log("les requetes $type ne sont pas fournies", _LOG_HS);
278
+
279
+        return;
280
+    }
281
+    if ($g = $h($host, $port, $login, $pass, $db, $prefixe)) {
282
+        if (!is_array($auth)) {
283
+            // compatibilite version 0.7 initiale
284
+            $g['ldap'] = $auth;
285
+            $auth = ['ldap' => $auth];
286
+        }
287
+        $g['authentification'] = $auth;
288
+        $g['type'] = $type;
289
+        $g['charset'] = $charset;
290
+
291
+        return $GLOBALS['db_ok'] = $g;
292
+    }
293
+    // En cas d'indisponibilite du serveur, eviter de le bombarder
294
+    if ($f) {
295
+        @touch($f);
296
+        spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type . '.' . _LOG_HS);
297
+    }
298 298
 }
299 299
 
300 300
 
@@ -326,32 +326,32 @@  discard block
 block discarded – undo
326 326
  *     - nom du charset sinon
327 327
  **/
328 328
 function spip_connect_main($connexion, $charset_sql_connexion = '') {
329
-	if ($GLOBALS['spip_connect_version'] < 0.1 and _DIR_RESTREINT) {
330
-		include_spip('inc/headers');
331
-		redirige_url_ecrire('upgrade', 'reinstall=oui');
332
-	}
333
-
334
-	if (!($f = $connexion['select'])) {
335
-		return false;
336
-	}
337
-	// si le charset est fourni, l'utiliser
338
-	if ($charset_sql_connexion) {
339
-		return $charset_sql_connexion;
340
-	}
341
-	// sinon on regarde la table spip_meta
342
-	// en cas d'erreur select retourne la requette (is_string=true donc)
343
-	if (
344
-		!$r = $f('valeur', 'spip_meta', "nom='charset_sql_connexion'")
345
-		or is_string($r)
346
-	) {
347
-		return false;
348
-	}
349
-	if (!($f = $connexion['fetch'])) {
350
-		return false;
351
-	}
352
-	$r = $f($r);
353
-
354
-	return (isset($r['valeur']) && $r['valeur']) ? $r['valeur'] : -1;
329
+    if ($GLOBALS['spip_connect_version'] < 0.1 and _DIR_RESTREINT) {
330
+        include_spip('inc/headers');
331
+        redirige_url_ecrire('upgrade', 'reinstall=oui');
332
+    }
333
+
334
+    if (!($f = $connexion['select'])) {
335
+        return false;
336
+    }
337
+    // si le charset est fourni, l'utiliser
338
+    if ($charset_sql_connexion) {
339
+        return $charset_sql_connexion;
340
+    }
341
+    // sinon on regarde la table spip_meta
342
+    // en cas d'erreur select retourne la requette (is_string=true donc)
343
+    if (
344
+        !$r = $f('valeur', 'spip_meta', "nom='charset_sql_connexion'")
345
+        or is_string($r)
346
+    ) {
347
+        return false;
348
+    }
349
+    if (!($f = $connexion['fetch'])) {
350
+        return false;
351
+    }
352
+    $r = $f($r);
353
+
354
+    return (isset($r['valeur']) && $r['valeur']) ? $r['valeur'] : -1;
355 355
 }
356 356
 
357 357
 /**
@@ -367,9 +367,9 @@  discard block
 block discarded – undo
367 367
  * @return array
368 368
  */
369 369
 function spip_connect_ldap($serveur = '') {
370
-	include_spip('auth/ldap');
370
+    include_spip('auth/ldap');
371 371
 
372
-	return auth_ldap_connect($serveur);
372
+    return auth_ldap_connect($serveur);
373 373
 }
374 374
 
375 375
 /**
@@ -385,16 +385,16 @@  discard block
 block discarded – undo
385 385
  * @return string Valeur échappée.
386 386
  **/
387 387
 function _q($a): string {
388
-	if (is_numeric($a)) {
389
-		return strval($a);
390
-	} elseif (is_array($a)) {
391
-		return join(',', array_map('_q', $a));
392
-	} elseif (is_scalar($a)) {
393
-		return ("'" . addslashes($a) . "'");
394
-	} elseif ($a === null) {
395
-		return "''";
396
-	}
397
-	throw new \RuntimeException("Can’t use _q with " . gettype($a));
388
+    if (is_numeric($a)) {
389
+        return strval($a);
390
+    } elseif (is_array($a)) {
391
+        return join(',', array_map('_q', $a));
392
+    } elseif (is_scalar($a)) {
393
+        return ("'" . addslashes($a) . "'");
394
+    } elseif ($a === null) {
395
+        return "''";
396
+    }
397
+    throw new \RuntimeException("Can’t use _q with " . gettype($a));
398 398
 }
399 399
 
400 400
 /**
@@ -410,66 +410,66 @@  discard block
 block discarded – undo
410 410
  * @return array
411 411
  */
412 412
 function query_echappe_textes($query, $uniqid = null) {
413
-	static $codeEchappements = null;
414
-	if (is_null($codeEchappements) or $uniqid) {
415
-		if (is_null($uniqid)) {
416
-			$uniqid = uniqid();
417
-		}
418
-		$uniqid = substr(md5($uniqid), 0, 4);
419
-		$codeEchappements = ['\\\\' => "\x1@#{$uniqid}#@\x1", "\\'" => "\x2@#{$uniqid}#@\x2", '\\"' => "\x3@#{$uniqid}#@\x3"];
420
-	}
421
-	if ($query === null) {
422
-		return $codeEchappements;
423
-	}
424
-
425
-	// si la query contient deja des codes d'echappement on va s'emmeler les pinceaux et donc on ne touche a rien
426
-	// ce n'est pas un cas legitime
427
-	foreach ($codeEchappements as $codeEchappement) {
428
-		if (strpos($query, $codeEchappement) !== false) {
429
-			return [$query, []];
430
-		}
431
-	}
432
-
433
-	$query_echappees = str_replace(array_keys($codeEchappements), array_values($codeEchappements), $query);
434
-	if (preg_match_all("/('[^']*')|(\"[^\"]*\")/S", $query_echappees, $textes)) {
435
-		$textes = reset($textes); // indice 0 du match
436
-		switch (count($textes)) {
437
-			case 0:
438
-				$replace = [];
439
-				break;
440
-			case 1:
441
-				$replace = ['%1$s'];
442
-				break;
443
-			case 2:
444
-				$replace = ['%1$s', '%2$s'];
445
-				break;
446
-			case 3:
447
-				$replace = ['%1$s', '%2$s', '%3$s'];
448
-				break;
449
-			case 4:
450
-				$replace = ['%1$s', '%2$s', '%3$s', '%4$s'];
451
-				break;
452
-			case 5:
453
-				$replace = ['%1$s', '%2$s', '%3$s', '%4$s', '%5$s'];
454
-				break;
455
-			default:
456
-				$replace = range(1, count($textes));
457
-				$replace = '%' . implode('$s,%', $replace) . '$s';
458
-				$replace = explode(',', $replace);
459
-				break;
460
-		}
461
-		$query_echappees = str_replace($textes, $replace, $query_echappees);
462
-	} else {
463
-		$textes = [];
464
-	}
465
-
466
-	// si il reste des quotes simples ou doubles, c'est qu'on s'est emmelles les pinceaux
467
-	// dans le doute on ne touche a rien
468
-	if (strpbrk($query_echappees, "'\"") !== false) {
469
-		return [$query, []];
470
-	}
471
-
472
-	return [$query_echappees, $textes];
413
+    static $codeEchappements = null;
414
+    if (is_null($codeEchappements) or $uniqid) {
415
+        if (is_null($uniqid)) {
416
+            $uniqid = uniqid();
417
+        }
418
+        $uniqid = substr(md5($uniqid), 0, 4);
419
+        $codeEchappements = ['\\\\' => "\x1@#{$uniqid}#@\x1", "\\'" => "\x2@#{$uniqid}#@\x2", '\\"' => "\x3@#{$uniqid}#@\x3"];
420
+    }
421
+    if ($query === null) {
422
+        return $codeEchappements;
423
+    }
424
+
425
+    // si la query contient deja des codes d'echappement on va s'emmeler les pinceaux et donc on ne touche a rien
426
+    // ce n'est pas un cas legitime
427
+    foreach ($codeEchappements as $codeEchappement) {
428
+        if (strpos($query, $codeEchappement) !== false) {
429
+            return [$query, []];
430
+        }
431
+    }
432
+
433
+    $query_echappees = str_replace(array_keys($codeEchappements), array_values($codeEchappements), $query);
434
+    if (preg_match_all("/('[^']*')|(\"[^\"]*\")/S", $query_echappees, $textes)) {
435
+        $textes = reset($textes); // indice 0 du match
436
+        switch (count($textes)) {
437
+            case 0:
438
+                $replace = [];
439
+                break;
440
+            case 1:
441
+                $replace = ['%1$s'];
442
+                break;
443
+            case 2:
444
+                $replace = ['%1$s', '%2$s'];
445
+                break;
446
+            case 3:
447
+                $replace = ['%1$s', '%2$s', '%3$s'];
448
+                break;
449
+            case 4:
450
+                $replace = ['%1$s', '%2$s', '%3$s', '%4$s'];
451
+                break;
452
+            case 5:
453
+                $replace = ['%1$s', '%2$s', '%3$s', '%4$s', '%5$s'];
454
+                break;
455
+            default:
456
+                $replace = range(1, count($textes));
457
+                $replace = '%' . implode('$s,%', $replace) . '$s';
458
+                $replace = explode(',', $replace);
459
+                break;
460
+        }
461
+        $query_echappees = str_replace($textes, $replace, $query_echappees);
462
+    } else {
463
+        $textes = [];
464
+    }
465
+
466
+    // si il reste des quotes simples ou doubles, c'est qu'on s'est emmelles les pinceaux
467
+    // dans le doute on ne touche a rien
468
+    if (strpbrk($query_echappees, "'\"") !== false) {
469
+        return [$query, []];
470
+    }
471
+
472
+    return [$query_echappees, $textes];
473 473
 }
474 474
 
475 475
 /**
@@ -483,14 +483,14 @@  discard block
 block discarded – undo
483 483
  * @return string
484 484
  */
485 485
 function query_reinjecte_textes($query, $textes) {
486
-	// recuperer les codes echappements
487
-	$codeEchappements = query_echappe_textes(null);
486
+    // recuperer les codes echappements
487
+    $codeEchappements = query_echappe_textes(null);
488 488
 
489
-	$query = sprintf($query, ...$textes);
489
+    $query = sprintf($query, ...$textes);
490 490
 
491
-	$query = str_replace(array_values($codeEchappements), array_keys($codeEchappements), $query);
491
+    $query = str_replace(array_values($codeEchappements), array_keys($codeEchappements), $query);
492 492
 
493
-	return $query;
493
+    return $query;
494 494
 }
495 495
 
496 496
 
@@ -509,7 +509,7 @@  discard block
 block discarded – undo
509 509
  **/
510 510
 function spip_query($query, $serveur = '') {
511 511
 
512
-	$f = spip_connect_sql($GLOBALS['spip_sql_version'], 'query', $serveur, true);
512
+    $f = spip_connect_sql($GLOBALS['spip_sql_version'], 'query', $serveur, true);
513 513
 
514
-	return function_exists($f) ? $f($query, $serveur) : false;
514
+    return function_exists($f) ? $f($query, $serveur) : false;
515 515
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19 19
 	return;
20 20
 }
21
-require_once _ROOT_RESTREINT . 'base/objets.php';
21
+require_once _ROOT_RESTREINT.'base/objets.php';
22 22
 
23 23
 
24 24
 /**
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 		$f = (!preg_match('/^[\w\.]*$/', $serveur))
60 60
 			? '' // nom de serveur mal ecrit
61 61
 			: ($serveur ?
62
-				(_DIR_CONNECT . $serveur . '.php') // serveur externe
62
+				(_DIR_CONNECT.$serveur.'.php') // serveur externe
63 63
 				: (_FILE_CONNECT ? _FILE_CONNECT // serveur principal ok
64 64
 					: ($install ? _FILE_CONNECT_TMP // init du serveur principal
65 65
 						: ''))); // installation pas faite
@@ -102,9 +102,9 @@  discard block
 block discarded – undo
102 102
 	// chargement de la version du jeu de fonctions
103 103
 	// si pas dans le fichier par defaut
104 104
 	$type = $GLOBALS['db_ok']['type'];
105
-	$jeu = 'spip_' . $type . '_functions_' . $version;
105
+	$jeu = 'spip_'.$type.'_functions_'.$version;
106 106
 	if (!isset($GLOBALS[$jeu])) {
107
-		if (!find_in_path($type . '_' . $version . '.php', 'req/', true)) {
107
+		if (!find_in_path($type.'_'.$version.'.php', 'req/', true)) {
108 108
 			spip_log("spip_connect: serveur $index version '$version' non defini pour '$type'", _LOG_HS);
109 109
 
110 110
 			// ne plus reessayer
@@ -166,9 +166,9 @@  discard block
 block discarded – undo
166 166
 	$connexion = spip_connect($serveur);
167 167
 	$e = sql_errno($serveur);
168 168
 	$t = (isset($connexion['type']) ? $connexion['type'] : 'sql');
169
-	$m = "Erreur $e de $t: " . sql_error($serveur) . "\nin " . sql_error_backtrace() . "\n" . trim($connexion['last']);
170
-	$f = $t . $serveur;
171
-	spip_log($m, $f . '.' . _LOG_ERREUR);
169
+	$m = "Erreur $e de $t: ".sql_error($serveur)."\nin ".sql_error_backtrace()."\n".trim($connexion['last']);
170
+	$f = $t.$serveur;
171
+	spip_log($m, $f.'.'._LOG_ERREUR);
172 172
 }
173 173
 
174 174
 /**
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	// si en cours d'installation ou si db=@test@ on ne pose rien
255 255
 	// car c'est un test de connexion
256 256
 	if (!defined('_ECRIRE_INSTALL') and $db !== '@test@') {
257
-		$f = _DIR_TMP . $type . '.' . substr(md5($host . $port . $db), 0, 8) . '.out';
257
+		$f = _DIR_TMP.$type.'.'.substr(md5($host.$port.$db), 0, 8).'.out';
258 258
 	} elseif ($db == '@test@') {
259 259
 		$db = '';
260 260
 	}
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 	// En cas d'indisponibilite du serveur, eviter de le bombarder
294 294
 	if ($f) {
295 295
 		@touch($f);
296
-		spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type . '.' . _LOG_HS);
296
+		spip_log("Echec connexion serveur $type : host[$host] port[$port] login[$login] base[$db]", $type.'.'._LOG_HS);
297 297
 	}
298 298
 }
299 299
 
@@ -390,11 +390,11 @@  discard block
 block discarded – undo
390 390
 	} elseif (is_array($a)) {
391 391
 		return join(',', array_map('_q', $a));
392 392
 	} elseif (is_scalar($a)) {
393
-		return ("'" . addslashes($a) . "'");
393
+		return ("'".addslashes($a)."'");
394 394
 	} elseif ($a === null) {
395 395
 		return "''";
396 396
 	}
397
-	throw new \RuntimeException("Can’t use _q with " . gettype($a));
397
+	throw new \RuntimeException("Can’t use _q with ".gettype($a));
398 398
 }
399 399
 
400 400
 /**
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 				break;
455 455
 			default:
456 456
 				$replace = range(1, count($textes));
457
-				$replace = '%' . implode('$s,%', $replace) . '$s';
457
+				$replace = '%'.implode('$s,%', $replace).'$s';
458 458
 				$replace = explode(',', $replace);
459 459
 				break;
460 460
 		}
Please login to merge, or discard this patch.
ecrire/base/objets.php 1 patch
Indentation   +1256 added lines, -1256 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -32,11 +32,11 @@  discard block
 block discarded – undo
32 32
  * @return void
33 33
  **/
34 34
 function array_set_merge(&$table, $index, $valeur) {
35
-	if (!isset($table[$index])) {
36
-		$table[$index] = $valeur;
37
-	} else {
38
-		$table[$index] = array_merge($table[$index], $valeur);
39
-	}
35
+    if (!isset($table[$index])) {
36
+        $table[$index] = $valeur;
37
+    } else {
38
+        $table[$index] = array_merge($table[$index], $valeur);
39
+    }
40 40
 }
41 41
 
42 42
 /**
@@ -53,440 +53,440 @@  discard block
 block discarded – undo
53 53
  * @return array|bool
54 54
  */
55 55
 function lister_tables_objets_sql(?string $table_sql = null, $desc = []) {
56
-	static $deja_la = false;
57
-	static $infos_tables = null;
58
-	static $md5 = null;
59
-	static $plugin_hash = null;
60
-
61
-	// plugins hash connu ? non si _CACHE_PLUGINS_OPT est pas encore chargé.
62
-	$_PLUGINS_HASH = defined('_PLUGINS_HASH') ? _PLUGINS_HASH : '!_CACHE_PLUGINS_OPT';
63
-
64
-	// prealablement recuperer les tables_principales
65
-	if (is_null($infos_tables) or $plugin_hash !== $_PLUGINS_HASH) {
66
-		// pas de reentrance (cas base/serial)
67
-		if ($deja_la) {
68
-			spip_log('Re-entrance anormale sur lister_tables_objets_sql : '
69
-				. var_export(debug_backtrace(), true), _LOG_CRITIQUE);
70
-
71
-			return ($table_sql === '::md5' ? $md5 : []);
72
-		}
73
-		$deja_la = true;
74
-		$plugin_hash = $_PLUGINS_HASH; // avant de lancer les pipelines
75
-
76
-		// recuperer les declarations explicites ancienne mode
77
-		// qui servent a completer declarer_tables_objets_sql
78
-		base_serial($GLOBALS['tables_principales']);
79
-		base_auxiliaires($GLOBALS['tables_auxiliaires']);
80
-		$infos_tables = [
81
-			'spip_articles' => [
82
-				'page' => 'article',
83
-				'texte_retour' => 'icone_retour_article',
84
-				'texte_modifier' => 'icone_modifier_article',
85
-				'texte_creer' => 'icone_ecrire_article',
86
-				'texte_objets' => 'public:articles',
87
-				'texte_objet' => 'public:article',
88
-				'texte_signale_edition' => 'texte_travail_article',
89
-				'info_aucun_objet' => 'info_aucun_article',
90
-				'info_1_objet' => 'info_1_article',
91
-				'info_nb_objets' => 'info_nb_articles',
92
-				'texte_logo_objet' => 'logo_article',
93
-				'texte_langue_objet' => 'titre_langue_article',
94
-				'texte_definir_comme_traduction_objet' => 'trad_lier',
95
-				'titre' => 'titre, lang',
96
-				'date' => 'date',
97
-				'principale' => 'oui',
98
-				'introduction_longueur' => '500',
99
-				'champs_editables' => [
100
-					'surtitre',
101
-					'titre',
102
-					'soustitre',
103
-					'descriptif',
104
-					'nom_site',
105
-					'url_site',
106
-					'chapo',
107
-					'texte',
108
-					'ps',
109
-					'virtuel'
110
-				],
111
-				'champs_versionnes' => [
112
-					'id_rubrique',
113
-					'surtitre',
114
-					'titre',
115
-					'soustitre',
116
-					'jointure_auteurs',
117
-					'descriptif',
118
-					'nom_site',
119
-					'url_site',
120
-					'chapo',
121
-					'texte',
122
-					'ps'
123
-				],
124
-				'field' => [
125
-					'id_article' => 'bigint(21) NOT NULL',
126
-					'surtitre' => "text DEFAULT '' NOT NULL",
127
-					'titre' => "text DEFAULT '' NOT NULL",
128
-					'soustitre' => "text DEFAULT '' NOT NULL",
129
-					'id_rubrique' => "bigint(21) DEFAULT '0' NOT NULL",
130
-					'descriptif' => "text DEFAULT '' NOT NULL",
131
-					'chapo' => "mediumtext DEFAULT '' NOT NULL",
132
-					'texte' => "longtext DEFAULT '' NOT NULL",
133
-					'ps' => "mediumtext DEFAULT '' NOT NULL",
134
-					'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
135
-					'statut' => "varchar(10) DEFAULT '0' NOT NULL",
136
-					'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
137
-					'maj' => 'TIMESTAMP',
138
-					'export' => "VARCHAR(10) DEFAULT 'oui'",
139
-					'date_redac' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
140
-					'visites' => "integer DEFAULT '0' NOT NULL",
141
-					'referers' => "integer DEFAULT '0' NOT NULL",
142
-					'popularite' => "DOUBLE DEFAULT '0' NOT NULL",
143
-					'accepter_forum' => "CHAR(3) DEFAULT '' NOT NULL",
144
-					'date_modif' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
145
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
146
-					'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
147
-					'id_trad' => "bigint(21) DEFAULT '0' NOT NULL",
148
-					'nom_site' => "tinytext DEFAULT '' NOT NULL",
149
-					'url_site' => "text DEFAULT '' NOT NULL",
150
-					'virtuel' => "text DEFAULT '' NOT NULL",
151
-				],
152
-				'key' => [
153
-					'PRIMARY KEY' => 'id_article',
154
-					'KEY id_rubrique' => 'id_rubrique',
155
-					'KEY id_secteur' => 'id_secteur',
156
-					'KEY id_trad' => 'id_trad',
157
-					'KEY lang' => 'lang',
158
-					'KEY statut' => 'statut, date',
159
-				],
160
-				'join' => [
161
-					'id_article' => 'id_article',
162
-					'id_rubrique' => 'id_rubrique'
163
-				],
164
-				'parent' => [
165
-					['type' => 'rubrique', 'champ' => 'id_rubrique']
166
-				],
167
-				'rechercher_champs' => [
168
-					'surtitre' => 5,
169
-					'titre' => 8,
170
-					'soustitre' => 5,
171
-					'chapo' => 3,
172
-					'texte' => 1,
173
-					'ps' => 1,
174
-					'nom_site' => 1,
175
-					'url_site' => 1,
176
-					'descriptif' => 4
177
-				],
178
-				'rechercher_jointures' => [
179
-					'auteur' => ['nom' => 10],
180
-				],
181
-				'statut' => [
182
-					[
183
-						'champ' => 'statut',
184
-						'publie' => 'publie',
185
-						'previsu' => 'publie,prop,prepa/auteur',
186
-						'post_date' => 'date',
187
-						'exception' => ['statut', 'tout']
188
-					]
189
-				],
190
-				'statut_titres' => [
191
-					'prepa' => 'info_article_redaction',
192
-					'prop' => 'info_article_propose',
193
-					'publie' => 'info_article_publie',
194
-					'refuse' => 'info_article_refuse',
195
-					'poubelle' => 'info_article_supprime'
196
-				],
197
-				'statut_textes_instituer' => [
198
-					'prepa' => 'texte_statut_en_cours_redaction',
199
-					'prop' => 'texte_statut_propose_evaluation',
200
-					'publie' => 'texte_statut_publie',
201
-					'refuse' => 'texte_statut_refuse',
202
-					'poubelle' => 'texte_statut_poubelle',
203
-				],
204
-				'texte_changer_statut' => 'texte_article_statut',
205
-				'aide_changer_statut' => 'artstatut',
206
-				'tables_jointures' => [
207
-					'profondeur' => 'rubriques',
208
-					#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
209
-				],
210
-			],
211
-			'spip_auteurs' => [
212
-				'page' => 'auteur',
213
-				'texte_retour' => 'icone_retour',
214
-				'texte_ajouter' => 'titre_ajouter_un_auteur',
215
-				'texte_modifier' => 'admin_modifier_auteur',
216
-				'texte_objets' => 'icone_auteurs',
217
-				'texte_objet' => 'public:auteur',
218
-				'info_aucun_objet' => 'info_aucun_auteur',
219
-				'info_1_objet' => 'info_1_auteur',
220
-				'info_nb_objets' => 'info_nb_auteurs',
221
-				'texte_logo_objet' => 'logo_auteur',
222
-				'texte_creer_associer' => 'creer_et_associer_un_auteur',
223
-				'titre' => "nom AS titre, '' AS lang",
224
-				'date' => 'date',
225
-				'principale' => 'oui',
226
-				'champs_editables' => ['nom', 'email', 'bio', 'nom_site', 'url_site', 'imessage', 'pgp'],
227
-				'champs_versionnes' => ['nom', 'bio', 'email', 'nom_site', 'url_site', 'login'],
228
-				'field' => [
229
-					'id_auteur' => 'bigint(21) NOT NULL',
230
-					'nom' => "text DEFAULT '' NOT NULL",
231
-					'bio' => "text DEFAULT '' NOT NULL",
232
-					'email' => "tinytext DEFAULT '' NOT NULL",
233
-					'nom_site' => "tinytext DEFAULT '' NOT NULL",
234
-					'url_site' => "text DEFAULT '' NOT NULL",
235
-					'login' => 'VARCHAR(255) BINARY',
236
-					'pass' => "tinytext DEFAULT '' NOT NULL",
237
-					'low_sec' => "tinytext DEFAULT '' NOT NULL",
238
-					'statut' => "varchar(255)  DEFAULT '0' NOT NULL",
239
-					'webmestre' => "varchar(3)  DEFAULT 'non' NOT NULL",
240
-					'maj' => 'TIMESTAMP',
241
-					'pgp' => "TEXT DEFAULT '' NOT NULL",
242
-					'htpass' => "tinytext DEFAULT '' NOT NULL",
243
-					'en_ligne' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
244
-					'alea_actuel' => 'tinytext',
245
-					'alea_futur' => 'tinytext',
246
-					'prefs' => 'text',
247
-					'cookie_oubli' => 'tinytext',
248
-					'source' => "VARCHAR(10) DEFAULT 'spip' NOT NULL",
249
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
250
-					'imessage' => "VARCHAR(3) DEFAULT '' NOT NULL"
251
-				],
252
-				'key' => [
253
-					'PRIMARY KEY' => 'id_auteur',
254
-					'KEY login' => 'login',
255
-					'KEY statut' => 'statut',
256
-					'KEY en_ligne' => 'en_ligne',
257
-				],
258
-				'join' => [
259
-					'id_auteur' => 'id_auteur',
260
-					'login' => 'login'
261
-				],
262
-				'rechercher_champs' => [
263
-					'nom' => 5,
264
-					'bio' => 1,
265
-					'email' => 1,
266
-					'nom_site' => 1,
267
-					'url_site' => 1,
268
-					'login' => 1
269
-				],
270
-				// 2 conditions pour les auteurs : statut!=poubelle,
271
-				// et avoir des articles publies
272
-				'statut' => [
273
-					[
274
-						'champ' => 'statut',
275
-						'publie' => '!5poubelle',
276
-						'previsu' => '!5poubelle',
277
-						'exception' => 'statut'
278
-					],
279
-					[
280
-						'champ' => [
281
-							['spip_auteurs_liens', 'id_auteur'],
282
-							[
283
-								'spip_articles',
284
-								['id_objet', 'id_article', 'objet', 'article']
285
-							],
286
-							'statut'
287
-						],
288
-						'publie' => 'publie',
289
-						'previsu' => '!',
290
-						'post_date' => 'date',
291
-						'exception' => ['statut', 'lien', 'tout']
292
-					],
293
-				],
294
-				'statut_images' => [
295
-					'auteur-6forum-16.png',
296
-					'0minirezo' => 'auteur-0minirezo-16.png',
297
-					'1comite' => 'auteur-1comite-16.png',
298
-					'6forum' => 'auteur-6forum-16.png',
299
-					'5poubelle' => 'auteur-5poubelle-16.png',
300
-					'nouveau' => ''
301
-				],
302
-				'statut_titres' => [
303
-					'titre_image_visiteur',
304
-					'0minirezo' => 'titre_image_administrateur',
305
-					'1comite' => 'titre_image_redacteur_02',
306
-					'6forum' => 'titre_image_visiteur',
307
-					'5poubelle' => 'titre_image_auteur_supprime',
308
-				],
309
-				'tables_jointures' => [#'auteurs_liens' // declaration generique plus bas
310
-				],
311
-			],
312
-			'spip_rubriques' => [
313
-				'page' => 'rubrique',
314
-				'url_voir' => 'rubrique',
315
-				'url_edit' => 'rubrique_edit',
316
-				'texte_retour' => 'icone_retour',
317
-				'texte_objets' => 'public:rubriques',
318
-				'texte_objet' => 'public:rubrique',
319
-				'texte_modifier' => 'icone_modifier_rubrique',
320
-				'texte_creer' => 'icone_creer_rubrique',
321
-				'texte_ajouter' => 'titre_ajouter_une_rubrique',
322
-				'texte_creer_associer' => 'creer_et_associer_une_rubrique',
323
-				'info_aucun_objet' => 'info_aucun_rubrique',
324
-				'info_1_objet' => 'info_1_rubrique',
325
-				'info_nb_objets' => 'info_nb_rubriques',
326
-				'texte_logo_objet' => 'logo_rubrique',
327
-				'texte_langue_objet' => 'titre_langue_rubrique',
328
-				'texte_definir_comme_traduction_objet' => 'texte_definir_comme_traduction_rubrique',
329
-				'titre' => 'titre, lang',
330
-				'date' => 'date',
331
-				'principale' => 'oui',
332
-				'introduction_longueur' => '600',
333
-				'champs_editables' => ['titre', 'texte', 'descriptif', 'extra'],
334
-				'champs_versionnes' => ['titre', 'descriptif', 'texte'],
335
-				'field' => [
336
-					'id_rubrique' => 'bigint(21) NOT NULL',
337
-					'id_parent' => "bigint(21) DEFAULT '0' NOT NULL",
338
-					'titre' => "text DEFAULT '' NOT NULL",
339
-					'descriptif' => "text DEFAULT '' NOT NULL",
340
-					'texte' => "longtext DEFAULT '' NOT NULL",
341
-					'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
342
-					'maj' => 'TIMESTAMP',
343
-					'statut' => "varchar(10) DEFAULT '0' NOT NULL",
344
-					'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
345
-					'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
346
-					'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
347
-					'statut_tmp' => "varchar(10) DEFAULT '0' NOT NULL",
348
-					'date_tmp' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
349
-					'profondeur' => "smallint(5) DEFAULT '0' NOT NULL"
350
-				],
351
-				'key' => [
352
-					'PRIMARY KEY' => 'id_rubrique',
353
-					'KEY lang' => 'lang',
354
-					'KEY id_parent' => 'id_parent',
355
-				],
356
-				'parent' => [
357
-					['type' => 'rubrique', 'champ' => 'id_parent']
358
-				],
359
-				'rechercher_champs' => [
360
-					'titre' => 8,
361
-					'descriptif' => 5,
362
-					'texte' => 1
363
-				],
364
-				'statut' => [
365
-					[
366
-						'champ' => 'statut',
367
-						'publie' => 'publie',
368
-						'previsu' => '!',
369
-						'exception' => ['statut', 'tout']
370
-					],
371
-				],
372
-				'tables_jointures' => [#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
373
-				],
374
-			],
375
-			// toutes les tables ont le droit a une jointure sur les auteurs
376
-			['tables_jointures' => ['id_auteur' => 'auteurs_liens']]
377
-		];
378
-
379
-		// avant d'appeller les pipeline qui peuvent generer une reentrance a l'install
380
-		// initialiser la signature
381
-		$md5 = md5(serialize($infos_tables));
382
-
383
-		$GLOBALS['tables_principales'] = pipeline('declarer_tables_principales', $GLOBALS['tables_principales']);
384
-		$GLOBALS['tables_auxiliaires'] = pipeline('declarer_tables_auxiliaires', $GLOBALS['tables_auxiliaires']);
385
-		$infos_tables = pipeline('declarer_tables_objets_sql', $infos_tables);
386
-
387
-		// completer les informations manquantes ou implicites
388
-		$all = [];
389
-		foreach (array_keys($infos_tables) as $t) {
390
-			// les cles numeriques servent a declarer
391
-			// les proprietes applicables a tous les objets
392
-			// on les mets de cote
393
-			if (is_numeric($t)) {
394
-				$all = array_merge_recursive($all, $infos_tables[$t]);
395
-				unset($infos_tables[$t]);
396
-			} else {
397
-				$infos_tables[$t] = renseigner_table_objet_sql($t, $infos_tables[$t]);
398
-			}
399
-		}
400
-
401
-		// repercuter les proprietes generales communes a tous les objets
402
-		foreach (array_keys($infos_tables) as $t) {
403
-			foreach ($all as $i => $v) {
404
-				if (in_array($i, ['tables_jointures', 'champs_versionnes'])) {
405
-					$add = $all[$i];
406
-					// eviter les doublons de declaration de table jointure (ex des mots sur auteurs)
407
-					// pour les declarations generiques avec cles numeriques
408
-					if ($i == 'tables_jointures' and isset($infos_tables[$t][$i]) and count($infos_tables[$t][$i])) {
409
-						$doublons = array_intersect($infos_tables[$t][$i], $add);
410
-						foreach ($doublons as $d) {
411
-							if (
412
-								is_numeric(array_search($d, $infos_tables[$t][$i]))
413
-								and is_numeric($k = array_search($d, $add))
414
-							) {
415
-								unset($add[$k]);
416
-							}
417
-						}
418
-					}
419
-					$infos_tables[$t][$i] = array_merge(isset($infos_tables[$t][$i]) ? $infos_tables[$t][$i] : [], $add);
420
-				} else {
421
-					$infos_tables[$t][$i] = array_merge_recursive(
422
-						isset($infos_tables[$t][$i]) ? $infos_tables[$t][$i] : [],
423
-						$all[$i]
424
-					);
425
-				}
426
-			}
427
-		}
428
-
429
-		// completer les tables principales et auxiliaires
430
-		// avec celles declarees uniquement dans declarer_table_objets_sql
431
-		// pour assurer la compat en transition
432
-		foreach ($infos_tables as $table => $infos) {
433
-			$principale_ou_auxiliaire = ($infos['principale'] ? 'tables_principales' : 'tables_auxiliaires');
434
-			// memoriser des champs eventuels declares par des plugins dans le pipeline tables_xxx
435
-			// qui a ete appelle avant
436
-			$mem = (isset($GLOBALS[$principale_ou_auxiliaire][$table]) ? $GLOBALS[$principale_ou_auxiliaire][$table] : []);
437
-			// l'ajouter au tableau
438
-			$GLOBALS[$principale_ou_auxiliaire][$table] = [];
439
-			if (isset($infos['field']) and isset($infos['key'])) {
440
-				foreach (['field', 'key', 'join'] as $k) {
441
-					if (isset($infos_tables[$table][$k])) {
442
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = &$infos_tables[$table][$k];
443
-					}
444
-				}
445
-			} else {
446
-				// ici on ne renvoie que les declarations, donc RIEN
447
-				// pour avoir la vrai description en base, il faut passer par trouver_table
448
-				$GLOBALS[$principale_ou_auxiliaire][$table] = [];
449
-			}
450
-			if (count($mem)) {
451
-				foreach (array_keys($mem) as $k) {
452
-					if (isset($GLOBALS[$principale_ou_auxiliaire][$table][$k])) {
453
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = array_merge(
454
-							$GLOBALS[$principale_ou_auxiliaire][$table][$k],
455
-							$mem[$k]
456
-						);
457
-					} else {
458
-						$GLOBALS[$principale_ou_auxiliaire][$table][$k] = $mem[$k];
459
-					}
460
-				}
461
-			}
462
-		}
463
-
464
-		// recuperer les interfaces (table_titre, table_date)
465
-		// on ne le fait que dans un second temps pour que table_objet soit fonctionnel
466
-		// dans le pipeline de declarer_tables_interfaces
467
-		include_spip('public/interfaces');
468
-		foreach (array_keys($infos_tables) as $t) {
469
-			$infos_tables[$t] = renseigner_table_objet_interfaces($t, $infos_tables[$t]);
470
-		}
471
-
472
-		$deja_la = false;
473
-		// signature
474
-		$md5 = md5(serialize($infos_tables));
475
-	}
476
-	if ($table_sql === '::md5') {
477
-		return $md5;
478
-	}
479
-	if ($table_sql and !isset($infos_tables[$table_sql])) {
480
-		#$desc = renseigner_table_objet_sql($table_sql,$desc);
481
-		$desc = renseigner_table_objet_interfaces($table_sql, $desc);
482
-
483
-		return $desc;
484
-	}
485
-	if ($table_sql) {
486
-		return isset($infos_tables[$table_sql]) ? $infos_tables[$table_sql] : [];
487
-	}
488
-
489
-	return $infos_tables;
56
+    static $deja_la = false;
57
+    static $infos_tables = null;
58
+    static $md5 = null;
59
+    static $plugin_hash = null;
60
+
61
+    // plugins hash connu ? non si _CACHE_PLUGINS_OPT est pas encore chargé.
62
+    $_PLUGINS_HASH = defined('_PLUGINS_HASH') ? _PLUGINS_HASH : '!_CACHE_PLUGINS_OPT';
63
+
64
+    // prealablement recuperer les tables_principales
65
+    if (is_null($infos_tables) or $plugin_hash !== $_PLUGINS_HASH) {
66
+        // pas de reentrance (cas base/serial)
67
+        if ($deja_la) {
68
+            spip_log('Re-entrance anormale sur lister_tables_objets_sql : '
69
+                . var_export(debug_backtrace(), true), _LOG_CRITIQUE);
70
+
71
+            return ($table_sql === '::md5' ? $md5 : []);
72
+        }
73
+        $deja_la = true;
74
+        $plugin_hash = $_PLUGINS_HASH; // avant de lancer les pipelines
75
+
76
+        // recuperer les declarations explicites ancienne mode
77
+        // qui servent a completer declarer_tables_objets_sql
78
+        base_serial($GLOBALS['tables_principales']);
79
+        base_auxiliaires($GLOBALS['tables_auxiliaires']);
80
+        $infos_tables = [
81
+            'spip_articles' => [
82
+                'page' => 'article',
83
+                'texte_retour' => 'icone_retour_article',
84
+                'texte_modifier' => 'icone_modifier_article',
85
+                'texte_creer' => 'icone_ecrire_article',
86
+                'texte_objets' => 'public:articles',
87
+                'texte_objet' => 'public:article',
88
+                'texte_signale_edition' => 'texte_travail_article',
89
+                'info_aucun_objet' => 'info_aucun_article',
90
+                'info_1_objet' => 'info_1_article',
91
+                'info_nb_objets' => 'info_nb_articles',
92
+                'texte_logo_objet' => 'logo_article',
93
+                'texte_langue_objet' => 'titre_langue_article',
94
+                'texte_definir_comme_traduction_objet' => 'trad_lier',
95
+                'titre' => 'titre, lang',
96
+                'date' => 'date',
97
+                'principale' => 'oui',
98
+                'introduction_longueur' => '500',
99
+                'champs_editables' => [
100
+                    'surtitre',
101
+                    'titre',
102
+                    'soustitre',
103
+                    'descriptif',
104
+                    'nom_site',
105
+                    'url_site',
106
+                    'chapo',
107
+                    'texte',
108
+                    'ps',
109
+                    'virtuel'
110
+                ],
111
+                'champs_versionnes' => [
112
+                    'id_rubrique',
113
+                    'surtitre',
114
+                    'titre',
115
+                    'soustitre',
116
+                    'jointure_auteurs',
117
+                    'descriptif',
118
+                    'nom_site',
119
+                    'url_site',
120
+                    'chapo',
121
+                    'texte',
122
+                    'ps'
123
+                ],
124
+                'field' => [
125
+                    'id_article' => 'bigint(21) NOT NULL',
126
+                    'surtitre' => "text DEFAULT '' NOT NULL",
127
+                    'titre' => "text DEFAULT '' NOT NULL",
128
+                    'soustitre' => "text DEFAULT '' NOT NULL",
129
+                    'id_rubrique' => "bigint(21) DEFAULT '0' NOT NULL",
130
+                    'descriptif' => "text DEFAULT '' NOT NULL",
131
+                    'chapo' => "mediumtext DEFAULT '' NOT NULL",
132
+                    'texte' => "longtext DEFAULT '' NOT NULL",
133
+                    'ps' => "mediumtext DEFAULT '' NOT NULL",
134
+                    'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
135
+                    'statut' => "varchar(10) DEFAULT '0' NOT NULL",
136
+                    'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
137
+                    'maj' => 'TIMESTAMP',
138
+                    'export' => "VARCHAR(10) DEFAULT 'oui'",
139
+                    'date_redac' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
140
+                    'visites' => "integer DEFAULT '0' NOT NULL",
141
+                    'referers' => "integer DEFAULT '0' NOT NULL",
142
+                    'popularite' => "DOUBLE DEFAULT '0' NOT NULL",
143
+                    'accepter_forum' => "CHAR(3) DEFAULT '' NOT NULL",
144
+                    'date_modif' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
145
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
146
+                    'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
147
+                    'id_trad' => "bigint(21) DEFAULT '0' NOT NULL",
148
+                    'nom_site' => "tinytext DEFAULT '' NOT NULL",
149
+                    'url_site' => "text DEFAULT '' NOT NULL",
150
+                    'virtuel' => "text DEFAULT '' NOT NULL",
151
+                ],
152
+                'key' => [
153
+                    'PRIMARY KEY' => 'id_article',
154
+                    'KEY id_rubrique' => 'id_rubrique',
155
+                    'KEY id_secteur' => 'id_secteur',
156
+                    'KEY id_trad' => 'id_trad',
157
+                    'KEY lang' => 'lang',
158
+                    'KEY statut' => 'statut, date',
159
+                ],
160
+                'join' => [
161
+                    'id_article' => 'id_article',
162
+                    'id_rubrique' => 'id_rubrique'
163
+                ],
164
+                'parent' => [
165
+                    ['type' => 'rubrique', 'champ' => 'id_rubrique']
166
+                ],
167
+                'rechercher_champs' => [
168
+                    'surtitre' => 5,
169
+                    'titre' => 8,
170
+                    'soustitre' => 5,
171
+                    'chapo' => 3,
172
+                    'texte' => 1,
173
+                    'ps' => 1,
174
+                    'nom_site' => 1,
175
+                    'url_site' => 1,
176
+                    'descriptif' => 4
177
+                ],
178
+                'rechercher_jointures' => [
179
+                    'auteur' => ['nom' => 10],
180
+                ],
181
+                'statut' => [
182
+                    [
183
+                        'champ' => 'statut',
184
+                        'publie' => 'publie',
185
+                        'previsu' => 'publie,prop,prepa/auteur',
186
+                        'post_date' => 'date',
187
+                        'exception' => ['statut', 'tout']
188
+                    ]
189
+                ],
190
+                'statut_titres' => [
191
+                    'prepa' => 'info_article_redaction',
192
+                    'prop' => 'info_article_propose',
193
+                    'publie' => 'info_article_publie',
194
+                    'refuse' => 'info_article_refuse',
195
+                    'poubelle' => 'info_article_supprime'
196
+                ],
197
+                'statut_textes_instituer' => [
198
+                    'prepa' => 'texte_statut_en_cours_redaction',
199
+                    'prop' => 'texte_statut_propose_evaluation',
200
+                    'publie' => 'texte_statut_publie',
201
+                    'refuse' => 'texte_statut_refuse',
202
+                    'poubelle' => 'texte_statut_poubelle',
203
+                ],
204
+                'texte_changer_statut' => 'texte_article_statut',
205
+                'aide_changer_statut' => 'artstatut',
206
+                'tables_jointures' => [
207
+                    'profondeur' => 'rubriques',
208
+                    #'id_auteur' => 'auteurs_liens' // declaration generique plus bas
209
+                ],
210
+            ],
211
+            'spip_auteurs' => [
212
+                'page' => 'auteur',
213
+                'texte_retour' => 'icone_retour',
214
+                'texte_ajouter' => 'titre_ajouter_un_auteur',
215
+                'texte_modifier' => 'admin_modifier_auteur',
216
+                'texte_objets' => 'icone_auteurs',
217
+                'texte_objet' => 'public:auteur',
218
+                'info_aucun_objet' => 'info_aucun_auteur',
219
+                'info_1_objet' => 'info_1_auteur',
220
+                'info_nb_objets' => 'info_nb_auteurs',
221
+                'texte_logo_objet' => 'logo_auteur',
222
+                'texte_creer_associer' => 'creer_et_associer_un_auteur',
223
+                'titre' => "nom AS titre, '' AS lang",
224
+                'date' => 'date',
225
+                'principale' => 'oui',
226
+                'champs_editables' => ['nom', 'email', 'bio', 'nom_site', 'url_site', 'imessage', 'pgp'],
227
+                'champs_versionnes' => ['nom', 'bio', 'email', 'nom_site', 'url_site', 'login'],
228
+                'field' => [
229
+                    'id_auteur' => 'bigint(21) NOT NULL',
230
+                    'nom' => "text DEFAULT '' NOT NULL",
231
+                    'bio' => "text DEFAULT '' NOT NULL",
232
+                    'email' => "tinytext DEFAULT '' NOT NULL",
233
+                    'nom_site' => "tinytext DEFAULT '' NOT NULL",
234
+                    'url_site' => "text DEFAULT '' NOT NULL",
235
+                    'login' => 'VARCHAR(255) BINARY',
236
+                    'pass' => "tinytext DEFAULT '' NOT NULL",
237
+                    'low_sec' => "tinytext DEFAULT '' NOT NULL",
238
+                    'statut' => "varchar(255)  DEFAULT '0' NOT NULL",
239
+                    'webmestre' => "varchar(3)  DEFAULT 'non' NOT NULL",
240
+                    'maj' => 'TIMESTAMP',
241
+                    'pgp' => "TEXT DEFAULT '' NOT NULL",
242
+                    'htpass' => "tinytext DEFAULT '' NOT NULL",
243
+                    'en_ligne' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
244
+                    'alea_actuel' => 'tinytext',
245
+                    'alea_futur' => 'tinytext',
246
+                    'prefs' => 'text',
247
+                    'cookie_oubli' => 'tinytext',
248
+                    'source' => "VARCHAR(10) DEFAULT 'spip' NOT NULL",
249
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
250
+                    'imessage' => "VARCHAR(3) DEFAULT '' NOT NULL"
251
+                ],
252
+                'key' => [
253
+                    'PRIMARY KEY' => 'id_auteur',
254
+                    'KEY login' => 'login',
255
+                    'KEY statut' => 'statut',
256
+                    'KEY en_ligne' => 'en_ligne',
257
+                ],
258
+                'join' => [
259
+                    'id_auteur' => 'id_auteur',
260
+                    'login' => 'login'
261
+                ],
262
+                'rechercher_champs' => [
263
+                    'nom' => 5,
264
+                    'bio' => 1,
265
+                    'email' => 1,
266
+                    'nom_site' => 1,
267
+                    'url_site' => 1,
268
+                    'login' => 1
269
+                ],
270
+                // 2 conditions pour les auteurs : statut!=poubelle,
271
+                // et avoir des articles publies
272
+                'statut' => [
273
+                    [
274
+                        'champ' => 'statut',
275
+                        'publie' => '!5poubelle',
276
+                        'previsu' => '!5poubelle',
277
+                        'exception' => 'statut'
278
+                    ],
279
+                    [
280
+                        'champ' => [
281
+                            ['spip_auteurs_liens', 'id_auteur'],
282
+                            [
283
+                                'spip_articles',
284
+                                ['id_objet', 'id_article', 'objet', 'article']
285
+                            ],
286
+                            'statut'
287
+                        ],
288
+                        'publie' => 'publie',
289
+                        'previsu' => '!',
290
+                        'post_date' => 'date',
291
+                        'exception' => ['statut', 'lien', 'tout']
292
+                    ],
293
+                ],
294
+                'statut_images' => [
295
+                    'auteur-6forum-16.png',
296
+                    '0minirezo' => 'auteur-0minirezo-16.png',
297
+                    '1comite' => 'auteur-1comite-16.png',
298
+                    '6forum' => 'auteur-6forum-16.png',
299
+                    '5poubelle' => 'auteur-5poubelle-16.png',
300
+                    'nouveau' => ''
301
+                ],
302
+                'statut_titres' => [
303
+                    'titre_image_visiteur',
304
+                    '0minirezo' => 'titre_image_administrateur',
305
+                    '1comite' => 'titre_image_redacteur_02',
306
+                    '6forum' => 'titre_image_visiteur',
307
+                    '5poubelle' => 'titre_image_auteur_supprime',
308
+                ],
309
+                'tables_jointures' => [#'auteurs_liens' // declaration generique plus bas
310
+                ],
311
+            ],
312
+            'spip_rubriques' => [
313
+                'page' => 'rubrique',
314
+                'url_voir' => 'rubrique',
315
+                'url_edit' => 'rubrique_edit',
316
+                'texte_retour' => 'icone_retour',
317
+                'texte_objets' => 'public:rubriques',
318
+                'texte_objet' => 'public:rubrique',
319
+                'texte_modifier' => 'icone_modifier_rubrique',
320
+                'texte_creer' => 'icone_creer_rubrique',
321
+                'texte_ajouter' => 'titre_ajouter_une_rubrique',
322
+                'texte_creer_associer' => 'creer_et_associer_une_rubrique',
323
+                'info_aucun_objet' => 'info_aucun_rubrique',
324
+                'info_1_objet' => 'info_1_rubrique',
325
+                'info_nb_objets' => 'info_nb_rubriques',
326
+                'texte_logo_objet' => 'logo_rubrique',
327
+                'texte_langue_objet' => 'titre_langue_rubrique',
328
+                'texte_definir_comme_traduction_objet' => 'texte_definir_comme_traduction_rubrique',
329
+                'titre' => 'titre, lang',
330
+                'date' => 'date',
331
+                'principale' => 'oui',
332
+                'introduction_longueur' => '600',
333
+                'champs_editables' => ['titre', 'texte', 'descriptif', 'extra'],
334
+                'champs_versionnes' => ['titre', 'descriptif', 'texte'],
335
+                'field' => [
336
+                    'id_rubrique' => 'bigint(21) NOT NULL',
337
+                    'id_parent' => "bigint(21) DEFAULT '0' NOT NULL",
338
+                    'titre' => "text DEFAULT '' NOT NULL",
339
+                    'descriptif' => "text DEFAULT '' NOT NULL",
340
+                    'texte' => "longtext DEFAULT '' NOT NULL",
341
+                    'id_secteur' => "bigint(21) DEFAULT '0' NOT NULL",
342
+                    'maj' => 'TIMESTAMP',
343
+                    'statut' => "varchar(10) DEFAULT '0' NOT NULL",
344
+                    'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
345
+                    'lang' => "VARCHAR(10) DEFAULT '' NOT NULL",
346
+                    'langue_choisie' => "VARCHAR(3) DEFAULT 'non'",
347
+                    'statut_tmp' => "varchar(10) DEFAULT '0' NOT NULL",
348
+                    'date_tmp' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
349
+                    'profondeur' => "smallint(5) DEFAULT '0' NOT NULL"
350
+                ],
351
+                'key' => [
352
+                    'PRIMARY KEY' => 'id_rubrique',
353
+                    'KEY lang' => 'lang',
354
+                    'KEY id_parent' => 'id_parent',
355
+                ],
356
+                'parent' => [
357
+                    ['type' => 'rubrique', 'champ' => 'id_parent']
358
+                ],
359
+                'rechercher_champs' => [
360
+                    'titre' => 8,
361
+                    'descriptif' => 5,
362
+                    'texte' => 1
363
+                ],
364
+                'statut' => [
365
+                    [
366
+                        'champ' => 'statut',
367
+                        'publie' => 'publie',
368
+                        'previsu' => '!',
369
+                        'exception' => ['statut', 'tout']
370
+                    ],
371
+                ],
372
+                'tables_jointures' => [#'id_auteur' => 'auteurs_liens' // declaration generique plus bas
373
+                ],
374
+            ],
375
+            // toutes les tables ont le droit a une jointure sur les auteurs
376
+            ['tables_jointures' => ['id_auteur' => 'auteurs_liens']]
377
+        ];
378
+
379
+        // avant d'appeller les pipeline qui peuvent generer une reentrance a l'install
380
+        // initialiser la signature
381
+        $md5 = md5(serialize($infos_tables));
382
+
383
+        $GLOBALS['tables_principales'] = pipeline('declarer_tables_principales', $GLOBALS['tables_principales']);
384
+        $GLOBALS['tables_auxiliaires'] = pipeline('declarer_tables_auxiliaires', $GLOBALS['tables_auxiliaires']);
385
+        $infos_tables = pipeline('declarer_tables_objets_sql', $infos_tables);
386
+
387
+        // completer les informations manquantes ou implicites
388
+        $all = [];
389
+        foreach (array_keys($infos_tables) as $t) {
390
+            // les cles numeriques servent a declarer
391
+            // les proprietes applicables a tous les objets
392
+            // on les mets de cote
393
+            if (is_numeric($t)) {
394
+                $all = array_merge_recursive($all, $infos_tables[$t]);
395
+                unset($infos_tables[$t]);
396
+            } else {
397
+                $infos_tables[$t] = renseigner_table_objet_sql($t, $infos_tables[$t]);
398
+            }
399
+        }
400
+
401
+        // repercuter les proprietes generales communes a tous les objets
402
+        foreach (array_keys($infos_tables) as $t) {
403
+            foreach ($all as $i => $v) {
404
+                if (in_array($i, ['tables_jointures', 'champs_versionnes'])) {
405
+                    $add = $all[$i];
406
+                    // eviter les doublons de declaration de table jointure (ex des mots sur auteurs)
407
+                    // pour les declarations generiques avec cles numeriques
408
+                    if ($i == 'tables_jointures' and isset($infos_tables[$t][$i]) and count($infos_tables[$t][$i])) {
409
+                        $doublons = array_intersect($infos_tables[$t][$i], $add);
410
+                        foreach ($doublons as $d) {
411
+                            if (
412
+                                is_numeric(array_search($d, $infos_tables[$t][$i]))
413
+                                and is_numeric($k = array_search($d, $add))
414
+                            ) {
415
+                                unset($add[$k]);
416
+                            }
417
+                        }
418
+                    }
419
+                    $infos_tables[$t][$i] = array_merge(isset($infos_tables[$t][$i]) ? $infos_tables[$t][$i] : [], $add);
420
+                } else {
421
+                    $infos_tables[$t][$i] = array_merge_recursive(
422
+                        isset($infos_tables[$t][$i]) ? $infos_tables[$t][$i] : [],
423
+                        $all[$i]
424
+                    );
425
+                }
426
+            }
427
+        }
428
+
429
+        // completer les tables principales et auxiliaires
430
+        // avec celles declarees uniquement dans declarer_table_objets_sql
431
+        // pour assurer la compat en transition
432
+        foreach ($infos_tables as $table => $infos) {
433
+            $principale_ou_auxiliaire = ($infos['principale'] ? 'tables_principales' : 'tables_auxiliaires');
434
+            // memoriser des champs eventuels declares par des plugins dans le pipeline tables_xxx
435
+            // qui a ete appelle avant
436
+            $mem = (isset($GLOBALS[$principale_ou_auxiliaire][$table]) ? $GLOBALS[$principale_ou_auxiliaire][$table] : []);
437
+            // l'ajouter au tableau
438
+            $GLOBALS[$principale_ou_auxiliaire][$table] = [];
439
+            if (isset($infos['field']) and isset($infos['key'])) {
440
+                foreach (['field', 'key', 'join'] as $k) {
441
+                    if (isset($infos_tables[$table][$k])) {
442
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = &$infos_tables[$table][$k];
443
+                    }
444
+                }
445
+            } else {
446
+                // ici on ne renvoie que les declarations, donc RIEN
447
+                // pour avoir la vrai description en base, il faut passer par trouver_table
448
+                $GLOBALS[$principale_ou_auxiliaire][$table] = [];
449
+            }
450
+            if (count($mem)) {
451
+                foreach (array_keys($mem) as $k) {
452
+                    if (isset($GLOBALS[$principale_ou_auxiliaire][$table][$k])) {
453
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = array_merge(
454
+                            $GLOBALS[$principale_ou_auxiliaire][$table][$k],
455
+                            $mem[$k]
456
+                        );
457
+                    } else {
458
+                        $GLOBALS[$principale_ou_auxiliaire][$table][$k] = $mem[$k];
459
+                    }
460
+                }
461
+            }
462
+        }
463
+
464
+        // recuperer les interfaces (table_titre, table_date)
465
+        // on ne le fait que dans un second temps pour que table_objet soit fonctionnel
466
+        // dans le pipeline de declarer_tables_interfaces
467
+        include_spip('public/interfaces');
468
+        foreach (array_keys($infos_tables) as $t) {
469
+            $infos_tables[$t] = renseigner_table_objet_interfaces($t, $infos_tables[$t]);
470
+        }
471
+
472
+        $deja_la = false;
473
+        // signature
474
+        $md5 = md5(serialize($infos_tables));
475
+    }
476
+    if ($table_sql === '::md5') {
477
+        return $md5;
478
+    }
479
+    if ($table_sql and !isset($infos_tables[$table_sql])) {
480
+        #$desc = renseigner_table_objet_sql($table_sql,$desc);
481
+        $desc = renseigner_table_objet_interfaces($table_sql, $desc);
482
+
483
+        return $desc;
484
+    }
485
+    if ($table_sql) {
486
+        return isset($infos_tables[$table_sql]) ? $infos_tables[$table_sql] : [];
487
+    }
488
+
489
+    return $infos_tables;
490 490
 }
491 491
 
492 492
 
@@ -501,27 +501,27 @@  discard block
 block discarded – undo
501 501
  **/
502 502
 function base_serial(&$tables_principales) {
503 503
 
504
-	$spip_jobs = [
505
-		'id_job' => 'bigint(21) NOT NULL',
506
-		'descriptif' => "text DEFAULT '' NOT NULL",
507
-		'fonction' => 'varchar(255) NOT NULL', //nom de la fonction
508
-		'args' => "longblob DEFAULT '' NOT NULL", // arguments
509
-		'md5args' => "char(32) NOT NULL default ''", // signature des arguments
510
-		'inclure' => 'varchar(255) NOT NULL', // fichier a inclure ou path/ pour charger_fonction
511
-		'priorite' => 'smallint(6) NOT NULL default 0',
512
-		'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // date au plus tot
513
-		'status' => 'tinyint NOT NULL default 1',
514
-	];
515
-
516
-	$spip_jobs_key = [
517
-		'PRIMARY KEY' => 'id_job',
518
-		'KEY date' => 'date',
519
-		'KEY status' => 'status',
520
-	];
521
-
522
-	/// Attention: mes_fonctions peut avoir deja defini cette variable
523
-	/// il faut donc rajouter, mais pas reinitialiser
524
-	$tables_principales['spip_jobs'] = ['field' => &$spip_jobs, 'key' => &$spip_jobs_key];
504
+    $spip_jobs = [
505
+        'id_job' => 'bigint(21) NOT NULL',
506
+        'descriptif' => "text DEFAULT '' NOT NULL",
507
+        'fonction' => 'varchar(255) NOT NULL', //nom de la fonction
508
+        'args' => "longblob DEFAULT '' NOT NULL", // arguments
509
+        'md5args' => "char(32) NOT NULL default ''", // signature des arguments
510
+        'inclure' => 'varchar(255) NOT NULL', // fichier a inclure ou path/ pour charger_fonction
511
+        'priorite' => 'smallint(6) NOT NULL default 0',
512
+        'date' => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // date au plus tot
513
+        'status' => 'tinyint NOT NULL default 1',
514
+    ];
515
+
516
+    $spip_jobs_key = [
517
+        'PRIMARY KEY' => 'id_job',
518
+        'KEY date' => 'date',
519
+        'KEY status' => 'status',
520
+    ];
521
+
522
+    /// Attention: mes_fonctions peut avoir deja defini cette variable
523
+    /// il faut donc rajouter, mais pas reinitialiser
524
+    $tables_principales['spip_jobs'] = ['field' => &$spip_jobs, 'key' => &$spip_jobs_key];
525 525
 }
526 526
 
527 527
 
@@ -533,71 +533,71 @@  discard block
 block discarded – undo
533 533
  * @return void
534 534
  **/
535 535
 function base_auxiliaires(&$tables_auxiliaires) {
536
-	$spip_resultats = [
537
-		'recherche' => "char(16) DEFAULT '' NOT NULL",
538
-		'id' => 'INT UNSIGNED NOT NULL',
539
-		'points' => "INT UNSIGNED DEFAULT '0' NOT NULL",
540
-		'table_objet' => "varchar(30) DEFAULT '' NOT NULL",
541
-		'serveur' => "char(16) DEFAULT '' NOT NULL", // hash md5 partiel du serveur de base ('' pour le serveur principal)
542
-		'maj' => 'TIMESTAMP'
543
-	];
544
-
545
-	$spip_resultats_key = [// pas de cle ni index, ca fait des insertions plus rapides et les requetes jointes utilisees en recheche ne sont pas plus lentes ...
546
-	];
547
-
548
-	$spip_auteurs_liens = [
549
-		'id_auteur' => "bigint(21) DEFAULT '0' NOT NULL",
550
-		'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
551
-		'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
552
-		'vu' => "VARCHAR(6) DEFAULT 'non' NOT NULL"
553
-	];
554
-
555
-	$spip_auteurs_liens_key = [
556
-		'PRIMARY KEY' => 'id_auteur,id_objet,objet',
557
-		'KEY id_auteur' => 'id_auteur',
558
-		'KEY id_objet' => 'id_objet',
559
-		'KEY objet' => 'objet',
560
-	];
561
-
562
-	$spip_meta = [
563
-		'nom' => 'VARCHAR (255) NOT NULL',
564
-		'valeur' => "text DEFAULT ''",
565
-		'impt' => "ENUM('non', 'oui') DEFAULT 'oui' NOT NULL",
566
-		'maj' => 'TIMESTAMP'
567
-	];
568
-
569
-	$spip_meta_key = [
570
-		'PRIMARY KEY' => 'nom'
571
-	];
572
-
573
-	$spip_jobs_liens = [
574
-		'id_job' => "bigint(21) DEFAULT '0' NOT NULL",
575
-		'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
576
-		'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
577
-	];
578
-
579
-	$spip_jobs_liens_key = [
580
-		'PRIMARY KEY' => 'id_job,id_objet,objet',
581
-		'KEY id_job' => 'id_job'
582
-	];
583
-
584
-	$tables_auxiliaires['spip_auteurs_liens'] = [
585
-		'field' => &$spip_auteurs_liens,
586
-		'key' => &$spip_auteurs_liens_key
587
-	];
588
-
589
-	$tables_auxiliaires['spip_meta'] = [
590
-		'field' => &$spip_meta,
591
-		'key' => &$spip_meta_key
592
-	];
593
-	$tables_auxiliaires['spip_resultats'] = [
594
-		'field' => &$spip_resultats,
595
-		'key' => &$spip_resultats_key
596
-	];
597
-	$tables_auxiliaires['spip_jobs_liens'] = [
598
-		'field' => &$spip_jobs_liens,
599
-		'key' => &$spip_jobs_liens_key
600
-	];
536
+    $spip_resultats = [
537
+        'recherche' => "char(16) DEFAULT '' NOT NULL",
538
+        'id' => 'INT UNSIGNED NOT NULL',
539
+        'points' => "INT UNSIGNED DEFAULT '0' NOT NULL",
540
+        'table_objet' => "varchar(30) DEFAULT '' NOT NULL",
541
+        'serveur' => "char(16) DEFAULT '' NOT NULL", // hash md5 partiel du serveur de base ('' pour le serveur principal)
542
+        'maj' => 'TIMESTAMP'
543
+    ];
544
+
545
+    $spip_resultats_key = [// pas de cle ni index, ca fait des insertions plus rapides et les requetes jointes utilisees en recheche ne sont pas plus lentes ...
546
+    ];
547
+
548
+    $spip_auteurs_liens = [
549
+        'id_auteur' => "bigint(21) DEFAULT '0' NOT NULL",
550
+        'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
551
+        'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
552
+        'vu' => "VARCHAR(6) DEFAULT 'non' NOT NULL"
553
+    ];
554
+
555
+    $spip_auteurs_liens_key = [
556
+        'PRIMARY KEY' => 'id_auteur,id_objet,objet',
557
+        'KEY id_auteur' => 'id_auteur',
558
+        'KEY id_objet' => 'id_objet',
559
+        'KEY objet' => 'objet',
560
+    ];
561
+
562
+    $spip_meta = [
563
+        'nom' => 'VARCHAR (255) NOT NULL',
564
+        'valeur' => "text DEFAULT ''",
565
+        'impt' => "ENUM('non', 'oui') DEFAULT 'oui' NOT NULL",
566
+        'maj' => 'TIMESTAMP'
567
+    ];
568
+
569
+    $spip_meta_key = [
570
+        'PRIMARY KEY' => 'nom'
571
+    ];
572
+
573
+    $spip_jobs_liens = [
574
+        'id_job' => "bigint(21) DEFAULT '0' NOT NULL",
575
+        'id_objet' => "bigint(21) DEFAULT '0' NOT NULL",
576
+        'objet' => "VARCHAR (25) DEFAULT '' NOT NULL",
577
+    ];
578
+
579
+    $spip_jobs_liens_key = [
580
+        'PRIMARY KEY' => 'id_job,id_objet,objet',
581
+        'KEY id_job' => 'id_job'
582
+    ];
583
+
584
+    $tables_auxiliaires['spip_auteurs_liens'] = [
585
+        'field' => &$spip_auteurs_liens,
586
+        'key' => &$spip_auteurs_liens_key
587
+    ];
588
+
589
+    $tables_auxiliaires['spip_meta'] = [
590
+        'field' => &$spip_meta,
591
+        'key' => &$spip_meta_key
592
+    ];
593
+    $tables_auxiliaires['spip_resultats'] = [
594
+        'field' => &$spip_resultats,
595
+        'key' => &$spip_resultats_key
596
+    ];
597
+    $tables_auxiliaires['spip_jobs_liens'] = [
598
+        'field' => &$spip_jobs_liens,
599
+        'key' => &$spip_jobs_liens_key
600
+    ];
601 601
 }
602 602
 
603 603
 
@@ -654,129 +654,129 @@  discard block
 block discarded – undo
654 654
  * @return array
655 655
  */
656 656
 function renseigner_table_objet_sql($table_sql, &$infos) {
657
-	if (!isset($infos['type'])) {
658
-		// si on arrive de base/trouver_table, on a la cle primaire :
659
-		// s'en servir pour extrapoler le type
660
-		if (isset($infos['key']['PRIMARY KEY'])) {
661
-			$primary = $infos['key']['PRIMARY KEY'];
662
-			$primary = explode(',', $primary);
663
-			$primary = reset($primary);
664
-			$infos['type'] = preg_replace(',^spip_|^id_|s$,', '', $primary);
665
-		} else {
666
-			$infos['type'] = preg_replace(',^spip_|s$,', '', $table_sql);
667
-		}
668
-	}
669
-	if (!isset($infos['type_surnoms'])) {
670
-		$infos['type_surnoms'] = [];
671
-	}
672
-
673
-	if (!isset($infos['table_objet'])) {
674
-		$infos['table_objet'] = preg_replace(',^spip_,', '', $table_sql);
675
-	}
676
-	if (!isset($infos['table_objet_surnoms'])) {
677
-		$infos['table_objet_surnoms'] = [];
678
-	}
679
-
680
-	if (!isset($infos['principale'])) {
681
-		$infos['principale'] = (isset($GLOBALS['tables_principales'][$table_sql]) ? 'oui' : false);
682
-	}
683
-
684
-	// normaliser pour pouvoir tester en php $infos['principale']?
685
-	// et dans une boucle {principale=oui}
686
-	$infos['principale'] = (($infos['principale'] and $infos['principale'] != 'non') ? 'oui' : false);
687
-
688
-	// declarer et normaliser pour pouvoir tester en php $infos['editable']?
689
-	// et dans une boucle {editable=oui}
690
-	if (!isset($infos['editable'])) {
691
-		$infos['editable'] = 'oui';
692
-	}
693
-
694
-	$infos['editable'] = (($infos['editable'] and $infos['editable'] != 'non') ? 'oui' : false);
695
-
696
-	// les urls publiques sont par defaut page=type pour les tables principales, et rien pour les autres
697
-	// seules les exceptions sont donc a declarer
698
-	if (!isset($infos['page'])) {
699
-		$infos['page'] = ($infos['principale'] ? $infos['type'] : '');
700
-	}
701
-
702
-	if (!isset($infos['url_voir'])) {
703
-		$infos['url_voir'] = $infos['type'];
704
-	}
705
-	if (!isset($infos['url_edit'])) {
706
-		$infos['url_edit'] = $infos['url_voir'] . ($infos['editable'] ? '_edit' : '');
707
-	}
708
-	if (!isset($infos['icone_objet'])) {
709
-		$infos['icone_objet'] = $infos['type'];
710
-	}
711
-
712
-	// chaines de langue
713
-	// par defaut : objet:icone_xxx_objet
714
-	if (!isset($infos['texte_retour'])) {
715
-		$infos['texte_retour'] = 'icone_retour';
716
-	}
717
-	if (!isset($infos['texte_modifier'])) {
718
-		$infos['texte_modifier'] = $infos['type'] . ':' . 'icone_modifier_' . $infos['type'];
719
-	}
720
-	if (!isset($infos['texte_creer'])) {
721
-		$infos['texte_creer'] = $infos['type'] . ':' . 'icone_creer_' . $infos['type'];
722
-	}
723
-	if (!isset($infos['texte_creer_associer'])) {
724
-		$infos['texte_creer_associer'] = $infos['type'] . ':' . 'texte_creer_associer_' . $infos['type'];
725
-	}
726
-	if (!isset($infos['texte_ajouter'])) {
727
-		// Ajouter un X
728
-		$infos['texte_ajouter'] = $infos['type'] . ':' . 'texte_ajouter_' . $infos['type'];
729
-	}
730
-	if (!isset($infos['texte_objets'])) {
731
-		$infos['texte_objets'] = $infos['type'] . ':' . 'titre_' . $infos['table_objet'];
732
-	}
733
-	if (!isset($infos['texte_objet'])) {
734
-		$infos['texte_objet'] = $infos['type'] . ':' . 'titre_' . $infos['type'];
735
-	}
736
-	if (!isset($infos['texte_logo_objet'])) {
737
-		// objet:titre_logo_objet "Logo de ce X"
738
-		$infos['texte_logo_objet'] = $infos['type'] . ':' . 'titre_logo_' . $infos['type'];
739
-	}
740
-	if (!isset($infos['texte_langue_objet'])) {
741
-		// objet:texte_langue_objet "Langue de ce X"
742
-		$infos['texte_langue_objet'] = $infos['type'] . ':' . 'titre_langue_' . $infos['type'];
743
-	}
744
-	if (!isset($infos['texte_definir_comme_traduction_objet'])) {
745
-		// "Ce X est une traduction du X numéro :"
746
-		$infos['texte_definir_comme_traduction_objet'] = $infos['type'] . ':' . 'texte_definir_comme_traduction_' . $infos['type'];
747
-	}
748
-
749
-	// objet:info_aucun_objet
750
-	if (!isset($infos['info_aucun_objet'])) {
751
-		$infos['info_aucun_objet'] = $infos['type'] . ':' . 'info_aucun_' . $infos['type'];
752
-	}
753
-	// objet:info_1_objet
754
-	if (!isset($infos['info_1_objet'])) {
755
-		$infos['info_1_objet'] = $infos['type'] . ':' . 'info_1_' . $infos['type'];
756
-	}
757
-	// objet:info_nb_objets
758
-	if (!isset($infos['info_nb_objets'])) {
759
-		$infos['info_nb_objets'] = $infos['type'] . ':' . 'info_nb_' . $infos['table_objet'];
760
-	}
761
-
762
-	if (!isset($infos['champs_editables'])) {
763
-		$infos['champs_editables'] = [];
764
-	}
765
-	if (!isset($infos['champs_versionnes'])) {
766
-		$infos['champs_versionnes'] = [];
767
-	}
768
-	if (!isset($infos['rechercher_champs'])) {
769
-		$infos['rechercher_champs'] = [];
770
-	}
771
-	if (!isset($infos['rechercher_jointures'])) {
772
-		$infos['rechercher_jointures'] = [];
773
-	}
774
-
775
-	if (!isset($infos['modeles'])) {
776
-		$infos['modeles'] = [$infos['type']];
777
-	}
778
-
779
-	return $infos;
657
+    if (!isset($infos['type'])) {
658
+        // si on arrive de base/trouver_table, on a la cle primaire :
659
+        // s'en servir pour extrapoler le type
660
+        if (isset($infos['key']['PRIMARY KEY'])) {
661
+            $primary = $infos['key']['PRIMARY KEY'];
662
+            $primary = explode(',', $primary);
663
+            $primary = reset($primary);
664
+            $infos['type'] = preg_replace(',^spip_|^id_|s$,', '', $primary);
665
+        } else {
666
+            $infos['type'] = preg_replace(',^spip_|s$,', '', $table_sql);
667
+        }
668
+    }
669
+    if (!isset($infos['type_surnoms'])) {
670
+        $infos['type_surnoms'] = [];
671
+    }
672
+
673
+    if (!isset($infos['table_objet'])) {
674
+        $infos['table_objet'] = preg_replace(',^spip_,', '', $table_sql);
675
+    }
676
+    if (!isset($infos['table_objet_surnoms'])) {
677
+        $infos['table_objet_surnoms'] = [];
678
+    }
679
+
680
+    if (!isset($infos['principale'])) {
681
+        $infos['principale'] = (isset($GLOBALS['tables_principales'][$table_sql]) ? 'oui' : false);
682
+    }
683
+
684
+    // normaliser pour pouvoir tester en php $infos['principale']?
685
+    // et dans une boucle {principale=oui}
686
+    $infos['principale'] = (($infos['principale'] and $infos['principale'] != 'non') ? 'oui' : false);
687
+
688
+    // declarer et normaliser pour pouvoir tester en php $infos['editable']?
689
+    // et dans une boucle {editable=oui}
690
+    if (!isset($infos['editable'])) {
691
+        $infos['editable'] = 'oui';
692
+    }
693
+
694
+    $infos['editable'] = (($infos['editable'] and $infos['editable'] != 'non') ? 'oui' : false);
695
+
696
+    // les urls publiques sont par defaut page=type pour les tables principales, et rien pour les autres
697
+    // seules les exceptions sont donc a declarer
698
+    if (!isset($infos['page'])) {
699
+        $infos['page'] = ($infos['principale'] ? $infos['type'] : '');
700
+    }
701
+
702
+    if (!isset($infos['url_voir'])) {
703
+        $infos['url_voir'] = $infos['type'];
704
+    }
705
+    if (!isset($infos['url_edit'])) {
706
+        $infos['url_edit'] = $infos['url_voir'] . ($infos['editable'] ? '_edit' : '');
707
+    }
708
+    if (!isset($infos['icone_objet'])) {
709
+        $infos['icone_objet'] = $infos['type'];
710
+    }
711
+
712
+    // chaines de langue
713
+    // par defaut : objet:icone_xxx_objet
714
+    if (!isset($infos['texte_retour'])) {
715
+        $infos['texte_retour'] = 'icone_retour';
716
+    }
717
+    if (!isset($infos['texte_modifier'])) {
718
+        $infos['texte_modifier'] = $infos['type'] . ':' . 'icone_modifier_' . $infos['type'];
719
+    }
720
+    if (!isset($infos['texte_creer'])) {
721
+        $infos['texte_creer'] = $infos['type'] . ':' . 'icone_creer_' . $infos['type'];
722
+    }
723
+    if (!isset($infos['texte_creer_associer'])) {
724
+        $infos['texte_creer_associer'] = $infos['type'] . ':' . 'texte_creer_associer_' . $infos['type'];
725
+    }
726
+    if (!isset($infos['texte_ajouter'])) {
727
+        // Ajouter un X
728
+        $infos['texte_ajouter'] = $infos['type'] . ':' . 'texte_ajouter_' . $infos['type'];
729
+    }
730
+    if (!isset($infos['texte_objets'])) {
731
+        $infos['texte_objets'] = $infos['type'] . ':' . 'titre_' . $infos['table_objet'];
732
+    }
733
+    if (!isset($infos['texte_objet'])) {
734
+        $infos['texte_objet'] = $infos['type'] . ':' . 'titre_' . $infos['type'];
735
+    }
736
+    if (!isset($infos['texte_logo_objet'])) {
737
+        // objet:titre_logo_objet "Logo de ce X"
738
+        $infos['texte_logo_objet'] = $infos['type'] . ':' . 'titre_logo_' . $infos['type'];
739
+    }
740
+    if (!isset($infos['texte_langue_objet'])) {
741
+        // objet:texte_langue_objet "Langue de ce X"
742
+        $infos['texte_langue_objet'] = $infos['type'] . ':' . 'titre_langue_' . $infos['type'];
743
+    }
744
+    if (!isset($infos['texte_definir_comme_traduction_objet'])) {
745
+        // "Ce X est une traduction du X numéro :"
746
+        $infos['texte_definir_comme_traduction_objet'] = $infos['type'] . ':' . 'texte_definir_comme_traduction_' . $infos['type'];
747
+    }
748
+
749
+    // objet:info_aucun_objet
750
+    if (!isset($infos['info_aucun_objet'])) {
751
+        $infos['info_aucun_objet'] = $infos['type'] . ':' . 'info_aucun_' . $infos['type'];
752
+    }
753
+    // objet:info_1_objet
754
+    if (!isset($infos['info_1_objet'])) {
755
+        $infos['info_1_objet'] = $infos['type'] . ':' . 'info_1_' . $infos['type'];
756
+    }
757
+    // objet:info_nb_objets
758
+    if (!isset($infos['info_nb_objets'])) {
759
+        $infos['info_nb_objets'] = $infos['type'] . ':' . 'info_nb_' . $infos['table_objet'];
760
+    }
761
+
762
+    if (!isset($infos['champs_editables'])) {
763
+        $infos['champs_editables'] = [];
764
+    }
765
+    if (!isset($infos['champs_versionnes'])) {
766
+        $infos['champs_versionnes'] = [];
767
+    }
768
+    if (!isset($infos['rechercher_champs'])) {
769
+        $infos['rechercher_champs'] = [];
770
+    }
771
+    if (!isset($infos['rechercher_jointures'])) {
772
+        $infos['rechercher_jointures'] = [];
773
+    }
774
+
775
+    if (!isset($infos['modeles'])) {
776
+        $infos['modeles'] = [$infos['type']];
777
+    }
778
+
779
+    return $infos;
780 780
 }
781 781
 
782 782
 /**
@@ -793,30 +793,30 @@  discard block
 block discarded – undo
793 793
  * @return array
794 794
  */
795 795
 function renseigner_table_objet_interfaces($table_sql, &$infos) {
796
-	if (!isset($infos['titre'])) {
797
-		if (isset($infos['table_objet']) and isset($GLOBALS['table_titre'][$infos['table_objet']])) {
798
-			$infos['titre'] = $GLOBALS['table_titre'][$infos['table_objet']];
799
-		} else {
800
-			$infos['titre'] = ((isset($infos['field']['titre'])) ? 'titre,' : "'' as titre,");
801
-			$infos['titre'] .= ((isset($infos['field']['lang'])) ? 'lang' : "'' as lang");
802
-		}
803
-	}
804
-	if (!isset($infos['date'])) {
805
-		if (isset($infos['table_objet']) and isset($GLOBALS['table_date'][$infos['table_objet']])) {
806
-			$infos['date'] = $GLOBALS['table_date'][$infos['table_objet']];
807
-		} else {
808
-			$infos['date'] = ((isset($infos['field']['date'])) ? 'date' : '');
809
-		}
810
-	}
811
-
812
-	$infos['statut'] ??= $GLOBALS['table_statut'][$table_sql] ?? '';
813
-	$infos['tables_jointures'] ??= [];
814
-
815
-	if (isset($GLOBALS['tables_jointures'][$table_sql])) {
816
-		$infos['tables_jointures'] = array_merge($infos['tables_jointures'], $GLOBALS['tables_jointures'][$table_sql]);
817
-	}
818
-
819
-	return $infos;
796
+    if (!isset($infos['titre'])) {
797
+        if (isset($infos['table_objet']) and isset($GLOBALS['table_titre'][$infos['table_objet']])) {
798
+            $infos['titre'] = $GLOBALS['table_titre'][$infos['table_objet']];
799
+        } else {
800
+            $infos['titre'] = ((isset($infos['field']['titre'])) ? 'titre,' : "'' as titre,");
801
+            $infos['titre'] .= ((isset($infos['field']['lang'])) ? 'lang' : "'' as lang");
802
+        }
803
+    }
804
+    if (!isset($infos['date'])) {
805
+        if (isset($infos['table_objet']) and isset($GLOBALS['table_date'][$infos['table_objet']])) {
806
+            $infos['date'] = $GLOBALS['table_date'][$infos['table_objet']];
807
+        } else {
808
+            $infos['date'] = ((isset($infos['field']['date'])) ? 'date' : '');
809
+        }
810
+    }
811
+
812
+    $infos['statut'] ??= $GLOBALS['table_statut'][$table_sql] ?? '';
813
+    $infos['tables_jointures'] ??= [];
814
+
815
+    if (isset($GLOBALS['tables_jointures'][$table_sql])) {
816
+        $infos['tables_jointures'] = array_merge($infos['tables_jointures'], $GLOBALS['tables_jointures'][$table_sql]);
817
+    }
818
+
819
+    return $infos;
820 820
 }
821 821
 
822 822
 /**
@@ -827,13 +827,13 @@  discard block
 block discarded – undo
827 827
  *     Liste et descriptions des tables principales
828 828
  **/
829 829
 function lister_tables_principales() {
830
-	static $done = false;
831
-	if (!$done or !count($GLOBALS['tables_principales'])) {
832
-		lister_tables_objets_sql();
833
-		$done = true;
834
-	}
830
+    static $done = false;
831
+    if (!$done or !count($GLOBALS['tables_principales'])) {
832
+        lister_tables_objets_sql();
833
+        $done = true;
834
+    }
835 835
 
836
-	return $GLOBALS['tables_principales'];
836
+    return $GLOBALS['tables_principales'];
837 837
 }
838 838
 
839 839
 /**
@@ -844,13 +844,13 @@  discard block
 block discarded – undo
844 844
  *     Liste et descriptions des tables auxiliaires
845 845
  **/
846 846
 function lister_tables_auxiliaires() {
847
-	static $done = false;
848
-	if (!$done or !count($GLOBALS['tables_auxiliaires'])) {
849
-		lister_tables_objets_sql();
850
-		$done = true;
851
-	}
847
+    static $done = false;
848
+    if (!$done or !count($GLOBALS['tables_auxiliaires'])) {
849
+        lister_tables_objets_sql();
850
+        $done = true;
851
+    }
852 852
 
853
-	return $GLOBALS['tables_auxiliaires'];
853
+    return $GLOBALS['tables_auxiliaires'];
854 854
 }
855 855
 
856 856
 /**
@@ -859,45 +859,45 @@  discard block
 block discarded – undo
859 859
  * @return array
860 860
  */
861 861
 function lister_tables_objets_surnoms() {
862
-	static $surnoms = null;
863
-	static $md5 = null;
864
-	if (
865
-		!$surnoms
866
-		or $md5 != lister_tables_objets_sql('::md5')
867
-	) {
868
-		// passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
869
-		// pour compatibilite, car il faut dorenavent utiliser
870
-		// declarer_table_objets_sql
871
-		$surnoms = pipeline(
872
-			'declarer_tables_objets_surnoms',
873
-			[
874
-				# pour les modeles
875
-				# a enlever ?
876
-				'doc' => 'documents',
877
-				'img' => 'documents',
878
-				'emb' => 'documents',
879
-			]
880
-		);
881
-		$infos_tables = lister_tables_objets_sql();
882
-		foreach ($infos_tables as $t => $infos) {
883
-			// cas de base type=>table
884
-			// et preg_replace(',^spip_|^id_|s$,',table)=>table
885
-			if ($infos['table_objet']) { // securite, si la fonction est appelee trop tot, c'est vide
886
-				// optimisations pour table_objet
887
-				//$surnoms[$infos['type']] = $infos['table_objet'];
888
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['table_objet'];
889
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['table_objet'];
890
-				if (is_array($infos['table_objet_surnoms']) and count($infos['table_objet_surnoms'])) {
891
-					foreach ($infos['table_objet_surnoms'] as $surnom) {
892
-						$surnoms[$surnom] = $infos['table_objet'];
893
-					}
894
-				}
895
-			}
896
-		}
897
-		$md5 = lister_tables_objets_sql('::md5');
898
-	}
899
-
900
-	return $surnoms;
862
+    static $surnoms = null;
863
+    static $md5 = null;
864
+    if (
865
+        !$surnoms
866
+        or $md5 != lister_tables_objets_sql('::md5')
867
+    ) {
868
+        // passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
869
+        // pour compatibilite, car il faut dorenavent utiliser
870
+        // declarer_table_objets_sql
871
+        $surnoms = pipeline(
872
+            'declarer_tables_objets_surnoms',
873
+            [
874
+                # pour les modeles
875
+                # a enlever ?
876
+                'doc' => 'documents',
877
+                'img' => 'documents',
878
+                'emb' => 'documents',
879
+            ]
880
+        );
881
+        $infos_tables = lister_tables_objets_sql();
882
+        foreach ($infos_tables as $t => $infos) {
883
+            // cas de base type=>table
884
+            // et preg_replace(',^spip_|^id_|s$,',table)=>table
885
+            if ($infos['table_objet']) { // securite, si la fonction est appelee trop tot, c'est vide
886
+                // optimisations pour table_objet
887
+                //$surnoms[$infos['type']] = $infos['table_objet'];
888
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['table_objet'];
889
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['table_objet'];
890
+                if (is_array($infos['table_objet_surnoms']) and count($infos['table_objet_surnoms'])) {
891
+                    foreach ($infos['table_objet_surnoms'] as $surnom) {
892
+                        $surnoms[$surnom] = $infos['table_objet'];
893
+                    }
894
+                }
895
+            }
896
+        }
897
+        $md5 = lister_tables_objets_sql('::md5');
898
+    }
899
+
900
+    return $surnoms;
901 901
 }
902 902
 
903 903
 /**
@@ -906,35 +906,35 @@  discard block
 block discarded – undo
906 906
  * @return array
907 907
  */
908 908
 function lister_types_surnoms() {
909
-	static $surnoms = null;
910
-	static $md5 = null;
911
-	if (
912
-		!$surnoms
913
-		or $md5 != lister_tables_objets_sql('::md5')
914
-	) {
915
-		// passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
916
-		// pour compatibilite, car il faut dorenavent utiliser
917
-		// declarer_table_objets_sql
918
-		$surnoms = pipeline('declarer_type_surnoms', ['racine-site' => 'site']);
919
-		$infos_tables = lister_tables_objets_sql();
920
-		foreach ($infos_tables as $t => $infos) {
921
-			if ($infos['type']) { // securite, si la fonction est appelee trop tot, c'est vide
922
-				// optimisations pour objet_type
923
-				//$surnoms[$infos['type']] = $infos['type'];
924
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['type'];
925
-				$surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['type'];
926
-				// surnoms declares
927
-				if (is_array($infos['type_surnoms']) and count($infos['type_surnoms'])) {
928
-					foreach ($infos['type_surnoms'] as $surnom) {
929
-						$surnoms[$surnom] = $infos['type'];
930
-					}
931
-				}
932
-			}
933
-		}
934
-		$md5 = lister_tables_objets_sql('::md5');
935
-	}
936
-
937
-	return $surnoms;
909
+    static $surnoms = null;
910
+    static $md5 = null;
911
+    if (
912
+        !$surnoms
913
+        or $md5 != lister_tables_objets_sql('::md5')
914
+    ) {
915
+        // passer dans un pipeline qui permet aux plugins de declarer leurs exceptions
916
+        // pour compatibilite, car il faut dorenavent utiliser
917
+        // declarer_table_objets_sql
918
+        $surnoms = pipeline('declarer_type_surnoms', ['racine-site' => 'site']);
919
+        $infos_tables = lister_tables_objets_sql();
920
+        foreach ($infos_tables as $t => $infos) {
921
+            if ($infos['type']) { // securite, si la fonction est appelee trop tot, c'est vide
922
+                // optimisations pour objet_type
923
+                //$surnoms[$infos['type']] = $infos['type'];
924
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['table_objet'])] = $infos['type'];
925
+                $surnoms[preg_replace(',^spip_|^id_|s$,', '', $infos['type'])] = $infos['type'];
926
+                // surnoms declares
927
+                if (is_array($infos['type_surnoms']) and count($infos['type_surnoms'])) {
928
+                    foreach ($infos['type_surnoms'] as $surnom) {
929
+                        $surnoms[$surnom] = $infos['type'];
930
+                    }
931
+                }
932
+            }
933
+        }
934
+        $md5 = lister_tables_objets_sql('::md5');
935
+    }
936
+
937
+    return $surnoms;
938 938
 }
939 939
 
940 940
 /**
@@ -948,22 +948,22 @@  discard block
 block discarded – undo
948 948
  *     Couples (nom de la table SQL => même nom, sans 'spip_' devant)
949 949
  **/
950 950
 function lister_tables_spip($serveur = '') {
951
-	static $tables = [];
952
-	if (!isset($tables[$serveur])) {
953
-		$tables[$serveur] = [];
954
-		if (!function_exists('sql_alltable')) {
955
-			include_spip('base/abstract_sql');
956
-		}
957
-		$ts = sql_alltable(null, $serveur); // toutes les tables "spip_" (ou prefixe perso)
958
-		$connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
959
-		$spip = $connexion['prefixe'] . '_';
960
-		foreach ($ts as $t) {
961
-			$t = substr($t, strlen($spip));
962
-			$tables[$serveur]["spip_$t"] = $t;
963
-		}
964
-	}
965
-
966
-	return $tables[$serveur];
951
+    static $tables = [];
952
+    if (!isset($tables[$serveur])) {
953
+        $tables[$serveur] = [];
954
+        if (!function_exists('sql_alltable')) {
955
+            include_spip('base/abstract_sql');
956
+        }
957
+        $ts = sql_alltable(null, $serveur); // toutes les tables "spip_" (ou prefixe perso)
958
+        $connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
959
+        $spip = $connexion['prefixe'] . '_';
960
+        foreach ($ts as $t) {
961
+            $t = substr($t, strlen($spip));
962
+            $tables[$serveur]["spip_$t"] = $t;
963
+        }
964
+    }
965
+
966
+    return $tables[$serveur];
967 967
 }
968 968
 
969 969
 
@@ -978,18 +978,18 @@  discard block
 block discarded – undo
978 978
  *     Couples (nom de la table SQL => même nom)
979 979
  **/
980 980
 function lister_toutes_tables($serveur) {
981
-	static $tables = [];
982
-	if (!isset($tables[$serveur])) {
983
-		$tables[$serveur] = [];
984
-		if (!function_exists('sql_alltable')) {
985
-			include_spip('base/abstract_sql');
986
-		}
987
-		$ts = sql_alltable('%', $serveur); // toutes les tables
988
-		foreach ($ts as $t) {
989
-			$tables[$serveur][$t] = $t;
990
-		}
991
-	}
992
-	return $tables[$serveur];
981
+    static $tables = [];
982
+    if (!isset($tables[$serveur])) {
983
+        $tables[$serveur] = [];
984
+        if (!function_exists('sql_alltable')) {
985
+            include_spip('base/abstract_sql');
986
+        }
987
+        $ts = sql_alltable('%', $serveur); // toutes les tables
988
+        foreach ($ts as $t) {
989
+            $tables[$serveur][$t] = $t;
990
+        }
991
+    }
992
+    return $tables[$serveur];
993 993
 }
994 994
 
995 995
 /**
@@ -1010,39 +1010,39 @@  discard block
 block discarded – undo
1010 1010
  **/
1011 1011
 function table_objet(string $type, string $serveur = ''): string {
1012 1012
 
1013
-	if ($type) {
1014
-		$type = preg_replace(',^spip_|^id_|s$,', '', $type);
1015
-	}
1016
-	if (!strlen($type)) {
1017
-		return '';
1018
-	}
1019
-
1020
-	$surnoms = lister_tables_objets_surnoms();
1021
-	if (isset($surnoms[$type])) {
1022
-		return $surnoms[$type];
1023
-	}
1024
-
1025
-	if ($serveur !== false) {
1026
-		$t = lister_tables_spip($serveur);
1027
-		$trouver_table = charger_fonction('trouver_table', 'base');
1028
-		$typetrim = rtrim($type, 's') . 's';
1029
-		if (
1030
-			(isset($t[$typetrim]) or in_array($typetrim, $t))
1031
-			and ($desc = $trouver_table(rtrim($type, 's') . 's', $serveur))
1032
-		) {
1033
-			return $desc['id_table'];
1034
-		} elseif (
1035
-			(isset($t[$type]) or in_array($type, $t))
1036
-			and ($desc = $trouver_table($type, $serveur))
1037
-		) {
1038
-			return $desc['id_table'];
1039
-		}
1040
-
1041
-		spip_log('table_objet(' . $type . ') calculee sans verification');
1042
-		#spip_log(debug_backtrace(),'db');
1043
-	}
1044
-
1045
-	return rtrim($type, 's') . 's'; # cas historique ne devant plus servir, sauf si $serveur=false
1013
+    if ($type) {
1014
+        $type = preg_replace(',^spip_|^id_|s$,', '', $type);
1015
+    }
1016
+    if (!strlen($type)) {
1017
+        return '';
1018
+    }
1019
+
1020
+    $surnoms = lister_tables_objets_surnoms();
1021
+    if (isset($surnoms[$type])) {
1022
+        return $surnoms[$type];
1023
+    }
1024
+
1025
+    if ($serveur !== false) {
1026
+        $t = lister_tables_spip($serveur);
1027
+        $trouver_table = charger_fonction('trouver_table', 'base');
1028
+        $typetrim = rtrim($type, 's') . 's';
1029
+        if (
1030
+            (isset($t[$typetrim]) or in_array($typetrim, $t))
1031
+            and ($desc = $trouver_table(rtrim($type, 's') . 's', $serveur))
1032
+        ) {
1033
+            return $desc['id_table'];
1034
+        } elseif (
1035
+            (isset($t[$type]) or in_array($type, $t))
1036
+            and ($desc = $trouver_table($type, $serveur))
1037
+        ) {
1038
+            return $desc['id_table'];
1039
+        }
1040
+
1041
+        spip_log('table_objet(' . $type . ') calculee sans verification');
1042
+        #spip_log(debug_backtrace(),'db');
1043
+    }
1044
+
1045
+    return rtrim($type, 's') . 's'; # cas historique ne devant plus servir, sauf si $serveur=false
1046 1046
 }
1047 1047
 
1048 1048
 /**
@@ -1063,33 +1063,33 @@  discard block
 block discarded – undo
1063 1063
  **/
1064 1064
 function table_objet_sql(string $type, string $serveur = ''): string {
1065 1065
 
1066
-	$nom = table_objet($type, $serveur);
1067
-	if (!strlen($nom)) {
1068
-		return '';
1069
-	}
1070
-	if (!isset($GLOBALS['table_des_tables']['articles'])) {
1071
-		// eviter de multiples inclusions
1072
-		include_spip('public/interfaces');
1073
-	}
1074
-	if (isset($GLOBALS['table_des_tables'][$nom])) {
1075
-		$nom = $GLOBALS['table_des_tables'][$nom];
1076
-		$nom = "spip_$nom";
1077
-	} else {
1078
-		$infos_tables = lister_tables_objets_sql();
1079
-		if (isset($infos_tables["spip_$nom"])) {
1080
-			$nom = "spip_$nom";
1081
-		} elseif ($serveur !== false) {
1082
-			$t = lister_tables_spip($serveur);
1083
-			if (isset($t[$nom]) or in_array($nom, $t)) {
1084
-				$trouver_table = charger_fonction('trouver_table', 'base');
1085
-				if ($desc = $trouver_table($nom, $serveur)) {
1086
-					return $desc['table_sql'];
1087
-				}
1088
-			}
1089
-		}
1090
-	}
1091
-
1092
-	return $nom;
1066
+    $nom = table_objet($type, $serveur);
1067
+    if (!strlen($nom)) {
1068
+        return '';
1069
+    }
1070
+    if (!isset($GLOBALS['table_des_tables']['articles'])) {
1071
+        // eviter de multiples inclusions
1072
+        include_spip('public/interfaces');
1073
+    }
1074
+    if (isset($GLOBALS['table_des_tables'][$nom])) {
1075
+        $nom = $GLOBALS['table_des_tables'][$nom];
1076
+        $nom = "spip_$nom";
1077
+    } else {
1078
+        $infos_tables = lister_tables_objets_sql();
1079
+        if (isset($infos_tables["spip_$nom"])) {
1080
+            $nom = "spip_$nom";
1081
+        } elseif ($serveur !== false) {
1082
+            $t = lister_tables_spip($serveur);
1083
+            if (isset($t[$nom]) or in_array($nom, $t)) {
1084
+                $trouver_table = charger_fonction('trouver_table', 'base');
1085
+                if ($desc = $trouver_table($nom, $serveur)) {
1086
+                    return $desc['table_sql'];
1087
+                }
1088
+            }
1089
+        }
1090
+    }
1091
+
1092
+    return $nom;
1093 1093
 }
1094 1094
 
1095 1095
 /**
@@ -1108,35 +1108,35 @@  discard block
 block discarded – undo
1108 1108
  *     Nom de la clé primaire
1109 1109
  **/
1110 1110
 function id_table_objet($type, $serveur = '') {
1111
-	static $trouver_table = null;
1112
-	$type = objet_type($type, $serveur);
1113
-	if (!$type) {
1114
-		return;
1115
-	}
1116
-	$t = table_objet($type);
1117
-	if (!$trouver_table) {
1118
-		$trouver_table = charger_fonction('trouver_table', 'base');
1119
-	}
1120
-
1121
-	$ts = lister_tables_spip($serveur);
1122
-	if (
1123
-		in_array($t, $ts)
1124
-		or in_array($t, lister_toutes_tables($serveur))
1125
-	) {
1126
-		$desc = $trouver_table($t, $serveur);
1127
-		if (isset($desc['key']['PRIMARY KEY'])) {
1128
-			return $desc['key']['PRIMARY KEY'];
1129
-		}
1130
-		if (!$desc or isset($desc['field']["id_$type"])) {
1131
-			return "id_$type";
1132
-		}
1133
-		// sinon renvoyer le premier champ de la table...
1134
-		$keys = array_keys($desc['field']);
1135
-
1136
-		return array_shift($keys);
1137
-	}
1138
-
1139
-	return "id_$type";
1111
+    static $trouver_table = null;
1112
+    $type = objet_type($type, $serveur);
1113
+    if (!$type) {
1114
+        return;
1115
+    }
1116
+    $t = table_objet($type);
1117
+    if (!$trouver_table) {
1118
+        $trouver_table = charger_fonction('trouver_table', 'base');
1119
+    }
1120
+
1121
+    $ts = lister_tables_spip($serveur);
1122
+    if (
1123
+        in_array($t, $ts)
1124
+        or in_array($t, lister_toutes_tables($serveur))
1125
+    ) {
1126
+        $desc = $trouver_table($t, $serveur);
1127
+        if (isset($desc['key']['PRIMARY KEY'])) {
1128
+            return $desc['key']['PRIMARY KEY'];
1129
+        }
1130
+        if (!$desc or isset($desc['field']["id_$type"])) {
1131
+            return "id_$type";
1132
+        }
1133
+        // sinon renvoyer le premier champ de la table...
1134
+        $keys = array_keys($desc['field']);
1135
+
1136
+        return array_shift($keys);
1137
+    }
1138
+
1139
+    return "id_$type";
1140 1140
 }
1141 1141
 
1142 1142
 /**
@@ -1155,60 +1155,60 @@  discard block
 block discarded – undo
1155 1155
  *     Type de l'objet
1156 1156
  **/
1157 1157
 function objet_type(string $table_objet, string $serveur = '') : ?string {
1158
-	if (!$table_objet) {
1159
-		return null;
1160
-	}
1161
-	$surnoms = lister_types_surnoms();
1162
-
1163
-	// scenario de base
1164
-	// le type est decline a partir du nom de la table en enlevant le prefixe eventuel
1165
-	// et la marque du pluriel
1166
-	// on accepte id_xx en entree aussi
1167
-	$type = preg_replace(',^spip_|^id_|s$,', '', $table_objet);
1168
-	if (isset($surnoms[$type])) {
1169
-		return $surnoms[$type];
1170
-	}
1171
-
1172
-	// securite : eliminer les caracteres non \w
1173
-	$type = preg_replace(',[^\w-],', '', $type);
1174
-
1175
-	// si le type redonne bien la table c'est bon
1176
-	// oui si table_objet ressemblait deja a un type
1177
-	if (
1178
-		$type == $table_objet
1179
-		or (table_objet($type, $serveur) == $table_objet)
1180
-		or (table_objet_sql($type, $serveur) == $table_objet)
1181
-	) {
1182
-		return $type;
1183
-	}
1184
-
1185
-	// si on ne veut pas chercher en base
1186
-	if ($serveur === false) {
1187
-		return $type;
1188
-	}
1189
-
1190
-	// sinon on passe par la cle primaire id_xx pour trouver le type
1191
-	// car le s a la fin est incertain
1192
-	// notamment en cas de pluriel derogatoire
1193
-	// id_jeu/spip_jeux id_journal/spip_journaux qui necessitent tout deux
1194
-	// une declaration jeu => jeux, journal => journaux
1195
-	// dans le pipeline declarer_tables_objets_surnoms
1196
-	$trouver_table = charger_fonction('trouver_table', 'base');
1197
-	$ts = lister_tables_spip($serveur);
1198
-	$desc = false;
1199
-	if (in_array($table_objet, $ts)) {
1200
-		$desc = $trouver_table($table_objet);
1201
-	}
1202
-	if (!$desc and in_array($table_objet = table_objet($type, $serveur), $ts)) {
1203
-		$desc = $trouver_table($table_objet, $serveur);
1204
-	}
1205
-	// si le type est declare : bingo !
1206
-	if ($desc and isset($desc['type'])) {
1207
-		return $desc['type'];
1208
-	}
1209
-
1210
-	// on a fait ce qu'on a pu
1211
-	return $type;
1158
+    if (!$table_objet) {
1159
+        return null;
1160
+    }
1161
+    $surnoms = lister_types_surnoms();
1162
+
1163
+    // scenario de base
1164
+    // le type est decline a partir du nom de la table en enlevant le prefixe eventuel
1165
+    // et la marque du pluriel
1166
+    // on accepte id_xx en entree aussi
1167
+    $type = preg_replace(',^spip_|^id_|s$,', '', $table_objet);
1168
+    if (isset($surnoms[$type])) {
1169
+        return $surnoms[$type];
1170
+    }
1171
+
1172
+    // securite : eliminer les caracteres non \w
1173
+    $type = preg_replace(',[^\w-],', '', $type);
1174
+
1175
+    // si le type redonne bien la table c'est bon
1176
+    // oui si table_objet ressemblait deja a un type
1177
+    if (
1178
+        $type == $table_objet
1179
+        or (table_objet($type, $serveur) == $table_objet)
1180
+        or (table_objet_sql($type, $serveur) == $table_objet)
1181
+    ) {
1182
+        return $type;
1183
+    }
1184
+
1185
+    // si on ne veut pas chercher en base
1186
+    if ($serveur === false) {
1187
+        return $type;
1188
+    }
1189
+
1190
+    // sinon on passe par la cle primaire id_xx pour trouver le type
1191
+    // car le s a la fin est incertain
1192
+    // notamment en cas de pluriel derogatoire
1193
+    // id_jeu/spip_jeux id_journal/spip_journaux qui necessitent tout deux
1194
+    // une declaration jeu => jeux, journal => journaux
1195
+    // dans le pipeline declarer_tables_objets_surnoms
1196
+    $trouver_table = charger_fonction('trouver_table', 'base');
1197
+    $ts = lister_tables_spip($serveur);
1198
+    $desc = false;
1199
+    if (in_array($table_objet, $ts)) {
1200
+        $desc = $trouver_table($table_objet);
1201
+    }
1202
+    if (!$desc and in_array($table_objet = table_objet($type, $serveur), $ts)) {
1203
+        $desc = $trouver_table($table_objet, $serveur);
1204
+    }
1205
+    // si le type est declare : bingo !
1206
+    if ($desc and isset($desc['type'])) {
1207
+        return $desc['type'];
1208
+    }
1209
+
1210
+    // on a fait ce qu'on a pu
1211
+    return $type;
1212 1212
 }
1213 1213
 
1214 1214
 /**
@@ -1224,62 +1224,62 @@  discard block
 block discarded – undo
1224 1224
  * @return bool
1225 1225
  */
1226 1226
 function objet_test_si_publie($objet, $id_objet, $serveur = '') {
1227
-	// voir si une fonction est definie pour faire le boulot
1228
-	// elle a la priorite dans ce cas
1229
-	if ($f = charger_fonction($objet . '_test_si_publie', 'base', true)) {
1230
-		return $f($objet, $id_objet, $serveur);
1231
-	}
1232
-
1233
-	// sinon on se fie a la declaration de l'objet si presente
1234
-	$id_table = $table_objet = table_objet($objet);
1235
-	$id_table_objet = id_table_objet($objet, $serveur);
1236
-	$trouver_table = charger_fonction('trouver_table', 'base');
1237
-	if (
1238
-		$desc = $trouver_table($table_objet, $serveur)
1239
-		and isset($desc['statut'])
1240
-		and $desc['statut']
1241
-	) {
1242
-		$boucle = new Boucle();
1243
-		$boucle->show = $desc;
1244
-		$boucle->nom = 'objet_test_si_publie';
1245
-		$boucle->id_boucle = $id_table;
1246
-		$boucle->id_table = $id_table;
1247
-		$boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
1248
-		$boucle->sql_serveur = $serveur;
1249
-		$boucle->select[] = $id_table_objet;
1250
-		$boucle->from[$table_objet] = table_objet_sql($objet, $serveur);
1251
-		$boucle->where[] = $id_table . '.' . $id_table_objet . '=' . intval($id_objet);
1252
-
1253
-		$boucle->descr['nom'] = 'objet_test_si_publie'; // eviter notice php
1254
-		$boucle->descr['sourcefile'] = 'internal';
1255
-		$boucle->descr['gram'] = 'html';
1256
-
1257
-		include_spip('public/compiler');
1258
-		include_spip('public/composer');
1259
-		instituer_boucle($boucle, false, true);
1260
-		$res = calculer_select(
1261
-			$boucle->select,
1262
-			$boucle->from,
1263
-			$boucle->from_type,
1264
-			$boucle->where,
1265
-			$boucle->join,
1266
-			$boucle->group,
1267
-			$boucle->order,
1268
-			$boucle->limit,
1269
-			$boucle->having,
1270
-			$table_objet,
1271
-			$id_table,
1272
-			$serveur
1273
-		);
1274
-		if (sql_fetch($res)) {
1275
-			return true;
1276
-		}
1277
-
1278
-		return false;
1279
-	}
1280
-
1281
-	// si pas d'info statut ni de fonction : l'objet est publie
1282
-	return true;
1227
+    // voir si une fonction est definie pour faire le boulot
1228
+    // elle a la priorite dans ce cas
1229
+    if ($f = charger_fonction($objet . '_test_si_publie', 'base', true)) {
1230
+        return $f($objet, $id_objet, $serveur);
1231
+    }
1232
+
1233
+    // sinon on se fie a la declaration de l'objet si presente
1234
+    $id_table = $table_objet = table_objet($objet);
1235
+    $id_table_objet = id_table_objet($objet, $serveur);
1236
+    $trouver_table = charger_fonction('trouver_table', 'base');
1237
+    if (
1238
+        $desc = $trouver_table($table_objet, $serveur)
1239
+        and isset($desc['statut'])
1240
+        and $desc['statut']
1241
+    ) {
1242
+        $boucle = new Boucle();
1243
+        $boucle->show = $desc;
1244
+        $boucle->nom = 'objet_test_si_publie';
1245
+        $boucle->id_boucle = $id_table;
1246
+        $boucle->id_table = $id_table;
1247
+        $boucle->primary = $desc['key']['PRIMARY KEY'] ?? '';
1248
+        $boucle->sql_serveur = $serveur;
1249
+        $boucle->select[] = $id_table_objet;
1250
+        $boucle->from[$table_objet] = table_objet_sql($objet, $serveur);
1251
+        $boucle->where[] = $id_table . '.' . $id_table_objet . '=' . intval($id_objet);
1252
+
1253
+        $boucle->descr['nom'] = 'objet_test_si_publie'; // eviter notice php
1254
+        $boucle->descr['sourcefile'] = 'internal';
1255
+        $boucle->descr['gram'] = 'html';
1256
+
1257
+        include_spip('public/compiler');
1258
+        include_spip('public/composer');
1259
+        instituer_boucle($boucle, false, true);
1260
+        $res = calculer_select(
1261
+            $boucle->select,
1262
+            $boucle->from,
1263
+            $boucle->from_type,
1264
+            $boucle->where,
1265
+            $boucle->join,
1266
+            $boucle->group,
1267
+            $boucle->order,
1268
+            $boucle->limit,
1269
+            $boucle->having,
1270
+            $table_objet,
1271
+            $id_table,
1272
+            $serveur
1273
+        );
1274
+        if (sql_fetch($res)) {
1275
+            return true;
1276
+        }
1277
+
1278
+        return false;
1279
+    }
1280
+
1281
+    // si pas d'info statut ni de fonction : l'objet est publie
1282
+    return true;
1283 1283
 }
1284 1284
 
1285 1285
 
@@ -1314,124 +1314,124 @@  discard block
 block discarded – undo
1314 1314
  *     Retourne un tableau décrivant les parents trouvés
1315 1315
  */
1316 1316
 function objet_lister_parents($objet, $id_objet, $parent_direct_seulement = false) {
1317
-	$parents = [];
1318
-
1319
-	// Si on trouve une ou des méthodes de parent
1320
-	if ($parent_methodes = objet_type_decrire_infos_parents($objet)) {
1321
-		// On identifie les informations sur l'objet source dont on cherche le parent.
1322
-		include_spip('base/abstract_sql');
1323
-		$table_objet = table_objet_sql($objet);
1324
-		$cle_objet = id_table_objet($objet);
1325
-		$id_objet = intval($id_objet);
1326
-
1327
-		// On teste chacun méthode dans l'ordre, et dès qu'on a trouvé un parent on s'arrête
1328
-		foreach ($parent_methodes as $parent_methode) {
1329
-			// Champ identifiant le parent (id et éventuellement le type)
1330
-			// -- cette identification ne dépend pas du fait que le parent soit stocké dans une table de différente
1331
-			//    de celle de l'objet source
1332
-			$select = [];
1333
-			if (isset($parent_methode['champ'])) {
1334
-				$select[] = $parent_methode['champ'];
1335
-			}
1336
-			if (isset($parent_methode['champ_type'])) {
1337
-				$select[] = $parent_methode['champ_type'];
1338
-			}
1339
-
1340
-			// Détermination de la table du parent et des conditions sur l'objet source et le parent.
1341
-			$condition_objet_invalide = false;
1342
-			$where = [];
1343
-			if (!isset($parent_methode['table'])) {
1344
-				// Le parent est stocké dans la même table que l'objet source :
1345
-				// -- toutes les conditions s'appliquent à la table source.
1346
-				$table = $table_objet;
1347
-				$where = ["$cle_objet = $id_objet"];
1348
-				// -- Condition supplémentaire sur la détection du parent
1349
-				if (isset($parent_methode['condition'])) {
1350
-					$where[] = $parent_methode['condition'];
1351
-				}
1352
-			} elseif (!$parent_direct_seulement) {
1353
-				// Le parent est stocké dans une table différente de l'objet source.
1354
-				// -- on vérifie d'emblée si il y a une condition sur l'objet source et si celle-ci est vérifiée
1355
-				//    Si non, on peut arrêter le traitement.
1356
-				if (isset($parent_methode['condition'])) {
1357
-					$where = [
1358
-						"$cle_objet = $id_objet",
1359
-						$parent_methode['condition']
1360
-					];
1361
-					if (!sql_countsel($table_objet, $where)) {
1362
-						$condition_objet_invalide = true;
1363
-					}
1364
-				}
1365
-
1366
-				// Si pas de condition sur l'objet source ou que la condition est vérifiée, on peut construire
1367
-				// la requête sur la table qui accueille le parent.
1368
-				if (!$condition_objet_invalide) {
1369
-					$table = $parent_methode['table'];
1370
-					// On construit les conditions en fonction de l'identification de l'objet source
1371
-					$where = [];
1372
-					// -- si le champ_source de l'id n'est pas précisé c'est qu'il est déjà connu et donc que c'est
1373
-					//    le même que celui de l'objet source.
1374
-					$where[] = isset($parent_methode['source_champ'])
1375
-						? "{$parent_methode['source_champ']} = $id_objet"
1376
-						: "${cle_objet} = $id_objet";
1377
-					if (isset($parent_methode['source_champ_type'])) {
1378
-						$where[] = "{$parent_methode['source_champ_type']} = " . sql_quote($objet);
1379
-					}
1380
-					// -- Condition supplémentaire sur la détection du parent
1381
-					if (isset($parent_methode['table_condition'])) {
1382
-						$where[] = $parent_methode['table_condition'];
1383
-					}
1384
-				}
1385
-			}
1386
-
1387
-			// On lance la requête de récupération du parent
1388
-			$is_table_lien = (strpos($table, '_liens') !== false and substr($table, -6) === '_liens');
1389
-			if (
1390
-				!$condition_objet_invalide
1391
-				and $where
1392
-				and ($lignes = sql_allfetsel($is_table_lien ? '*' : $select, $table, $where))
1393
-			) {
1394
-				foreach ($lignes as $ligne) {
1395
-					// Si le type est fixe
1396
-					if (isset($parent_methode['type'])) {
1397
-						$parent = [
1398
-							'objet' 	=> $parent_methode['type'],
1399
-							'id_objet'	=> intval($ligne[$parent_methode['champ']]),
1400
-							'champ' 	=> $parent_methode['champ'],
1401
-							'table'    => $table,
1402
-						];
1403
-					}
1404
-					elseif (isset($parent_methode['champ_type'])) {
1405
-						$parent = [
1406
-							'objet' 	 => $ligne[$parent_methode['champ_type']],
1407
-							'id_objet' 	 => intval($ligne[$parent_methode['champ']]),
1408
-							'champ' 	 => $parent_methode['champ'],
1409
-							'champ_type' => $parent_methode['champ_type'],
1410
-							'table'    => $table,
1411
-						];
1412
-					}
1413
-					if ($is_table_lien) {
1414
-						$parent['lien'] = $ligne;
1415
-					}
1416
-					$parents[] = $parent;
1417
-				}
1418
-			}
1419
-		}
1420
-	}
1421
-
1422
-	// On passe par un pipeline avant de retourner
1423
-	$parents = pipeline(
1424
-		'objet_lister_parents',
1425
-		[
1426
-			'args' => [
1427
-				'objet' => $objet,
1428
-				'id_objet' => $id_objet,
1429
-			],
1430
-			'data' => $parents,
1431
-		]
1432
-	);
1433
-
1434
-	return $parents;
1317
+    $parents = [];
1318
+
1319
+    // Si on trouve une ou des méthodes de parent
1320
+    if ($parent_methodes = objet_type_decrire_infos_parents($objet)) {
1321
+        // On identifie les informations sur l'objet source dont on cherche le parent.
1322
+        include_spip('base/abstract_sql');
1323
+        $table_objet = table_objet_sql($objet);
1324
+        $cle_objet = id_table_objet($objet);
1325
+        $id_objet = intval($id_objet);
1326
+
1327
+        // On teste chacun méthode dans l'ordre, et dès qu'on a trouvé un parent on s'arrête
1328
+        foreach ($parent_methodes as $parent_methode) {
1329
+            // Champ identifiant le parent (id et éventuellement le type)
1330
+            // -- cette identification ne dépend pas du fait que le parent soit stocké dans une table de différente
1331
+            //    de celle de l'objet source
1332
+            $select = [];
1333
+            if (isset($parent_methode['champ'])) {
1334
+                $select[] = $parent_methode['champ'];
1335
+            }
1336
+            if (isset($parent_methode['champ_type'])) {
1337
+                $select[] = $parent_methode['champ_type'];
1338
+            }
1339
+
1340
+            // Détermination de la table du parent et des conditions sur l'objet source et le parent.
1341
+            $condition_objet_invalide = false;
1342
+            $where = [];
1343
+            if (!isset($parent_methode['table'])) {
1344
+                // Le parent est stocké dans la même table que l'objet source :
1345
+                // -- toutes les conditions s'appliquent à la table source.
1346
+                $table = $table_objet;
1347
+                $where = ["$cle_objet = $id_objet"];
1348
+                // -- Condition supplémentaire sur la détection du parent
1349
+                if (isset($parent_methode['condition'])) {
1350
+                    $where[] = $parent_methode['condition'];
1351
+                }
1352
+            } elseif (!$parent_direct_seulement) {
1353
+                // Le parent est stocké dans une table différente de l'objet source.
1354
+                // -- on vérifie d'emblée si il y a une condition sur l'objet source et si celle-ci est vérifiée
1355
+                //    Si non, on peut arrêter le traitement.
1356
+                if (isset($parent_methode['condition'])) {
1357
+                    $where = [
1358
+                        "$cle_objet = $id_objet",
1359
+                        $parent_methode['condition']
1360
+                    ];
1361
+                    if (!sql_countsel($table_objet, $where)) {
1362
+                        $condition_objet_invalide = true;
1363
+                    }
1364
+                }
1365
+
1366
+                // Si pas de condition sur l'objet source ou que la condition est vérifiée, on peut construire
1367
+                // la requête sur la table qui accueille le parent.
1368
+                if (!$condition_objet_invalide) {
1369
+                    $table = $parent_methode['table'];
1370
+                    // On construit les conditions en fonction de l'identification de l'objet source
1371
+                    $where = [];
1372
+                    // -- si le champ_source de l'id n'est pas précisé c'est qu'il est déjà connu et donc que c'est
1373
+                    //    le même que celui de l'objet source.
1374
+                    $where[] = isset($parent_methode['source_champ'])
1375
+                        ? "{$parent_methode['source_champ']} = $id_objet"
1376
+                        : "${cle_objet} = $id_objet";
1377
+                    if (isset($parent_methode['source_champ_type'])) {
1378
+                        $where[] = "{$parent_methode['source_champ_type']} = " . sql_quote($objet);
1379
+                    }
1380
+                    // -- Condition supplémentaire sur la détection du parent
1381
+                    if (isset($parent_methode['table_condition'])) {
1382
+                        $where[] = $parent_methode['table_condition'];
1383
+                    }
1384
+                }
1385
+            }
1386
+
1387
+            // On lance la requête de récupération du parent
1388
+            $is_table_lien = (strpos($table, '_liens') !== false and substr($table, -6) === '_liens');
1389
+            if (
1390
+                !$condition_objet_invalide
1391
+                and $where
1392
+                and ($lignes = sql_allfetsel($is_table_lien ? '*' : $select, $table, $where))
1393
+            ) {
1394
+                foreach ($lignes as $ligne) {
1395
+                    // Si le type est fixe
1396
+                    if (isset($parent_methode['type'])) {
1397
+                        $parent = [
1398
+                            'objet' 	=> $parent_methode['type'],
1399
+                            'id_objet'	=> intval($ligne[$parent_methode['champ']]),
1400
+                            'champ' 	=> $parent_methode['champ'],
1401
+                            'table'    => $table,
1402
+                        ];
1403
+                    }
1404
+                    elseif (isset($parent_methode['champ_type'])) {
1405
+                        $parent = [
1406
+                            'objet' 	 => $ligne[$parent_methode['champ_type']],
1407
+                            'id_objet' 	 => intval($ligne[$parent_methode['champ']]),
1408
+                            'champ' 	 => $parent_methode['champ'],
1409
+                            'champ_type' => $parent_methode['champ_type'],
1410
+                            'table'    => $table,
1411
+                        ];
1412
+                    }
1413
+                    if ($is_table_lien) {
1414
+                        $parent['lien'] = $ligne;
1415
+                    }
1416
+                    $parents[] = $parent;
1417
+                }
1418
+            }
1419
+        }
1420
+    }
1421
+
1422
+    // On passe par un pipeline avant de retourner
1423
+    $parents = pipeline(
1424
+        'objet_lister_parents',
1425
+        [
1426
+            'args' => [
1427
+                'objet' => $objet,
1428
+                'id_objet' => $id_objet,
1429
+            ],
1430
+            'data' => $parents,
1431
+        ]
1432
+    );
1433
+
1434
+    return $parents;
1435 1435
 }
1436 1436
 
1437 1437
 /**
@@ -1443,17 +1443,17 @@  discard block
 block discarded – undo
1443 1443
  * @return array
1444 1444
  */
1445 1445
 function objet_lister_parents_par_type($objet, $id_objet) {
1446
-	$parents = objet_lister_parents($objet, $id_objet);
1446
+    $parents = objet_lister_parents($objet, $id_objet);
1447 1447
 
1448
-	$parents_par_type = [];
1449
-	foreach ($parents as $parent) {
1450
-		if (!isset($parents_par_type[$parent['objet']])) {
1451
-			$parents_par_type[$parent['objet']] = [];
1452
-		}
1453
-		$parents_par_type[$parent['objet']][] = $parent['id_objet'];
1454
-	}
1448
+    $parents_par_type = [];
1449
+    foreach ($parents as $parent) {
1450
+        if (!isset($parents_par_type[$parent['objet']])) {
1451
+            $parents_par_type[$parent['objet']] = [];
1452
+        }
1453
+        $parents_par_type[$parent['objet']][] = $parent['id_objet'];
1454
+    }
1455 1455
 
1456
-	return $parents_par_type;
1456
+    return $parents_par_type;
1457 1457
 }
1458 1458
 
1459 1459
 
@@ -1486,85 +1486,85 @@  discard block
 block discarded – undo
1486 1486
  *     Retourne un tableau de tableaux, avec comme clés les types des objets, et dans chacun un tableau des identifiants trouvés
1487 1487
  */
1488 1488
 function objet_lister_enfants($objet, $id_objet) {
1489
-	$enfants = [];
1490
-
1491
-	// Si on trouve des types d'enfants et leurs méthodes
1492
-	if ($enfants_methodes = objet_type_decrire_infos_enfants($objet)) {
1493
-		include_spip('base/abstract_sql');
1494
-		$id_objet = intval($id_objet);
1495
-
1496
-		// On parcourt tous les types d'enfants trouvés
1497
-		foreach ($enfants_methodes as $objet_enfant => $_methode_parent) {
1498
-			// On construit les conditions d'identification du parent
1499
-			$where = [];
1500
-			// -- L'identifiant du parent
1501
-			if (isset($_methode_parent['champ'])) {
1502
-				$where[] = $_methode_parent['champ'] . ' = ' . $id_objet;
1503
-			}
1504
-			// -- Si le parent est variable
1505
-			if (isset($_methode_parent['champ_type'])) {
1506
-				$where[] = $_methode_parent['champ_type'] . ' = ' . sql_quote($objet);
1507
-			}
1508
-
1509
-			// On détermine la table, le champ id des enfants et on complète éventuellement les conditions
1510
-			if (!isset($_methode_parent['table'])) {
1511
-				// Les enfants sont stockés dans la même table que l'objet parent :
1512
-				$table_enfant = table_objet_sql($objet_enfant);
1513
-				$cle_objet_enfant = id_table_objet($objet_enfant);
1514
-
1515
-				// S'il y a une condition supplémentaire
1516
-				if (isset($_methode_parent['condition'])) {
1517
-					$where[] = $_methode_parent['condition'];
1518
-				}
1519
-			} else {
1520
-				// Les enfants sont stockés dans une table différente de l'objet parent.
1521
-				$table_enfant = $_methode_parent['table'];
1522
-				$cle_objet_enfant = $_methode_parent['source_champ'] ?? id_table_objet($objet_enfant);
1523
-
1524
-				// S'il y a une condition supplémentaire
1525
-				if (isset($_methode_parent['table_condition'])) {
1526
-					$where[] = $_methode_parent['table_condition'];
1527
-				}
1528
-			}
1529
-
1530
-			// On lance la requête
1531
-			$is_table_lien = (strpos($table_enfant, '_liens') !== false and substr($table_enfant, -6) === '_liens');
1532
-			if ($rows = sql_allfetsel($is_table_lien ? '*' : $cle_objet_enfant, $table_enfant, $where)) {
1533
-				$enfant = [
1534
-					'objet' => $objet_enfant,
1535
-					'id_objet' => 0,
1536
-					'table' => $table_enfant
1537
-				];
1538
-				if (isset($_methode_parent['champ'])) {
1539
-					$enfant['champ'] = $_methode_parent['champ'];
1540
-				}
1541
-				if (isset($_methode_parent['champ_type'])) {
1542
-					$enfant['champ_type'] = $_methode_parent['champ_type'];
1543
-				}
1544
-				foreach ($rows as $row) {
1545
-					$enfant['id_objet'] = intval($row[$cle_objet_enfant]);
1546
-					if ($is_table_lien) {
1547
-						$enfant['lien'] = $row;
1548
-					}
1549
-					$enfants[] = $enfant;
1550
-				}
1551
-			}
1552
-		}
1553
-	}
1554
-
1555
-	// On passe par un pipeline avant de retourner
1556
-	$enfants = pipeline(
1557
-		'objet_lister_enfants',
1558
-		[
1559
-			'args' => [
1560
-				'objet' => $objet,
1561
-				'id_objet' => $id_objet,
1562
-			],
1563
-			'data' => $enfants,
1564
-		]
1565
-	);
1566
-
1567
-	return $enfants;
1489
+    $enfants = [];
1490
+
1491
+    // Si on trouve des types d'enfants et leurs méthodes
1492
+    if ($enfants_methodes = objet_type_decrire_infos_enfants($objet)) {
1493
+        include_spip('base/abstract_sql');
1494
+        $id_objet = intval($id_objet);
1495
+
1496
+        // On parcourt tous les types d'enfants trouvés
1497
+        foreach ($enfants_methodes as $objet_enfant => $_methode_parent) {
1498
+            // On construit les conditions d'identification du parent
1499
+            $where = [];
1500
+            // -- L'identifiant du parent
1501
+            if (isset($_methode_parent['champ'])) {
1502
+                $where[] = $_methode_parent['champ'] . ' = ' . $id_objet;
1503
+            }
1504
+            // -- Si le parent est variable
1505
+            if (isset($_methode_parent['champ_type'])) {
1506
+                $where[] = $_methode_parent['champ_type'] . ' = ' . sql_quote($objet);
1507
+            }
1508
+
1509
+            // On détermine la table, le champ id des enfants et on complète éventuellement les conditions
1510
+            if (!isset($_methode_parent['table'])) {
1511
+                // Les enfants sont stockés dans la même table que l'objet parent :
1512
+                $table_enfant = table_objet_sql($objet_enfant);
1513
+                $cle_objet_enfant = id_table_objet($objet_enfant);
1514
+
1515
+                // S'il y a une condition supplémentaire
1516
+                if (isset($_methode_parent['condition'])) {
1517
+                    $where[] = $_methode_parent['condition'];
1518
+                }
1519
+            } else {
1520
+                // Les enfants sont stockés dans une table différente de l'objet parent.
1521
+                $table_enfant = $_methode_parent['table'];
1522
+                $cle_objet_enfant = $_methode_parent['source_champ'] ?? id_table_objet($objet_enfant);
1523
+
1524
+                // S'il y a une condition supplémentaire
1525
+                if (isset($_methode_parent['table_condition'])) {
1526
+                    $where[] = $_methode_parent['table_condition'];
1527
+                }
1528
+            }
1529
+
1530
+            // On lance la requête
1531
+            $is_table_lien = (strpos($table_enfant, '_liens') !== false and substr($table_enfant, -6) === '_liens');
1532
+            if ($rows = sql_allfetsel($is_table_lien ? '*' : $cle_objet_enfant, $table_enfant, $where)) {
1533
+                $enfant = [
1534
+                    'objet' => $objet_enfant,
1535
+                    'id_objet' => 0,
1536
+                    'table' => $table_enfant
1537
+                ];
1538
+                if (isset($_methode_parent['champ'])) {
1539
+                    $enfant['champ'] = $_methode_parent['champ'];
1540
+                }
1541
+                if (isset($_methode_parent['champ_type'])) {
1542
+                    $enfant['champ_type'] = $_methode_parent['champ_type'];
1543
+                }
1544
+                foreach ($rows as $row) {
1545
+                    $enfant['id_objet'] = intval($row[$cle_objet_enfant]);
1546
+                    if ($is_table_lien) {
1547
+                        $enfant['lien'] = $row;
1548
+                    }
1549
+                    $enfants[] = $enfant;
1550
+                }
1551
+            }
1552
+        }
1553
+    }
1554
+
1555
+    // On passe par un pipeline avant de retourner
1556
+    $enfants = pipeline(
1557
+        'objet_lister_enfants',
1558
+        [
1559
+            'args' => [
1560
+                'objet' => $objet,
1561
+                'id_objet' => $id_objet,
1562
+            ],
1563
+            'data' => $enfants,
1564
+        ]
1565
+    );
1566
+
1567
+    return $enfants;
1568 1568
 }
1569 1569
 
1570 1570
 /**
@@ -1576,17 +1576,17 @@  discard block
 block discarded – undo
1576 1576
  * @return array
1577 1577
  */
1578 1578
 function objet_lister_enfants_par_type($objet, $id_objet) {
1579
-	$enfants = objet_lister_enfants($objet, $id_objet);
1579
+    $enfants = objet_lister_enfants($objet, $id_objet);
1580 1580
 
1581
-	$enfants_par_type = [];
1582
-	foreach ($enfants as $enfant) {
1583
-		if (!isset($enfants_par_type[$enfant['objet']])) {
1584
-			$enfants_par_type[$enfant['objet']] = [];
1585
-		}
1586
-		$enfants_par_type[$enfant['objet']][] = $enfant['id_objet'];
1587
-	}
1581
+    $enfants_par_type = [];
1582
+    foreach ($enfants as $enfant) {
1583
+        if (!isset($enfants_par_type[$enfant['objet']])) {
1584
+            $enfants_par_type[$enfant['objet']] = [];
1585
+        }
1586
+        $enfants_par_type[$enfant['objet']][] = $enfant['id_objet'];
1587
+    }
1588 1588
 
1589
-	return $enfants_par_type;
1589
+    return $enfants_par_type;
1590 1590
 }
1591 1591
 
1592 1592
 /**
@@ -1598,35 +1598,35 @@  discard block
 block discarded – undo
1598 1598
  *     Retourne un tableau de tableau contenant les informations de type et de champ pour trouver le parent ou false sinon
1599 1599
  */
1600 1600
 function objet_type_decrire_infos_parents($objet) {
1601
-	static $parents = [];
1602
-
1603
-	// Si on ne l'a pas encore cherché pour cet objet
1604
-	if (!isset($parents[$objet])) {
1605
-		$parents[$objet] = false;
1606
-		$table = table_objet_sql($objet);
1607
-
1608
-		// Si on trouve bien la description de cet objet
1609
-		if ($infos = lister_tables_objets_sql($table)) {
1610
-			if (isset($infos['parent']) and is_array($infos['parent'])) {
1611
-				// S'il y a une description explicite de parent, c'est prioritaire
1612
-				// -- on traite les cas où il y a une ou plusieurs description mais on renvoie toujours un tableau
1613
-				//    de description
1614
-				if (!isset($infos['parent'][0])) {
1615
-					$parents[$objet] = [$infos['parent']];
1616
-				} else {
1617
-					$parents[$objet] = $infos['parent'];
1618
-				}
1619
-			} elseif (isset($infos['field']['id_rubrique'])) {
1620
-				// Sinon on cherche des cas courants connus magiquement, à commencer par id_rubrique
1621
-				$parents[$objet] = [['type' => 'rubrique', 'champ' => 'id_rubrique']];
1622
-			} elseif (isset($infos['field']['id_parent'])) {
1623
-				// Sinon on cherche un champ id_parent, ce qui signifie que l'objet est parent de lui-même
1624
-				$parents[$objet] = [['type' => $objet, 'champ' => 'id_parent']];
1625
-			}
1626
-		}
1627
-	}
1628
-
1629
-	return $parents[$objet];
1601
+    static $parents = [];
1602
+
1603
+    // Si on ne l'a pas encore cherché pour cet objet
1604
+    if (!isset($parents[$objet])) {
1605
+        $parents[$objet] = false;
1606
+        $table = table_objet_sql($objet);
1607
+
1608
+        // Si on trouve bien la description de cet objet
1609
+        if ($infos = lister_tables_objets_sql($table)) {
1610
+            if (isset($infos['parent']) and is_array($infos['parent'])) {
1611
+                // S'il y a une description explicite de parent, c'est prioritaire
1612
+                // -- on traite les cas où il y a une ou plusieurs description mais on renvoie toujours un tableau
1613
+                //    de description
1614
+                if (!isset($infos['parent'][0])) {
1615
+                    $parents[$objet] = [$infos['parent']];
1616
+                } else {
1617
+                    $parents[$objet] = $infos['parent'];
1618
+                }
1619
+            } elseif (isset($infos['field']['id_rubrique'])) {
1620
+                // Sinon on cherche des cas courants connus magiquement, à commencer par id_rubrique
1621
+                $parents[$objet] = [['type' => 'rubrique', 'champ' => 'id_rubrique']];
1622
+            } elseif (isset($infos['field']['id_parent'])) {
1623
+                // Sinon on cherche un champ id_parent, ce qui signifie que l'objet est parent de lui-même
1624
+                $parents[$objet] = [['type' => $objet, 'champ' => 'id_parent']];
1625
+            }
1626
+        }
1627
+    }
1628
+
1629
+    return $parents[$objet];
1630 1630
 }
1631 1631
 
1632 1632
 /**
@@ -1638,36 +1638,36 @@  discard block
 block discarded – undo
1638 1638
  *     Retourne un tableau de tableaux contenant chacun les informations d'un type d'enfant
1639 1639
  */
1640 1640
 function objet_type_decrire_infos_enfants($objet) {
1641
-	static $enfants = [];
1642
-
1643
-	// Si on a déjà fait la recherche pour ce type d'objet
1644
-	if (!isset($enfants[$objet])) {
1645
-		$enfants[$objet] = [];
1646
-		$tables = lister_tables_objets_sql();
1647
-
1648
-		// On parcourt toutes les tables d'objet, et on cherche si chacune peut être enfant
1649
-		foreach ($tables as $table => $infos) {
1650
-			$objet_enfant = objet_type($table);
1651
-
1652
-			// On ne va pas refaire les tests des différents cas, on réutilise
1653
-			if ($parent_methodes = objet_type_decrire_infos_parents($objet_enfant)) {
1654
-				// On parcourt les différents cas possible, si certains peuvent concerner l'objet demandé
1655
-				foreach ($parent_methodes as $parent_methode) {
1656
-					// Si la méthode qu'on teste n'exclut pas le parent demandé
1657
-					if (!isset($parent_methode['exclus']) or !in_array($objet, $parent_methode['exclus'])) {
1658
-						// Si le type du parent est fixe et directement l'objet demandé
1659
-						if (isset($parent_methode['type']) and isset($parent_methode['champ']) and $parent_methode['type'] == $objet) {
1660
-							$enfants[$objet][$objet_enfant] = $parent_methode;
1661
-						}
1662
-						// Si le type est variable, alors l'objet demandé peut forcément être parent
1663
-						elseif (isset($parent_methode['champ_type']) and isset($parent_methode['champ'])) {
1664
-							$enfants[$objet][$objet_enfant] = $parent_methode;
1665
-						}
1666
-					}
1667
-				}
1668
-			}
1669
-		}
1670
-	}
1671
-
1672
-	return $enfants[$objet];
1641
+    static $enfants = [];
1642
+
1643
+    // Si on a déjà fait la recherche pour ce type d'objet
1644
+    if (!isset($enfants[$objet])) {
1645
+        $enfants[$objet] = [];
1646
+        $tables = lister_tables_objets_sql();
1647
+
1648
+        // On parcourt toutes les tables d'objet, et on cherche si chacune peut être enfant
1649
+        foreach ($tables as $table => $infos) {
1650
+            $objet_enfant = objet_type($table);
1651
+
1652
+            // On ne va pas refaire les tests des différents cas, on réutilise
1653
+            if ($parent_methodes = objet_type_decrire_infos_parents($objet_enfant)) {
1654
+                // On parcourt les différents cas possible, si certains peuvent concerner l'objet demandé
1655
+                foreach ($parent_methodes as $parent_methode) {
1656
+                    // Si la méthode qu'on teste n'exclut pas le parent demandé
1657
+                    if (!isset($parent_methode['exclus']) or !in_array($objet, $parent_methode['exclus'])) {
1658
+                        // Si le type du parent est fixe et directement l'objet demandé
1659
+                        if (isset($parent_methode['type']) and isset($parent_methode['champ']) and $parent_methode['type'] == $objet) {
1660
+                            $enfants[$objet][$objet_enfant] = $parent_methode;
1661
+                        }
1662
+                        // Si le type est variable, alors l'objet demandé peut forcément être parent
1663
+                        elseif (isset($parent_methode['champ_type']) and isset($parent_methode['champ'])) {
1664
+                            $enfants[$objet][$objet_enfant] = $parent_methode;
1665
+                        }
1666
+                    }
1667
+                }
1668
+            }
1669
+        }
1670
+    }
1671
+
1672
+    return $enfants[$objet];
1673 1673
 }
Please login to merge, or discard this patch.
ecrire/base/dump.php 2 patches
Indentation   +539 added lines, -539 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
 define('_VERSION_ARCHIVE', '1.3');
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
  * @return string
39 39
  **/
40 40
 function base_dump_meta_name($rub) {
41
-	return $meta = "status_dump_{$rub}_" . abs($GLOBALS['visiteur_session']['id_auteur']);
41
+    return $meta = "status_dump_{$rub}_" . abs($GLOBALS['visiteur_session']['id_auteur']);
42 42
 }
43 43
 
44 44
 /**
@@ -53,15 +53,15 @@  discard block
 block discarded – undo
53 53
  * @return string
54 54
  **/
55 55
 function base_dump_dir($meta) {
56
-	include_spip('inc/documents');
57
-	// determine upload va aussi initialiser l'index "restreint"
58
-	$maindir = determine_upload();
59
-	if (!$GLOBALS['visiteur_session']['restreint']) {
60
-		$maindir = _DIR_DUMP;
61
-	}
62
-	$dir = sous_repertoire($maindir, $meta);
63
-
64
-	return $dir;
56
+    include_spip('inc/documents');
57
+    // determine upload va aussi initialiser l'index "restreint"
58
+    $maindir = determine_upload();
59
+    if (!$GLOBALS['visiteur_session']['restreint']) {
60
+        $maindir = _DIR_DUMP;
61
+    }
62
+    $dir = sous_repertoire($maindir, $meta);
63
+
64
+    return $dir;
65 65
 }
66 66
 
67 67
 /**
@@ -75,28 +75,28 @@  discard block
 block discarded – undo
75 75
  * @return array
76 76
  */
77 77
 function base_lister_toutes_tables(
78
-	$serveur = '',
79
-	$tables = [],
80
-	$exclude = [],
81
-	$affiche_vrai_prefixe = false
78
+    $serveur = '',
79
+    $tables = [],
80
+    $exclude = [],
81
+    $affiche_vrai_prefixe = false
82 82
 ) {
83
-	spip_connect($serveur);
84
-	$connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
85
-	$prefixe = $connexion['prefixe'];
86
-
87
-	$p = '/^' . $prefixe . '/';
88
-	$res = $tables;
89
-	foreach (sql_alltable(null, $serveur) as $t) {
90
-		if (preg_match($p, $t)) {
91
-			$t1 = preg_replace($p, 'spip', $t);
92
-			if (!in_array($t1, $tables) and !in_array($t1, $exclude)) {
93
-				$res[] = ($affiche_vrai_prefixe ? $t : $t1);
94
-			}
95
-		}
96
-	}
97
-	sort($res);
98
-
99
-	return $res;
83
+    spip_connect($serveur);
84
+    $connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
85
+    $prefixe = $connexion['prefixe'];
86
+
87
+    $p = '/^' . $prefixe . '/';
88
+    $res = $tables;
89
+    foreach (sql_alltable(null, $serveur) as $t) {
90
+        if (preg_match($p, $t)) {
91
+            $t1 = preg_replace($p, 'spip', $t);
92
+            if (!in_array($t1, $tables) and !in_array($t1, $exclude)) {
93
+                $res[] = ($affiche_vrai_prefixe ? $t : $t1);
94
+            }
95
+        }
96
+    }
97
+    sort($res);
98
+
99
+    return $res;
100 100
 }
101 101
 
102 102
 /**
@@ -106,11 +106,11 @@  discard block
 block discarded – undo
106 106
  * @return string
107 107
  */
108 108
 function base_prefixe_tables($serveur = '') {
109
-	spip_connect($serveur);
110
-	$connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
111
-	$prefixe = $connexion['prefixe'];
109
+    spip_connect($serveur);
110
+    $connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
111
+    $prefixe = $connexion['prefixe'];
112 112
 
113
-	return $prefixe;
113
+    return $prefixe;
114 114
 }
115 115
 
116 116
 
@@ -125,31 +125,31 @@  discard block
 block discarded – undo
125 125
  * @return array
126 126
  */
127 127
 function base_saisie_tables($name, $tables, $exclude = [], $post = null, $serveur = '') {
128
-	include_spip('inc/filtres');
129
-	$res = [];
130
-	foreach ($tables as $k => $t) {
131
-		// par defaut tout est coche sauf les tables dans $exclude
132
-		if (is_null($post)) {
133
-			$check = (in_array($t, $exclude) ? false : true);
134
-		} // mais si on a poste une selection, la reprendre
135
-		else {
136
-			$check = in_array($t, $post);
137
-		}
138
-
139
-		$res[$k] = "<input type='checkbox' value='$t' name='$name"
140
-			. "[]' id='$name$k'"
141
-			. ($check ? " checked='checked'" : '')
142
-			. "/>\n"
143
-			. "<label for='$name$k'>$t</label>"
144
-			. ' ('
145
-			. sinon(
146
-				singulier_ou_pluriel(sql_countsel($t, '', '', '', $serveur), 'dump:une_donnee', 'dump:nb_donnees'),
147
-				_T('dump:aucune_donnee')
148
-			)
149
-			. ')';
150
-	}
151
-
152
-	return $res;
128
+    include_spip('inc/filtres');
129
+    $res = [];
130
+    foreach ($tables as $k => $t) {
131
+        // par defaut tout est coche sauf les tables dans $exclude
132
+        if (is_null($post)) {
133
+            $check = (in_array($t, $exclude) ? false : true);
134
+        } // mais si on a poste une selection, la reprendre
135
+        else {
136
+            $check = in_array($t, $post);
137
+        }
138
+
139
+        $res[$k] = "<input type='checkbox' value='$t' name='$name"
140
+            . "[]' id='$name$k'"
141
+            . ($check ? " checked='checked'" : '')
142
+            . "/>\n"
143
+            . "<label for='$name$k'>$t</label>"
144
+            . ' ('
145
+            . sinon(
146
+                singulier_ou_pluriel(sql_countsel($t, '', '', '', $serveur), 'dump:une_donnee', 'dump:nb_donnees'),
147
+                _T('dump:aucune_donnee')
148
+            )
149
+            . ')';
150
+    }
151
+
152
+    return $res;
153 153
 }
154 154
 
155 155
 
@@ -161,27 +161,27 @@  discard block
 block discarded – undo
161 161
  * @return array
162 162
  */
163 163
 function lister_tables_noexport() {
164
-	// par defaut tout est exporte sauf les tables ci-dessous
165
-	static $EXPORT_tables_noexport = null;
166
-	if (!is_null($EXPORT_tables_noexport)) {
167
-		return $EXPORT_tables_noexport;
168
-	}
169
-
170
-	$EXPORT_tables_noexport = [
171
-		'spip_caches', // plugin invalideur
172
-		'spip_resultats', // resultats de recherche ... c'est un cache !
173
-		'spip_test', // c'est un test !
174
-		#'spip_referers',
175
-		#'spip_referers_articles',
176
-		#'spip_visites',
177
-		#'spip_visites_articles',
178
-		#'spip_versions',
179
-		#'spip_versions_fragments'
180
-	];
181
-
182
-	$EXPORT_tables_noexport = pipeline('lister_tables_noexport', $EXPORT_tables_noexport);
183
-
184
-	return $EXPORT_tables_noexport;
164
+    // par defaut tout est exporte sauf les tables ci-dessous
165
+    static $EXPORT_tables_noexport = null;
166
+    if (!is_null($EXPORT_tables_noexport)) {
167
+        return $EXPORT_tables_noexport;
168
+    }
169
+
170
+    $EXPORT_tables_noexport = [
171
+        'spip_caches', // plugin invalideur
172
+        'spip_resultats', // resultats de recherche ... c'est un cache !
173
+        'spip_test', // c'est un test !
174
+        #'spip_referers',
175
+        #'spip_referers_articles',
176
+        #'spip_visites',
177
+        #'spip_visites_articles',
178
+        #'spip_versions',
179
+        #'spip_versions_fragments'
180
+    ];
181
+
182
+    $EXPORT_tables_noexport = pipeline('lister_tables_noexport', $EXPORT_tables_noexport);
183
+
184
+    return $EXPORT_tables_noexport;
185 185
 }
186 186
 
187 187
 /**
@@ -192,25 +192,25 @@  discard block
 block discarded – undo
192 192
  * @return array
193 193
  */
194 194
 function lister_tables_noimport() {
195
-	static $IMPORT_tables_noimport = null;
196
-	if (!is_null($IMPORT_tables_noimport)) {
197
-		return $IMPORT_tables_noimport;
198
-	}
199
-
200
-	$IMPORT_tables_noimport = [];
201
-	// par defaut tout est importe sauf les tables ci-dessous
202
-	// possibiliter de definir cela tables via la meta
203
-	// compatibilite
204
-	if (isset($GLOBALS['meta']['IMPORT_tables_noimport'])) {
205
-		$IMPORT_tables_noimport = unserialize($GLOBALS['meta']['IMPORT_tables_noimport']);
206
-		if (!is_array($IMPORT_tables_noimport)) {
207
-			include_spip('inc/meta');
208
-			effacer_meta('IMPORT_tables_noimport');
209
-		}
210
-	}
211
-	$IMPORT_tables_noimport = pipeline('lister_tables_noimport', $IMPORT_tables_noimport);
212
-
213
-	return $IMPORT_tables_noimport;
195
+    static $IMPORT_tables_noimport = null;
196
+    if (!is_null($IMPORT_tables_noimport)) {
197
+        return $IMPORT_tables_noimport;
198
+    }
199
+
200
+    $IMPORT_tables_noimport = [];
201
+    // par defaut tout est importe sauf les tables ci-dessous
202
+    // possibiliter de definir cela tables via la meta
203
+    // compatibilite
204
+    if (isset($GLOBALS['meta']['IMPORT_tables_noimport'])) {
205
+        $IMPORT_tables_noimport = unserialize($GLOBALS['meta']['IMPORT_tables_noimport']);
206
+        if (!is_array($IMPORT_tables_noimport)) {
207
+            include_spip('inc/meta');
208
+            effacer_meta('IMPORT_tables_noimport');
209
+        }
210
+    }
211
+    $IMPORT_tables_noimport = pipeline('lister_tables_noimport', $IMPORT_tables_noimport);
212
+
213
+    return $IMPORT_tables_noimport;
214 214
 }
215 215
 
216 216
 
@@ -222,23 +222,23 @@  discard block
 block discarded – undo
222 222
  * @return array
223 223
  */
224 224
 function lister_tables_noerase() {
225
-	static $IMPORT_tables_noerase = null;
226
-	if (!is_null($IMPORT_tables_noerase)) {
227
-		return $IMPORT_tables_noerase;
228
-	}
229
-
230
-	$IMPORT_tables_noerase = [
231
-		'spip_meta',
232
-		// par defaut on ne vide pas les stats, car elles ne figurent pas dans les dump
233
-		// et le cas echeant, un bouton dans l'admin permet de les vider a la main...
234
-		'spip_referers',
235
-		'spip_referers_articles',
236
-		'spip_visites',
237
-		'spip_visites_articles'
238
-	];
239
-	$IMPORT_tables_noerase = pipeline('lister_tables_noerase', $IMPORT_tables_noerase);
240
-
241
-	return $IMPORT_tables_noerase;
225
+    static $IMPORT_tables_noerase = null;
226
+    if (!is_null($IMPORT_tables_noerase)) {
227
+        return $IMPORT_tables_noerase;
228
+    }
229
+
230
+    $IMPORT_tables_noerase = [
231
+        'spip_meta',
232
+        // par defaut on ne vide pas les stats, car elles ne figurent pas dans les dump
233
+        // et le cas echeant, un bouton dans l'admin permet de les vider a la main...
234
+        'spip_referers',
235
+        'spip_referers_articles',
236
+        'spip_visites',
237
+        'spip_visites_articles'
238
+    ];
239
+    $IMPORT_tables_noerase = pipeline('lister_tables_noerase', $IMPORT_tables_noerase);
240
+
241
+    return $IMPORT_tables_noerase;
242 242
 }
243 243
 
244 244
 
@@ -252,86 +252,86 @@  discard block
 block discarded – undo
252 252
  * @return array
253 253
  */
254 254
 function base_liste_table_for_dump($exclude_tables = []) {
255
-	$tables_for_dump = [];
256
-	$tables_pointees = [];
257
-	$tables = [];
258
-	$tables_principales = $GLOBALS['tables_principales'];
259
-	$tables_auxiliaires = $GLOBALS['tables_auxiliaires'];
260
-	$tables_jointures = $GLOBALS['tables_jointures'];
261
-
262
-	if (
263
-		include_spip('base/objets')
264
-		and function_exists('lister_tables_objets_sql')
265
-	) {
266
-		$tables = lister_tables_objets_sql();
267
-		foreach ($tables as $t => $infos) {
268
-			if ($infos['principale'] and !isset($tables_principales[$t])) {
269
-				$tables_principales[$t] = true;
270
-			}
271
-			if (!$infos['principale'] and !isset($tables_auxiliaires[$t])) {
272
-				$tables_auxiliaires[$t] = true;
273
-			}
274
-			if (count($infos['tables_jointures'])) {
275
-				$tables_jointures[$t] = array_merge(
276
-					isset($tables_jointures[$t]) ? $tables_jointures[$t] : [],
277
-					$infos['tables_jointures']
278
-				);
279
-			}
280
-		}
281
-	}
282
-
283
-	// on construit un index des tables de liens
284
-	// pour les ajouter SI les deux tables qu'ils connectent sont sauvegardees
285
-	$tables_for_link = [];
286
-	foreach ($tables_jointures as $table => $liste_relations) {
287
-		if (is_array($liste_relations)) {
288
-			$nom = $table;
289
-			if (!isset($tables_auxiliaires[$nom]) && !isset($tables_principales[$nom])) {
290
-				$nom = "spip_$table";
291
-			}
292
-			if (isset($tables_auxiliaires[$nom]) || isset($tables_principales[$nom])) {
293
-				foreach ($liste_relations as $link_table) {
294
-					if (isset($tables_auxiliaires[$link_table])/*||isset($tables_principales[$link_table])*/) {
295
-						$tables_for_link[$link_table][] = $nom;
296
-					} else {
297
-						if (isset($tables_auxiliaires["spip_$link_table"])/*||isset($tables_principales["spip_$link_table"])*/) {
298
-							$tables_for_link["spip_$link_table"][] = $nom;
299
-						}
300
-					}
301
-				}
302
-			}
303
-		}
304
-	}
305
-
306
-	$liste_tables = array_merge(array_keys($tables_principales), array_keys($tables_auxiliaires), array_keys($tables));
307
-	foreach ($liste_tables as $table) {
308
-		//		$name = preg_replace("{^spip_}","",$table);
309
-		if (
310
-			!isset($tables_pointees[$table])
311
-			&& !in_array($table, $exclude_tables)
312
-			&& !isset($tables_for_link[$table])
313
-		) {
314
-			$tables_for_dump[] = $table;
315
-			$tables_pointees[$table] = 1;
316
-		}
317
-	}
318
-	foreach ($tables_for_link as $link_table => $liste) {
319
-		$connecte = true;
320
-		foreach ($liste as $connect_table) {
321
-			if (!in_array($connect_table, $tables_for_dump)) {
322
-				$connecte = false;
323
-			}
324
-		}
325
-		if ($connecte) {
326
-			# on ajoute les liaisons en premier
327
-			# si une restauration est interrompue,
328
-			# cela se verra mieux si il manque des objets
329
-			# que des liens
330
-		array_unshift($tables_for_dump, $link_table);
331
-		}
332
-	}
333
-
334
-	return [$tables_for_dump, $tables_for_link];
255
+    $tables_for_dump = [];
256
+    $tables_pointees = [];
257
+    $tables = [];
258
+    $tables_principales = $GLOBALS['tables_principales'];
259
+    $tables_auxiliaires = $GLOBALS['tables_auxiliaires'];
260
+    $tables_jointures = $GLOBALS['tables_jointures'];
261
+
262
+    if (
263
+        include_spip('base/objets')
264
+        and function_exists('lister_tables_objets_sql')
265
+    ) {
266
+        $tables = lister_tables_objets_sql();
267
+        foreach ($tables as $t => $infos) {
268
+            if ($infos['principale'] and !isset($tables_principales[$t])) {
269
+                $tables_principales[$t] = true;
270
+            }
271
+            if (!$infos['principale'] and !isset($tables_auxiliaires[$t])) {
272
+                $tables_auxiliaires[$t] = true;
273
+            }
274
+            if (count($infos['tables_jointures'])) {
275
+                $tables_jointures[$t] = array_merge(
276
+                    isset($tables_jointures[$t]) ? $tables_jointures[$t] : [],
277
+                    $infos['tables_jointures']
278
+                );
279
+            }
280
+        }
281
+    }
282
+
283
+    // on construit un index des tables de liens
284
+    // pour les ajouter SI les deux tables qu'ils connectent sont sauvegardees
285
+    $tables_for_link = [];
286
+    foreach ($tables_jointures as $table => $liste_relations) {
287
+        if (is_array($liste_relations)) {
288
+            $nom = $table;
289
+            if (!isset($tables_auxiliaires[$nom]) && !isset($tables_principales[$nom])) {
290
+                $nom = "spip_$table";
291
+            }
292
+            if (isset($tables_auxiliaires[$nom]) || isset($tables_principales[$nom])) {
293
+                foreach ($liste_relations as $link_table) {
294
+                    if (isset($tables_auxiliaires[$link_table])/*||isset($tables_principales[$link_table])*/) {
295
+                        $tables_for_link[$link_table][] = $nom;
296
+                    } else {
297
+                        if (isset($tables_auxiliaires["spip_$link_table"])/*||isset($tables_principales["spip_$link_table"])*/) {
298
+                            $tables_for_link["spip_$link_table"][] = $nom;
299
+                        }
300
+                    }
301
+                }
302
+            }
303
+        }
304
+    }
305
+
306
+    $liste_tables = array_merge(array_keys($tables_principales), array_keys($tables_auxiliaires), array_keys($tables));
307
+    foreach ($liste_tables as $table) {
308
+        //		$name = preg_replace("{^spip_}","",$table);
309
+        if (
310
+            !isset($tables_pointees[$table])
311
+            && !in_array($table, $exclude_tables)
312
+            && !isset($tables_for_link[$table])
313
+        ) {
314
+            $tables_for_dump[] = $table;
315
+            $tables_pointees[$table] = 1;
316
+        }
317
+    }
318
+    foreach ($tables_for_link as $link_table => $liste) {
319
+        $connecte = true;
320
+        foreach ($liste as $connect_table) {
321
+            if (!in_array($connect_table, $tables_for_dump)) {
322
+                $connecte = false;
323
+            }
324
+        }
325
+        if ($connecte) {
326
+            # on ajoute les liaisons en premier
327
+            # si une restauration est interrompue,
328
+            # cela se verra mieux si il manque des objets
329
+            # que des liens
330
+        array_unshift($tables_for_dump, $link_table);
331
+        }
332
+    }
333
+
334
+    return [$tables_for_dump, $tables_for_link];
335 335
 }
336 336
 
337 337
 /**
@@ -346,37 +346,37 @@  discard block
 block discarded – undo
346 346
  * @param string $serveur
347 347
  */
348 348
 function base_vider_tables_destination_copie($tables, $exclure_tables = [], $serveur = '') {
349
-	$trouver_table = charger_fonction('trouver_table', 'base');
350
-
351
-	spip_log(
352
-		'Vider ' . count($tables) . " tables sur serveur '$serveur' : " . join(', ', $tables),
353
-		'base.' . _LOG_INFO_IMPORTANTE
354
-	);
355
-	foreach ($tables as $table) {
356
-		if (!in_array($table, $exclure_tables)) {
357
-			// sur le serveur principal, il ne faut pas supprimer l'auteur loge !
358
-			if (($table != 'spip_auteurs') or $serveur != '') {
359
-				// regarder si il y a au moins un champ impt='non'
360
-				$desc = $trouver_table($table, $serveur);
361
-				if (isset($desc['field']['impt'])) {
362
-					sql_delete($table, "impt='oui'", $serveur);
363
-				} elseif ($desc) {
364
-					sql_delete($table, '', $serveur);
365
-				}
366
-			}
367
-		}
368
-	}
369
-
370
-	// sur le serveur principal, il ne faut pas supprimer l'auteur loge !
371
-	// Bidouille pour garder l'acces admin actuel pendant toute la restauration
372
-	if (
373
-		$serveur == ''
374
-		and in_array('spip_auteurs', $tables)
375
-		and !in_array('spip_auteurs', $exclure_tables)
376
-	) {
377
-		base_conserver_copieur(true, $serveur);
378
-		sql_delete('spip_auteurs', 'id_auteur>0', $serveur);
379
-	}
349
+    $trouver_table = charger_fonction('trouver_table', 'base');
350
+
351
+    spip_log(
352
+        'Vider ' . count($tables) . " tables sur serveur '$serveur' : " . join(', ', $tables),
353
+        'base.' . _LOG_INFO_IMPORTANTE
354
+    );
355
+    foreach ($tables as $table) {
356
+        if (!in_array($table, $exclure_tables)) {
357
+            // sur le serveur principal, il ne faut pas supprimer l'auteur loge !
358
+            if (($table != 'spip_auteurs') or $serveur != '') {
359
+                // regarder si il y a au moins un champ impt='non'
360
+                $desc = $trouver_table($table, $serveur);
361
+                if (isset($desc['field']['impt'])) {
362
+                    sql_delete($table, "impt='oui'", $serveur);
363
+                } elseif ($desc) {
364
+                    sql_delete($table, '', $serveur);
365
+                }
366
+            }
367
+        }
368
+    }
369
+
370
+    // sur le serveur principal, il ne faut pas supprimer l'auteur loge !
371
+    // Bidouille pour garder l'acces admin actuel pendant toute la restauration
372
+    if (
373
+        $serveur == ''
374
+        and in_array('spip_auteurs', $tables)
375
+        and !in_array('spip_auteurs', $exclure_tables)
376
+    ) {
377
+        base_conserver_copieur(true, $serveur);
378
+        sql_delete('spip_auteurs', 'id_auteur>0', $serveur);
379
+    }
380 380
 }
381 381
 
382 382
 /**
@@ -387,36 +387,36 @@  discard block
 block discarded – undo
387 387
  * @return void
388 388
  */
389 389
 function base_conserver_copieur($move = true, $serveur = '') {
390
-	// s'asurer qu'on a pas deja fait la manip !
391
-	if ($GLOBALS['visiteur_session']['id_auteur'] > 0 and sql_countsel('spip_auteurs', 'id_auteur>0')) {
392
-		spip_log(
393
-			'Conserver copieur dans id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'] . " pour le serveur '$serveur'",
394
-			'dump.' . _LOG_INFO_IMPORTANTE
395
-		);
396
-		sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
397
-		if ($move) {
398
-			sql_updateq(
399
-				'spip_auteurs',
400
-				['id_auteur' => -$GLOBALS['visiteur_session']['id_auteur']],
401
-				'id_auteur=' . intval($GLOBALS['visiteur_session']['id_auteur']),
402
-				[],
403
-				$serveur
404
-			);
405
-		} else {
406
-			$row = sql_fetsel(
407
-				'*',
408
-				'spip_auteurs',
409
-				'id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'],
410
-				'',
411
-				'',
412
-				'',
413
-				'',
414
-				$serveur
415
-			);
416
-			$row['id_auteur'] = -$GLOBALS['visiteur_session']['id_auteur'];
417
-			sql_insertq('spip_auteurs', $row, [], $serveur);
418
-		}
419
-	}
390
+    // s'asurer qu'on a pas deja fait la manip !
391
+    if ($GLOBALS['visiteur_session']['id_auteur'] > 0 and sql_countsel('spip_auteurs', 'id_auteur>0')) {
392
+        spip_log(
393
+            'Conserver copieur dans id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'] . " pour le serveur '$serveur'",
394
+            'dump.' . _LOG_INFO_IMPORTANTE
395
+        );
396
+        sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
397
+        if ($move) {
398
+            sql_updateq(
399
+                'spip_auteurs',
400
+                ['id_auteur' => -$GLOBALS['visiteur_session']['id_auteur']],
401
+                'id_auteur=' . intval($GLOBALS['visiteur_session']['id_auteur']),
402
+                [],
403
+                $serveur
404
+            );
405
+        } else {
406
+            $row = sql_fetsel(
407
+                '*',
408
+                'spip_auteurs',
409
+                'id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'],
410
+                '',
411
+                '',
412
+                '',
413
+                '',
414
+                $serveur
415
+            );
416
+            $row['id_auteur'] = -$GLOBALS['visiteur_session']['id_auteur'];
417
+            sql_insertq('spip_auteurs', $row, [], $serveur);
418
+        }
419
+    }
420 420
 }
421 421
 
422 422
 /**
@@ -431,21 +431,21 @@  discard block
 block discarded – undo
431 431
  * @param string $serveur
432 432
  */
433 433
 function base_detruire_copieur_si_besoin($serveur = '') {
434
-	// rien a faire si ce n'est pas le serveur principal !
435
-	if ($serveur == '') {
436
-		if (sql_countsel('spip_auteurs', 'id_auteur>0')) {
437
-			spip_log("Detruire copieur id_auteur<0 pour le serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
438
-			sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
439
-		} else {
440
-			spip_log(
441
-				"Restaurer copieur id_auteur<0 pour le serveur '$serveur' (aucun autre auteur en base)",
442
-				'dump.' . _LOG_INFO_IMPORTANTE
443
-			);
444
-			sql_update('spip_auteurs', ['id_auteur' => '-id_auteur'], 'id_auteur<0');
445
-		}
446
-	} else {
447
-		spip_log("Pas de destruction copieur sur serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
448
-	}
434
+    // rien a faire si ce n'est pas le serveur principal !
435
+    if ($serveur == '') {
436
+        if (sql_countsel('spip_auteurs', 'id_auteur>0')) {
437
+            spip_log("Detruire copieur id_auteur<0 pour le serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
438
+            sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
439
+        } else {
440
+            spip_log(
441
+                "Restaurer copieur id_auteur<0 pour le serveur '$serveur' (aucun autre auteur en base)",
442
+                'dump.' . _LOG_INFO_IMPORTANTE
443
+            );
444
+            sql_update('spip_auteurs', ['id_auteur' => '-id_auteur'], 'id_auteur<0');
445
+        }
446
+    } else {
447
+        spip_log("Pas de destruction copieur sur serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
448
+    }
449 449
 }
450 450
 
451 451
 /**
@@ -460,40 +460,40 @@  discard block
 block discarded – undo
460 460
  * @return array
461 461
  */
462 462
 function base_preparer_table_dest($table, $desc, $serveur_dest, $init = false) {
463
-	$upgrade = false;
464
-	// si la table existe et qu'on est a l'init, la dropper
465
-	if ($desc_dest = sql_showtable($table, true, $serveur_dest) and $init) {
466
-		if ($serveur_dest == '' and in_array($table, ['spip_meta', 'spip_auteurs'])) {
467
-			// ne pas dropper auteurs et meta sur le serveur principal
468
-			// faire un simple upgrade a la place
469
-			// pour ajouter les champs manquants
470
-			$upgrade = true;
471
-			// coherence avec le drop sur les autres tables
472
-			base_vider_tables_destination_copie([$table], [], $serveur_dest);
473
-			if ($table == 'spip_meta') {
474
-				// virer les version base qui vont venir avec l'import
475
-				sql_delete($table, "nom like '%_base_version'", $serveur_dest);
476
-				// hum casse la base si pas version_installee a l'import ...
477
-				sql_delete($table, "nom='version_installee'", $serveur_dest);
478
-			}
479
-		} else {
480
-			sql_drop_table($table, '', $serveur_dest);
481
-			spip_log("drop table '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
482
-		}
483
-		$desc_dest = false;
484
-	}
485
-	// si la table n'existe pas dans la destination, la creer a l'identique !
486
-	if (!$desc_dest) {
487
-		spip_log("creation '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
488
-		include_spip('base/create');
489
-		creer_ou_upgrader_table($table, $desc, 'auto', $upgrade, $serveur_dest);
490
-		$desc_dest = sql_showtable($table, true, $serveur_dest);
491
-	}
492
-	if (!$desc_dest) {
493
-		spip_log("Erreur creation '$table' sur serveur '$serveur_dest'" . var_export($desc, 1), 'dump.' . _LOG_ERREUR);
494
-	}
495
-
496
-	return $desc_dest;
463
+    $upgrade = false;
464
+    // si la table existe et qu'on est a l'init, la dropper
465
+    if ($desc_dest = sql_showtable($table, true, $serveur_dest) and $init) {
466
+        if ($serveur_dest == '' and in_array($table, ['spip_meta', 'spip_auteurs'])) {
467
+            // ne pas dropper auteurs et meta sur le serveur principal
468
+            // faire un simple upgrade a la place
469
+            // pour ajouter les champs manquants
470
+            $upgrade = true;
471
+            // coherence avec le drop sur les autres tables
472
+            base_vider_tables_destination_copie([$table], [], $serveur_dest);
473
+            if ($table == 'spip_meta') {
474
+                // virer les version base qui vont venir avec l'import
475
+                sql_delete($table, "nom like '%_base_version'", $serveur_dest);
476
+                // hum casse la base si pas version_installee a l'import ...
477
+                sql_delete($table, "nom='version_installee'", $serveur_dest);
478
+            }
479
+        } else {
480
+            sql_drop_table($table, '', $serveur_dest);
481
+            spip_log("drop table '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
482
+        }
483
+        $desc_dest = false;
484
+    }
485
+    // si la table n'existe pas dans la destination, la creer a l'identique !
486
+    if (!$desc_dest) {
487
+        spip_log("creation '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
488
+        include_spip('base/create');
489
+        creer_ou_upgrader_table($table, $desc, 'auto', $upgrade, $serveur_dest);
490
+        $desc_dest = sql_showtable($table, true, $serveur_dest);
491
+    }
492
+    if (!$desc_dest) {
493
+        spip_log("Erreur creation '$table' sur serveur '$serveur_dest'" . var_export($desc, 1), 'dump.' . _LOG_ERREUR);
494
+    }
495
+
496
+    return $desc_dest;
497 497
 }
498 498
 
499 499
 /**
@@ -539,210 +539,210 @@  discard block
 block discarded – undo
539 539
  */
540 540
 function base_copier_tables($status_file, $tables, $serveur_source, $serveur_dest, $options = []) {
541 541
 
542
-	$callback_progression = $options['callback_progression'] ?? '';
543
-	$max_time = $options['max_time'] ?? 0;
544
-	$drop_source = $options['drop_source'] ?? false;
545
-	$no_erase_dest = $options['no_erase_dest'] ?? [];
546
-	$where = $options['where'] ?? [];
547
-	$fonction_base_inserer = $options['fonction_base_inserer'] ?? 'inserer_copie';
548
-	$desc_tables_dest = $options['desc_tables_dest'] ?? [];
549
-	$racine_fonctions = $options['racine_fonctions_dest'] ?? 'base';
550
-	$data_pool = $options['data_pool'] ?? 50 * 1024;
551
-
552
-	spip_log(
553
-		'Copier ' . count($tables) . " tables de '$serveur_source' vers '$serveur_dest'",
554
-		'dump.' . _LOG_INFO_IMPORTANTE
555
-	);
556
-
557
-	if (!$inserer_copie = charger_fonction($fonction_base_inserer, $racine_fonctions, true)) {
558
-		spip_log("Fonction '{$racine_fonctions}_$fonction_base_inserer' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
559
-
560
-		return true; // echec mais on a fini, donc true
561
-	}
562
-	if (!$preparer_table_dest = charger_fonction('preparer_table_dest', $racine_fonctions, true)) {
563
-		spip_log("Fonction '{$racine_fonctions}_$preparer_table_dest' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
564
-
565
-		return true; // echec mais on a fini, donc true
566
-	}
567
-
568
-	if (
569
-		!lire_fichier($status_file, $status)
570
-		or !$status = unserialize($status)
571
-	) {
572
-		$status = [];
573
-	}
574
-	$status['etape'] = 'basecopie';
575
-
576
-	// puis relister les tables a importer
577
-	// et les vider si besoin, au moment du premier passage ici
578
-	$initialisation_copie = (!isset($status['dump_status_copie'])) ? 0 : $status['dump_status_copie'];
579
-
580
-	// si init pas encore faite, vider les tables du serveur destination
581
-	if (!$initialisation_copie) {
582
-		if (
583
-			!$vider_tables_destination_copie = charger_fonction(
584
-				'vider_tables_destination_copie',
585
-				$racine_fonctions,
586
-				true
587
-			)
588
-		) {
589
-			spip_log(
590
-				"Fonction '{$racine_fonctions}_vider_tables_destination_copie' inconnue. Abandon",
591
-				'dump.' . _LOG_INFO_IMPORTANTE
592
-			);
593
-
594
-			return true; // echec mais on a fini, donc true
595
-		}
596
-		$vider_tables_destination_copie($tables, $no_erase_dest, $serveur_dest);
597
-		$status['dump_status_copie'] = 'ok';
598
-		ecrire_fichier($status_file, serialize($status));
599
-	}
600
-
601
-	// les tables auteurs et meta doivent etre copiees en dernier !
602
-	if (in_array('spip_auteurs', $tables)) {
603
-		$tables = array_diff($tables, ['spip_auteurs']);
604
-		$tables[] = 'spip_auteurs';
605
-	}
606
-	if (in_array('spip_meta', $tables)) {
607
-		$tables = array_diff($tables, ['spip_meta']);
608
-		$tables[] = 'spip_meta';
609
-	}
610
-	spip_log('Tables a copier :' . implode(', ', $tables), 'dump.' . _LOG_INFO);
611
-
612
-	$trouver_table = charger_fonction('trouver_table', 'base');
613
-
614
-	foreach ($tables as $table) {
615
-		// si table commence par spip_ c'est une table SPIP, renommer le prefixe si besoin
616
-		// sinon chercher la vraie table
617
-		$desc_source = false;
618
-		if (strncmp($table, 'spip_', 5) == 0) {
619
-			$desc_source = $trouver_table(preg_replace(',^spip_,', '', $table), $serveur_source, true);
620
-		}
621
-		if (!$desc_source or !isset($desc_source['exist']) or !$desc_source['exist']) {
622
-			$desc_source = $trouver_table($table, $serveur_source, false);
623
-		}
624
-
625
-		// verifier que la table est presente dans la base source
626
-		if ($desc_source) {
627
-			// $status['tables_copiees'][$table] contient l'avancement
628
-			// de la copie pour la $table : 0 a N et -N quand elle est finie (-1 si vide et finie...)
629
-			if (!isset($status['tables_copiees'][$table])) {
630
-				$status['tables_copiees'][$table] = 0;
631
-			}
632
-
633
-			if (
634
-				is_numeric($status['tables_copiees'][$table])
635
-				and $status['tables_copiees'][$table] >= 0
636
-				and $desc_dest = $preparer_table_dest(
637
-					$table,
638
-					isset($desc_tables_dest[$table]) ? $desc_tables_dest[$table] : $desc_source,
639
-					$serveur_dest,
640
-					$status['tables_copiees'][$table] == 0
641
-				)
642
-			) {
643
-				if ($callback_progression) {
644
-					$callback_progression($status['tables_copiees'][$table], 0, $table);
645
-				}
646
-				while (true) {
647
-					$n = intval($status['tables_copiees'][$table]);
648
-					// on copie par lot de 400
649
-					$res = sql_select(
650
-						'*',
651
-						$table,
652
-						isset($where[$table]) ? $where[$table] : '',
653
-						'',
654
-						'',
655
-						"$n,400",
656
-						'',
657
-						$serveur_source
658
-					);
659
-					while ($row = sql_fetch($res, $serveur_source)) {
660
-						$rows = [$row];
661
-						// lire un groupe de donnees si demande en option
662
-						// (permet un envoi par lot vers la destination)
663
-						if ($data_pool > 0) {
664
-							$s = strlen(serialize($row));
665
-							while ($s < $data_pool and $row = sql_fetch($res, $serveur_source)) {
666
-								$s += strlen(serialize($row));
667
-								$rows[] = $row;
668
-							}
669
-						}
670
-						// si l'enregistrement est deja en base, ca fera un echec ou un doublon
671
-						// mais si ca renvoie false c'est une erreur fatale => abandon
672
-						if ($inserer_copie($table, $rows, $desc_dest, $serveur_dest) === false) {
673
-							// forcer la sortie, charge a l'appelant de gerer l'echec
674
-							spip_log("Erreur fatale dans $inserer_copie table $table", 'dump' . _LOG_ERREUR);
675
-							$status['errors'][] = "Erreur fatale  lors de la copie de la table $table";
676
-							ecrire_fichier($status_file, serialize($status));
677
-
678
-							// copie finie
679
-							return true;
680
-						}
681
-						$status['tables_copiees'][$table] += count($rows);
682
-						if ($max_time and time() > $max_time) {
683
-							break;
684
-						}
685
-					}
686
-					if ($n == $status['tables_copiees'][$table]) {
687
-						break;
688
-					}
689
-					spip_log("recopie $table " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO_IMPORTANTE);
690
-					if ($callback_progression) {
691
-						$callback_progression($status['tables_copiees'][$table], 0, $table);
692
-					}
693
-					ecrire_fichier($status_file, serialize($status));
694
-					if ($max_time and time() > $max_time) {
695
-						return false;
696
-					} // on a pas fini, mais le temps imparti est ecoule
697
-				}
698
-				if ($drop_source) {
699
-					sql_drop_table($table, '', $serveur_source);
700
-					spip_log("drop $table sur serveur source '$serveur_source'", 'dump.' . _LOG_INFO_IMPORTANTE);
701
-				}
702
-				$status['tables_copiees'][$table] = ($status['tables_copiees'][$table] ? -$status['tables_copiees'][$table] : 'zero');
703
-				ecrire_fichier($status_file, serialize($status));
704
-				spip_log('tables_recopiees ' . implode(',', array_keys($status['tables_copiees'])), 'dump.' . _LOG_INFO);
705
-				if ($callback_progression) {
706
-					$callback_progression($status['tables_copiees'][$table], $status['tables_copiees'][$table], $table);
707
-				}
708
-			} else {
709
-				if ($status['tables_copiees'][$table] < 0) {
710
-					spip_log("Table $table deja copiee : " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO);
711
-				}
712
-				if ($callback_progression) {
713
-					$callback_progression(
714
-						0,
715
-						$status['tables_copiees'][$table],
716
-						"$table" . ((is_numeric($status['tables_copiees'][$table]) and $status['tables_copiees'][$table] >= 0) ? '[Echec]' : '')
717
-					);
718
-				}
719
-			}
720
-		} else {
721
-			$status['errors'][] = "Impossible de lire la description de la table $table";
722
-			ecrire_fichier($status_file, serialize($status));
723
-			spip_log("Impossible de lire la description de la table $table", 'dump.' . _LOG_ERREUR);
724
-		}
725
-	}
726
-
727
-	// si le nombre de tables envoyees n'est pas egal au nombre de tables demandees
728
-	// abandonner
729
-	if (count($status['tables_copiees']) < count($tables)) {
730
-		spip_log(
731
-			'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables),
732
-			'dump.' . _LOG_ERREUR
733
-		);
734
-		$status['errors'][] = 'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables);
735
-		ecrire_fichier($status_file, serialize($status));
736
-	}
737
-
738
-	if ($detruire_copieur_si_besoin = charger_fonction('detruire_copieur_si_besoin', $racine_fonctions, true)) {
739
-		$detruire_copieur_si_besoin($serveur_dest);
740
-	} else {
741
-		spip_log("Fonction '{$racine_fonctions}_detruire_copieur_si_besoin' inconnue.", 'dump.' . _LOG_INFO_IMPORTANTE);
742
-	}
743
-
744
-	// OK, copie complete
745
-	return true;
542
+    $callback_progression = $options['callback_progression'] ?? '';
543
+    $max_time = $options['max_time'] ?? 0;
544
+    $drop_source = $options['drop_source'] ?? false;
545
+    $no_erase_dest = $options['no_erase_dest'] ?? [];
546
+    $where = $options['where'] ?? [];
547
+    $fonction_base_inserer = $options['fonction_base_inserer'] ?? 'inserer_copie';
548
+    $desc_tables_dest = $options['desc_tables_dest'] ?? [];
549
+    $racine_fonctions = $options['racine_fonctions_dest'] ?? 'base';
550
+    $data_pool = $options['data_pool'] ?? 50 * 1024;
551
+
552
+    spip_log(
553
+        'Copier ' . count($tables) . " tables de '$serveur_source' vers '$serveur_dest'",
554
+        'dump.' . _LOG_INFO_IMPORTANTE
555
+    );
556
+
557
+    if (!$inserer_copie = charger_fonction($fonction_base_inserer, $racine_fonctions, true)) {
558
+        spip_log("Fonction '{$racine_fonctions}_$fonction_base_inserer' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
559
+
560
+        return true; // echec mais on a fini, donc true
561
+    }
562
+    if (!$preparer_table_dest = charger_fonction('preparer_table_dest', $racine_fonctions, true)) {
563
+        spip_log("Fonction '{$racine_fonctions}_$preparer_table_dest' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
564
+
565
+        return true; // echec mais on a fini, donc true
566
+    }
567
+
568
+    if (
569
+        !lire_fichier($status_file, $status)
570
+        or !$status = unserialize($status)
571
+    ) {
572
+        $status = [];
573
+    }
574
+    $status['etape'] = 'basecopie';
575
+
576
+    // puis relister les tables a importer
577
+    // et les vider si besoin, au moment du premier passage ici
578
+    $initialisation_copie = (!isset($status['dump_status_copie'])) ? 0 : $status['dump_status_copie'];
579
+
580
+    // si init pas encore faite, vider les tables du serveur destination
581
+    if (!$initialisation_copie) {
582
+        if (
583
+            !$vider_tables_destination_copie = charger_fonction(
584
+                'vider_tables_destination_copie',
585
+                $racine_fonctions,
586
+                true
587
+            )
588
+        ) {
589
+            spip_log(
590
+                "Fonction '{$racine_fonctions}_vider_tables_destination_copie' inconnue. Abandon",
591
+                'dump.' . _LOG_INFO_IMPORTANTE
592
+            );
593
+
594
+            return true; // echec mais on a fini, donc true
595
+        }
596
+        $vider_tables_destination_copie($tables, $no_erase_dest, $serveur_dest);
597
+        $status['dump_status_copie'] = 'ok';
598
+        ecrire_fichier($status_file, serialize($status));
599
+    }
600
+
601
+    // les tables auteurs et meta doivent etre copiees en dernier !
602
+    if (in_array('spip_auteurs', $tables)) {
603
+        $tables = array_diff($tables, ['spip_auteurs']);
604
+        $tables[] = 'spip_auteurs';
605
+    }
606
+    if (in_array('spip_meta', $tables)) {
607
+        $tables = array_diff($tables, ['spip_meta']);
608
+        $tables[] = 'spip_meta';
609
+    }
610
+    spip_log('Tables a copier :' . implode(', ', $tables), 'dump.' . _LOG_INFO);
611
+
612
+    $trouver_table = charger_fonction('trouver_table', 'base');
613
+
614
+    foreach ($tables as $table) {
615
+        // si table commence par spip_ c'est une table SPIP, renommer le prefixe si besoin
616
+        // sinon chercher la vraie table
617
+        $desc_source = false;
618
+        if (strncmp($table, 'spip_', 5) == 0) {
619
+            $desc_source = $trouver_table(preg_replace(',^spip_,', '', $table), $serveur_source, true);
620
+        }
621
+        if (!$desc_source or !isset($desc_source['exist']) or !$desc_source['exist']) {
622
+            $desc_source = $trouver_table($table, $serveur_source, false);
623
+        }
624
+
625
+        // verifier que la table est presente dans la base source
626
+        if ($desc_source) {
627
+            // $status['tables_copiees'][$table] contient l'avancement
628
+            // de la copie pour la $table : 0 a N et -N quand elle est finie (-1 si vide et finie...)
629
+            if (!isset($status['tables_copiees'][$table])) {
630
+                $status['tables_copiees'][$table] = 0;
631
+            }
632
+
633
+            if (
634
+                is_numeric($status['tables_copiees'][$table])
635
+                and $status['tables_copiees'][$table] >= 0
636
+                and $desc_dest = $preparer_table_dest(
637
+                    $table,
638
+                    isset($desc_tables_dest[$table]) ? $desc_tables_dest[$table] : $desc_source,
639
+                    $serveur_dest,
640
+                    $status['tables_copiees'][$table] == 0
641
+                )
642
+            ) {
643
+                if ($callback_progression) {
644
+                    $callback_progression($status['tables_copiees'][$table], 0, $table);
645
+                }
646
+                while (true) {
647
+                    $n = intval($status['tables_copiees'][$table]);
648
+                    // on copie par lot de 400
649
+                    $res = sql_select(
650
+                        '*',
651
+                        $table,
652
+                        isset($where[$table]) ? $where[$table] : '',
653
+                        '',
654
+                        '',
655
+                        "$n,400",
656
+                        '',
657
+                        $serveur_source
658
+                    );
659
+                    while ($row = sql_fetch($res, $serveur_source)) {
660
+                        $rows = [$row];
661
+                        // lire un groupe de donnees si demande en option
662
+                        // (permet un envoi par lot vers la destination)
663
+                        if ($data_pool > 0) {
664
+                            $s = strlen(serialize($row));
665
+                            while ($s < $data_pool and $row = sql_fetch($res, $serveur_source)) {
666
+                                $s += strlen(serialize($row));
667
+                                $rows[] = $row;
668
+                            }
669
+                        }
670
+                        // si l'enregistrement est deja en base, ca fera un echec ou un doublon
671
+                        // mais si ca renvoie false c'est une erreur fatale => abandon
672
+                        if ($inserer_copie($table, $rows, $desc_dest, $serveur_dest) === false) {
673
+                            // forcer la sortie, charge a l'appelant de gerer l'echec
674
+                            spip_log("Erreur fatale dans $inserer_copie table $table", 'dump' . _LOG_ERREUR);
675
+                            $status['errors'][] = "Erreur fatale  lors de la copie de la table $table";
676
+                            ecrire_fichier($status_file, serialize($status));
677
+
678
+                            // copie finie
679
+                            return true;
680
+                        }
681
+                        $status['tables_copiees'][$table] += count($rows);
682
+                        if ($max_time and time() > $max_time) {
683
+                            break;
684
+                        }
685
+                    }
686
+                    if ($n == $status['tables_copiees'][$table]) {
687
+                        break;
688
+                    }
689
+                    spip_log("recopie $table " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO_IMPORTANTE);
690
+                    if ($callback_progression) {
691
+                        $callback_progression($status['tables_copiees'][$table], 0, $table);
692
+                    }
693
+                    ecrire_fichier($status_file, serialize($status));
694
+                    if ($max_time and time() > $max_time) {
695
+                        return false;
696
+                    } // on a pas fini, mais le temps imparti est ecoule
697
+                }
698
+                if ($drop_source) {
699
+                    sql_drop_table($table, '', $serveur_source);
700
+                    spip_log("drop $table sur serveur source '$serveur_source'", 'dump.' . _LOG_INFO_IMPORTANTE);
701
+                }
702
+                $status['tables_copiees'][$table] = ($status['tables_copiees'][$table] ? -$status['tables_copiees'][$table] : 'zero');
703
+                ecrire_fichier($status_file, serialize($status));
704
+                spip_log('tables_recopiees ' . implode(',', array_keys($status['tables_copiees'])), 'dump.' . _LOG_INFO);
705
+                if ($callback_progression) {
706
+                    $callback_progression($status['tables_copiees'][$table], $status['tables_copiees'][$table], $table);
707
+                }
708
+            } else {
709
+                if ($status['tables_copiees'][$table] < 0) {
710
+                    spip_log("Table $table deja copiee : " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO);
711
+                }
712
+                if ($callback_progression) {
713
+                    $callback_progression(
714
+                        0,
715
+                        $status['tables_copiees'][$table],
716
+                        "$table" . ((is_numeric($status['tables_copiees'][$table]) and $status['tables_copiees'][$table] >= 0) ? '[Echec]' : '')
717
+                    );
718
+                }
719
+            }
720
+        } else {
721
+            $status['errors'][] = "Impossible de lire la description de la table $table";
722
+            ecrire_fichier($status_file, serialize($status));
723
+            spip_log("Impossible de lire la description de la table $table", 'dump.' . _LOG_ERREUR);
724
+        }
725
+    }
726
+
727
+    // si le nombre de tables envoyees n'est pas egal au nombre de tables demandees
728
+    // abandonner
729
+    if (count($status['tables_copiees']) < count($tables)) {
730
+        spip_log(
731
+            'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables),
732
+            'dump.' . _LOG_ERREUR
733
+        );
734
+        $status['errors'][] = 'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables);
735
+        ecrire_fichier($status_file, serialize($status));
736
+    }
737
+
738
+    if ($detruire_copieur_si_besoin = charger_fonction('detruire_copieur_si_besoin', $racine_fonctions, true)) {
739
+        $detruire_copieur_si_besoin($serveur_dest);
740
+    } else {
741
+        spip_log("Fonction '{$racine_fonctions}_detruire_copieur_si_besoin' inconnue.", 'dump.' . _LOG_INFO_IMPORTANTE);
742
+    }
743
+
744
+    // OK, copie complete
745
+    return true;
746 746
 }
747 747
 
748 748
 /**
@@ -756,31 +756,31 @@  discard block
 block discarded – undo
756 756
  */
757 757
 function base_inserer_copie($table, $rows, $desc_dest, $serveur_dest) {
758 758
 
759
-	// verifier le nombre d'insertion
760
-	$nb1 = sql_countsel($table, '', '', '', $serveur_dest);
761
-	// si l'enregistrement est deja en base, ca fera un echec ou un doublon
762
-	$r = sql_insertq_multi($table, $rows, $desc_dest, $serveur_dest);
763
-	$nb = sql_countsel($table, '', '', '', $serveur_dest);
764
-	if ($nb - $nb1 < count($rows)) {
765
-		spip_log(
766
-			'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . '. On retente 1 par 1',
767
-			'dump' . _LOG_INFO_IMPORTANTE
768
-		);
769
-		foreach ($rows as $row) {
770
-			// si l'enregistrement est deja en base, ca fera un echec ou un doublon
771
-			$r = sql_insertq($table, $row, $desc_dest, $serveur_dest);
772
-		}
773
-		// on reverifie le total
774
-		$r = 0;
775
-		$nb = sql_countsel($table, '', '', '', $serveur_dest);
776
-		if ($nb - $nb1 < count($rows)) {
777
-			spip_log(
778
-				'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . ' apres insertion 1 par 1',
779
-				'dump' . _LOG_ERREUR
780
-			);
781
-			$r = false;
782
-		}
783
-	}
784
-
785
-	return $r;
759
+    // verifier le nombre d'insertion
760
+    $nb1 = sql_countsel($table, '', '', '', $serveur_dest);
761
+    // si l'enregistrement est deja en base, ca fera un echec ou un doublon
762
+    $r = sql_insertq_multi($table, $rows, $desc_dest, $serveur_dest);
763
+    $nb = sql_countsel($table, '', '', '', $serveur_dest);
764
+    if ($nb - $nb1 < count($rows)) {
765
+        spip_log(
766
+            'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . '. On retente 1 par 1',
767
+            'dump' . _LOG_INFO_IMPORTANTE
768
+        );
769
+        foreach ($rows as $row) {
770
+            // si l'enregistrement est deja en base, ca fera un echec ou un doublon
771
+            $r = sql_insertq($table, $row, $desc_dest, $serveur_dest);
772
+        }
773
+        // on reverifie le total
774
+        $r = 0;
775
+        $nb = sql_countsel($table, '', '', '', $serveur_dest);
776
+        if ($nb - $nb1 < count($rows)) {
777
+            spip_log(
778
+                'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . ' apres insertion 1 par 1',
779
+                'dump' . _LOG_ERREUR
780
+            );
781
+            $r = false;
782
+        }
783
+    }
784
+
785
+    return $r;
786 786
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
  * @return string
39 39
  **/
40 40
 function base_dump_meta_name($rub) {
41
-	return $meta = "status_dump_{$rub}_" . abs($GLOBALS['visiteur_session']['id_auteur']);
41
+	return $meta = "status_dump_{$rub}_".abs($GLOBALS['visiteur_session']['id_auteur']);
42 42
 }
43 43
 
44 44
 /**
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 	$connexion = $GLOBALS['connexions'][$serveur ? $serveur : 0];
85 85
 	$prefixe = $connexion['prefixe'];
86 86
 
87
-	$p = '/^' . $prefixe . '/';
87
+	$p = '/^'.$prefixe.'/';
88 88
 	$res = $tables;
89 89
 	foreach (sql_alltable(null, $serveur) as $t) {
90 90
 		if (preg_match($p, $t)) {
@@ -349,8 +349,8 @@  discard block
 block discarded – undo
349 349
 	$trouver_table = charger_fonction('trouver_table', 'base');
350 350
 
351 351
 	spip_log(
352
-		'Vider ' . count($tables) . " tables sur serveur '$serveur' : " . join(', ', $tables),
353
-		'base.' . _LOG_INFO_IMPORTANTE
352
+		'Vider '.count($tables)." tables sur serveur '$serveur' : ".join(', ', $tables),
353
+		'base.'._LOG_INFO_IMPORTANTE
354 354
 	);
355 355
 	foreach ($tables as $table) {
356 356
 		if (!in_array($table, $exclure_tables)) {
@@ -390,15 +390,15 @@  discard block
 block discarded – undo
390 390
 	// s'asurer qu'on a pas deja fait la manip !
391 391
 	if ($GLOBALS['visiteur_session']['id_auteur'] > 0 and sql_countsel('spip_auteurs', 'id_auteur>0')) {
392 392
 		spip_log(
393
-			'Conserver copieur dans id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'] . " pour le serveur '$serveur'",
394
-			'dump.' . _LOG_INFO_IMPORTANTE
393
+			'Conserver copieur dans id_auteur='.$GLOBALS['visiteur_session']['id_auteur']." pour le serveur '$serveur'",
394
+			'dump.'._LOG_INFO_IMPORTANTE
395 395
 		);
396 396
 		sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
397 397
 		if ($move) {
398 398
 			sql_updateq(
399 399
 				'spip_auteurs',
400 400
 				['id_auteur' => -$GLOBALS['visiteur_session']['id_auteur']],
401
-				'id_auteur=' . intval($GLOBALS['visiteur_session']['id_auteur']),
401
+				'id_auteur='.intval($GLOBALS['visiteur_session']['id_auteur']),
402 402
 				[],
403 403
 				$serveur
404 404
 			);
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 			$row = sql_fetsel(
407 407
 				'*',
408 408
 				'spip_auteurs',
409
-				'id_auteur=' . $GLOBALS['visiteur_session']['id_auteur'],
409
+				'id_auteur='.$GLOBALS['visiteur_session']['id_auteur'],
410 410
 				'',
411 411
 				'',
412 412
 				'',
@@ -434,17 +434,17 @@  discard block
 block discarded – undo
434 434
 	// rien a faire si ce n'est pas le serveur principal !
435 435
 	if ($serveur == '') {
436 436
 		if (sql_countsel('spip_auteurs', 'id_auteur>0')) {
437
-			spip_log("Detruire copieur id_auteur<0 pour le serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
437
+			spip_log("Detruire copieur id_auteur<0 pour le serveur '$serveur'", 'dump.'._LOG_INFO_IMPORTANTE);
438 438
 			sql_delete('spip_auteurs', 'id_auteur<0', $serveur);
439 439
 		} else {
440 440
 			spip_log(
441 441
 				"Restaurer copieur id_auteur<0 pour le serveur '$serveur' (aucun autre auteur en base)",
442
-				'dump.' . _LOG_INFO_IMPORTANTE
442
+				'dump.'._LOG_INFO_IMPORTANTE
443 443
 			);
444 444
 			sql_update('spip_auteurs', ['id_auteur' => '-id_auteur'], 'id_auteur<0');
445 445
 		}
446 446
 	} else {
447
-		spip_log("Pas de destruction copieur sur serveur '$serveur'", 'dump.' . _LOG_INFO_IMPORTANTE);
447
+		spip_log("Pas de destruction copieur sur serveur '$serveur'", 'dump.'._LOG_INFO_IMPORTANTE);
448 448
 	}
449 449
 }
450 450
 
@@ -478,19 +478,19 @@  discard block
 block discarded – undo
478 478
 			}
479 479
 		} else {
480 480
 			sql_drop_table($table, '', $serveur_dest);
481
-			spip_log("drop table '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
481
+			spip_log("drop table '$table' sur serveur '$serveur_dest'", 'dump.'._LOG_INFO_IMPORTANTE);
482 482
 		}
483 483
 		$desc_dest = false;
484 484
 	}
485 485
 	// si la table n'existe pas dans la destination, la creer a l'identique !
486 486
 	if (!$desc_dest) {
487
-		spip_log("creation '$table' sur serveur '$serveur_dest'", 'dump.' . _LOG_INFO_IMPORTANTE);
487
+		spip_log("creation '$table' sur serveur '$serveur_dest'", 'dump.'._LOG_INFO_IMPORTANTE);
488 488
 		include_spip('base/create');
489 489
 		creer_ou_upgrader_table($table, $desc, 'auto', $upgrade, $serveur_dest);
490 490
 		$desc_dest = sql_showtable($table, true, $serveur_dest);
491 491
 	}
492 492
 	if (!$desc_dest) {
493
-		spip_log("Erreur creation '$table' sur serveur '$serveur_dest'" . var_export($desc, 1), 'dump.' . _LOG_ERREUR);
493
+		spip_log("Erreur creation '$table' sur serveur '$serveur_dest'".var_export($desc, 1), 'dump.'._LOG_ERREUR);
494 494
 	}
495 495
 
496 496
 	return $desc_dest;
@@ -550,17 +550,17 @@  discard block
 block discarded – undo
550 550
 	$data_pool = $options['data_pool'] ?? 50 * 1024;
551 551
 
552 552
 	spip_log(
553
-		'Copier ' . count($tables) . " tables de '$serveur_source' vers '$serveur_dest'",
554
-		'dump.' . _LOG_INFO_IMPORTANTE
553
+		'Copier '.count($tables)." tables de '$serveur_source' vers '$serveur_dest'",
554
+		'dump.'._LOG_INFO_IMPORTANTE
555 555
 	);
556 556
 
557 557
 	if (!$inserer_copie = charger_fonction($fonction_base_inserer, $racine_fonctions, true)) {
558
-		spip_log("Fonction '{$racine_fonctions}_$fonction_base_inserer' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
558
+		spip_log("Fonction '{$racine_fonctions}_$fonction_base_inserer' inconnue. Abandon", 'dump.'._LOG_INFO_IMPORTANTE);
559 559
 
560 560
 		return true; // echec mais on a fini, donc true
561 561
 	}
562 562
 	if (!$preparer_table_dest = charger_fonction('preparer_table_dest', $racine_fonctions, true)) {
563
-		spip_log("Fonction '{$racine_fonctions}_$preparer_table_dest' inconnue. Abandon", 'dump.' . _LOG_INFO_IMPORTANTE);
563
+		spip_log("Fonction '{$racine_fonctions}_$preparer_table_dest' inconnue. Abandon", 'dump.'._LOG_INFO_IMPORTANTE);
564 564
 
565 565
 		return true; // echec mais on a fini, donc true
566 566
 	}
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
 		) {
589 589
 			spip_log(
590 590
 				"Fonction '{$racine_fonctions}_vider_tables_destination_copie' inconnue. Abandon",
591
-				'dump.' . _LOG_INFO_IMPORTANTE
591
+				'dump.'._LOG_INFO_IMPORTANTE
592 592
 			);
593 593
 
594 594
 			return true; // echec mais on a fini, donc true
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 		$tables = array_diff($tables, ['spip_meta']);
608 608
 		$tables[] = 'spip_meta';
609 609
 	}
610
-	spip_log('Tables a copier :' . implode(', ', $tables), 'dump.' . _LOG_INFO);
610
+	spip_log('Tables a copier :'.implode(', ', $tables), 'dump.'._LOG_INFO);
611 611
 
612 612
 	$trouver_table = charger_fonction('trouver_table', 'base');
613 613
 
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 						// mais si ca renvoie false c'est une erreur fatale => abandon
672 672
 						if ($inserer_copie($table, $rows, $desc_dest, $serveur_dest) === false) {
673 673
 							// forcer la sortie, charge a l'appelant de gerer l'echec
674
-							spip_log("Erreur fatale dans $inserer_copie table $table", 'dump' . _LOG_ERREUR);
674
+							spip_log("Erreur fatale dans $inserer_copie table $table", 'dump'._LOG_ERREUR);
675 675
 							$status['errors'][] = "Erreur fatale  lors de la copie de la table $table";
676 676
 							ecrire_fichier($status_file, serialize($status));
677 677
 
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 					if ($n == $status['tables_copiees'][$table]) {
687 687
 						break;
688 688
 					}
689
-					spip_log("recopie $table " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO_IMPORTANTE);
689
+					spip_log("recopie $table ".$status['tables_copiees'][$table], 'dump.'._LOG_INFO_IMPORTANTE);
690 690
 					if ($callback_progression) {
691 691
 						$callback_progression($status['tables_copiees'][$table], 0, $table);
692 692
 					}
@@ -697,30 +697,30 @@  discard block
 block discarded – undo
697 697
 				}
698 698
 				if ($drop_source) {
699 699
 					sql_drop_table($table, '', $serveur_source);
700
-					spip_log("drop $table sur serveur source '$serveur_source'", 'dump.' . _LOG_INFO_IMPORTANTE);
700
+					spip_log("drop $table sur serveur source '$serveur_source'", 'dump.'._LOG_INFO_IMPORTANTE);
701 701
 				}
702 702
 				$status['tables_copiees'][$table] = ($status['tables_copiees'][$table] ? -$status['tables_copiees'][$table] : 'zero');
703 703
 				ecrire_fichier($status_file, serialize($status));
704
-				spip_log('tables_recopiees ' . implode(',', array_keys($status['tables_copiees'])), 'dump.' . _LOG_INFO);
704
+				spip_log('tables_recopiees '.implode(',', array_keys($status['tables_copiees'])), 'dump.'._LOG_INFO);
705 705
 				if ($callback_progression) {
706 706
 					$callback_progression($status['tables_copiees'][$table], $status['tables_copiees'][$table], $table);
707 707
 				}
708 708
 			} else {
709 709
 				if ($status['tables_copiees'][$table] < 0) {
710
-					spip_log("Table $table deja copiee : " . $status['tables_copiees'][$table], 'dump.' . _LOG_INFO);
710
+					spip_log("Table $table deja copiee : ".$status['tables_copiees'][$table], 'dump.'._LOG_INFO);
711 711
 				}
712 712
 				if ($callback_progression) {
713 713
 					$callback_progression(
714 714
 						0,
715 715
 						$status['tables_copiees'][$table],
716
-						"$table" . ((is_numeric($status['tables_copiees'][$table]) and $status['tables_copiees'][$table] >= 0) ? '[Echec]' : '')
716
+						"$table".((is_numeric($status['tables_copiees'][$table]) and $status['tables_copiees'][$table] >= 0) ? '[Echec]' : '')
717 717
 					);
718 718
 				}
719 719
 			}
720 720
 		} else {
721 721
 			$status['errors'][] = "Impossible de lire la description de la table $table";
722 722
 			ecrire_fichier($status_file, serialize($status));
723
-			spip_log("Impossible de lire la description de la table $table", 'dump.' . _LOG_ERREUR);
723
+			spip_log("Impossible de lire la description de la table $table", 'dump.'._LOG_ERREUR);
724 724
 		}
725 725
 	}
726 726
 
@@ -728,17 +728,17 @@  discard block
 block discarded – undo
728 728
 	// abandonner
729 729
 	if (count($status['tables_copiees']) < count($tables)) {
730 730
 		spip_log(
731
-			'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables),
732
-			'dump.' . _LOG_ERREUR
731
+			'Nombre de tables copiees incorrect : '.count($status['tables_copiees']).'/'.count($tables),
732
+			'dump.'._LOG_ERREUR
733 733
 		);
734
-		$status['errors'][] = 'Nombre de tables copiees incorrect : ' . count($status['tables_copiees']) . '/' . count($tables);
734
+		$status['errors'][] = 'Nombre de tables copiees incorrect : '.count($status['tables_copiees']).'/'.count($tables);
735 735
 		ecrire_fichier($status_file, serialize($status));
736 736
 	}
737 737
 
738 738
 	if ($detruire_copieur_si_besoin = charger_fonction('detruire_copieur_si_besoin', $racine_fonctions, true)) {
739 739
 		$detruire_copieur_si_besoin($serveur_dest);
740 740
 	} else {
741
-		spip_log("Fonction '{$racine_fonctions}_detruire_copieur_si_besoin' inconnue.", 'dump.' . _LOG_INFO_IMPORTANTE);
741
+		spip_log("Fonction '{$racine_fonctions}_detruire_copieur_si_besoin' inconnue.", 'dump.'._LOG_INFO_IMPORTANTE);
742 742
 	}
743 743
 
744 744
 	// OK, copie complete
@@ -763,8 +763,8 @@  discard block
 block discarded – undo
763 763
 	$nb = sql_countsel($table, '', '', '', $serveur_dest);
764 764
 	if ($nb - $nb1 < count($rows)) {
765 765
 		spip_log(
766
-			'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . '. On retente 1 par 1',
767
-			'dump' . _LOG_INFO_IMPORTANTE
766
+			'base_inserer_copie : '.($nb - $nb1).' insertions au lieu de '.count($rows).'. On retente 1 par 1',
767
+			'dump'._LOG_INFO_IMPORTANTE
768 768
 		);
769 769
 		foreach ($rows as $row) {
770 770
 			// si l'enregistrement est deja en base, ca fera un echec ou un doublon
@@ -775,8 +775,8 @@  discard block
 block discarded – undo
775 775
 		$nb = sql_countsel($table, '', '', '', $serveur_dest);
776 776
 		if ($nb - $nb1 < count($rows)) {
777 777
 			spip_log(
778
-				'base_inserer_copie : ' . ($nb - $nb1) . ' insertions au lieu de ' . count($rows) . ' apres insertion 1 par 1',
779
-				'dump' . _LOG_ERREUR
778
+				'base_inserer_copie : '.($nb - $nb1).' insertions au lieu de '.count($rows).' apres insertion 1 par 1',
779
+				'dump'._LOG_ERREUR
780 780
 			);
781 781
 			$r = false;
782 782
 		}
Please login to merge, or discard this patch.
ecrire/balise/url_logout.php 1 patch
Indentation   +8 added lines, -8 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
 /**
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
  *     Pile complétée du code compilé
37 37
  **/
38 38
 function balise_URL_LOGOUT($p) {
39
-	return calculer_balise_dynamique($p, 'URL_LOGOUT', []);
39
+    return calculer_balise_dynamique($p, 'URL_LOGOUT', []);
40 40
 }
41 41
 
42 42
 
@@ -52,9 +52,9 @@  discard block
 block discarded – undo
52 52
  *   Liste (url) des arguments collectés.
53 53
  */
54 54
 function balise_URL_LOGOUT_stat($args, $context_compil) {
55
-	$url = $args[0] ?? '';
55
+    $url = $args[0] ?? '';
56 56
 
57
-	return [$url];
57
+    return [$url];
58 58
 }
59 59
 
60 60
 /**
@@ -69,9 +69,9 @@  discard block
 block discarded – undo
69 69
  **/
70 70
 function balise_URL_LOGOUT_dyn($cible) {
71 71
 
72
-	if (empty($GLOBALS['visiteur_session']['login']) and empty($GLOBALS['visiteur_session']['statut'])) {
73
-		return '';
74
-	}
72
+    if (empty($GLOBALS['visiteur_session']['login']) and empty($GLOBALS['visiteur_session']['statut'])) {
73
+        return '';
74
+    }
75 75
 
76
-	return generer_url_action('logout', 'logout=public&url=' . rawurlencode($cible ? $cible : self('&')));
76
+    return generer_url_action('logout', 'logout=public&url=' . rawurlencode($cible ? $cible : self('&')));
77 77
 }
Please login to merge, or discard this patch.
ecrire/balise/formulaire_.php 1 patch
Indentation   +266 added lines, -266 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Formulaires
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 include_spip('inc/filtres');
@@ -35,22 +35,22 @@  discard block
 block discarded – undo
35 35
  *     Saisie protégée
36 36
  **/
37 37
 function protege_champ($texte) {
38
-	if (is_array($texte)) {
39
-		return array_map('protege_champ', $texte);
40
-	} elseif ($texte === null) {
41
-		return $texte;
42
-	} elseif (is_bool($texte)) {
43
-		return $texte ? '1' : '';
44
-	} elseif (is_string($texte) and $texte) {
45
-		if (preg_match(',^[abis]:\d+[:;],', $texte) and @unserialize($texte) !== false) {
46
-			// ne pas corrompre une valeur serialize
47
-			return $texte;
48
-		} elseif (strpbrk($texte, "&\"'<>") !== false) {
49
-			return spip_htmlspecialchars($texte, ENT_QUOTES);
50
-		}
51
-	}
52
-
53
-	return $texte;
38
+    if (is_array($texte)) {
39
+        return array_map('protege_champ', $texte);
40
+    } elseif ($texte === null) {
41
+        return $texte;
42
+    } elseif (is_bool($texte)) {
43
+        return $texte ? '1' : '';
44
+    } elseif (is_string($texte) and $texte) {
45
+        if (preg_match(',^[abis]:\d+[:;],', $texte) and @unserialize($texte) !== false) {
46
+            // ne pas corrompre une valeur serialize
47
+            return $texte;
48
+        } elseif (strpbrk($texte, "&\"'<>") !== false) {
49
+            return spip_htmlspecialchars($texte, ENT_QUOTES);
50
+        }
51
+    }
52
+
53
+    return $texte;
54 54
 }
55 55
 
56 56
 /**
@@ -64,17 +64,17 @@  discard block
 block discarded – undo
64 64
  *     - false : pas de squelette trouvé
65 65
  **/
66 66
 function existe_formulaire($form) {
67
-	if (substr($form, 0, 11) == 'FORMULAIRE_') {
68
-		$form = strtolower(substr($form, 11));
69
-	} else {
70
-		$form = strtolower($form);
71
-	}
67
+    if (substr($form, 0, 11) == 'FORMULAIRE_') {
68
+        $form = strtolower(substr($form, 11));
69
+    } else {
70
+        $form = strtolower($form);
71
+    }
72 72
 
73
-	if (!$form) {
74
-		return '';
75
-	} // on ne sait pas, le nom du formulaire n'est pas fourni ici
73
+    if (!$form) {
74
+        return '';
75
+    } // on ne sait pas, le nom du formulaire n'est pas fourni ici
76 76
 
77
-	return trouver_fond($form, 'formulaires/') ? $form : false;
77
+    return trouver_fond($form, 'formulaires/') ? $form : false;
78 78
 }
79 79
 
80 80
 /**
@@ -83,31 +83,31 @@  discard block
 block discarded – undo
83 83
  * @return false|array
84 84
  */
85 85
 function test_formulaire_inclus_par_modele() {
86
-	$trace = debug_backtrace(null, 20);
87
-	$trace_fonctions = array_column($trace, 'function');
88
-	$trace_fonctions = array_map('strtolower', $trace_fonctions);
89
-
90
-	// regarder si un flag a ete leve juste avant l'appel de balise_FORMULAIRE_dyn
91
-	if (
92
-		function_exists('arguments_balise_dyn_depuis_modele')
93
-		and $form = arguments_balise_dyn_depuis_modele(null, 'read')
94
-	) {
95
-		if (in_array('balise_formulaire__dyn', $trace_fonctions)) {
96
-			$k = array_search('balise_formulaire__dyn', $trace_fonctions);
97
-			if ($trace[$k]['args'][0] === $form) {
98
-				return $trace[$k]['args'];
99
-			}
100
-		}
101
-	}
102
-
103
-	// fallback qui ne repose pas sur le flag lie a l'analyse de contexte_compil,
104
-	// mais ne marche pas si executer_balise_dynamique est appelee via du php dans le squelette
105
-	if (in_array('eval', $trace_fonctions) and in_array('inclure_modele', $trace_fonctions)) {
106
-		$k = array_search('inclure_modele', $trace_fonctions);
107
-		// les arguments de recuperer_fond() passes par inclure_modele()
108
-		return $trace[$k - 1]['args'][1]['args'];
109
-	}
110
-	return false;
86
+    $trace = debug_backtrace(null, 20);
87
+    $trace_fonctions = array_column($trace, 'function');
88
+    $trace_fonctions = array_map('strtolower', $trace_fonctions);
89
+
90
+    // regarder si un flag a ete leve juste avant l'appel de balise_FORMULAIRE_dyn
91
+    if (
92
+        function_exists('arguments_balise_dyn_depuis_modele')
93
+        and $form = arguments_balise_dyn_depuis_modele(null, 'read')
94
+    ) {
95
+        if (in_array('balise_formulaire__dyn', $trace_fonctions)) {
96
+            $k = array_search('balise_formulaire__dyn', $trace_fonctions);
97
+            if ($trace[$k]['args'][0] === $form) {
98
+                return $trace[$k]['args'];
99
+            }
100
+        }
101
+    }
102
+
103
+    // fallback qui ne repose pas sur le flag lie a l'analyse de contexte_compil,
104
+    // mais ne marche pas si executer_balise_dynamique est appelee via du php dans le squelette
105
+    if (in_array('eval', $trace_fonctions) and in_array('inclure_modele', $trace_fonctions)) {
106
+        $k = array_search('inclure_modele', $trace_fonctions);
107
+        // les arguments de recuperer_fond() passes par inclure_modele()
108
+        return $trace[$k - 1]['args'][1]['args'];
109
+    }
110
+    return false;
111 111
 }
112 112
 
113 113
 /**
@@ -122,32 +122,32 @@  discard block
 block discarded – undo
122 122
  **/
123 123
 function balise_FORMULAIRE__dist($p) {
124 124
 
125
-	// Cas d'un #FORMULAIRE_TOTO inexistant : renvoyer la chaine vide.
126
-	// mais si #FORMULAIRE_{toto} on ne peut pas savoir a la compilation, continuer
127
-	if (existe_formulaire($p->nom_champ) === false) {
128
-		$p->code = "''";
129
-		$p->interdire_scripts = false;
130
-
131
-		return $p;
132
-	}
133
-
134
-	// sinon renvoyer un code php dynamique
135
-	$p = calculer_balise_dynamique($p, $p->nom_champ, []);
136
-
137
-	if (
138
-		!test_espace_prive()
139
-		and !empty($p->descr['sourcefile'])
140
-		and $f = $p->descr['sourcefile']
141
-		and basename(dirname($f)) === 'modeles'
142
-	) {
143
-		// un modele est toujours inséré en texte dans son contenant
144
-		// donc si on est dans le public avec un cache on va perdre le dynamisme
145
-		// et on risque de mettre en cache les valeurs pre-remplies du formulaire
146
-		// on injecte donc le PHP qui va appeler la fonction pour generer le formulaire au lieu de directement la fonction
147
-		$p->code = "'<'.'?php echo (" . texte_script($p->code) . "); ?'.'>'";
148
-		// dans l'espace prive on a pas de cache, donc pas de soucis (et un leak serait moins grave)
149
-	}
150
-	return $p;
125
+    // Cas d'un #FORMULAIRE_TOTO inexistant : renvoyer la chaine vide.
126
+    // mais si #FORMULAIRE_{toto} on ne peut pas savoir a la compilation, continuer
127
+    if (existe_formulaire($p->nom_champ) === false) {
128
+        $p->code = "''";
129
+        $p->interdire_scripts = false;
130
+
131
+        return $p;
132
+    }
133
+
134
+    // sinon renvoyer un code php dynamique
135
+    $p = calculer_balise_dynamique($p, $p->nom_champ, []);
136
+
137
+    if (
138
+        !test_espace_prive()
139
+        and !empty($p->descr['sourcefile'])
140
+        and $f = $p->descr['sourcefile']
141
+        and basename(dirname($f)) === 'modeles'
142
+    ) {
143
+        // un modele est toujours inséré en texte dans son contenant
144
+        // donc si on est dans le public avec un cache on va perdre le dynamisme
145
+        // et on risque de mettre en cache les valeurs pre-remplies du formulaire
146
+        // on injecte donc le PHP qui va appeler la fonction pour generer le formulaire au lieu de directement la fonction
147
+        $p->code = "'<'.'?php echo (" . texte_script($p->code) . "); ?'.'>'";
148
+        // dans l'espace prive on a pas de cache, donc pas de soucis (et un leak serait moins grave)
149
+    }
150
+    return $p;
151 151
 }
152 152
 
153 153
 /**
@@ -167,17 +167,17 @@  discard block
 block discarded – undo
167 167
  *     - string : texte à afficher directement
168 168
  */
169 169
 function balise_FORMULAIRE__dyn($form, ...$args) {
170
-	$form = existe_formulaire($form);
171
-	if (!$form) {
172
-		return '';
173
-	}
170
+    $form = existe_formulaire($form);
171
+    if (!$form) {
172
+        return '';
173
+    }
174 174
 
175
-	$contexte = balise_FORMULAIRE__contexte($form, $args);
176
-	if (!is_array($contexte)) {
177
-		return $contexte;
178
-	}
175
+    $contexte = balise_FORMULAIRE__contexte($form, $args);
176
+    if (!is_array($contexte)) {
177
+        return $contexte;
178
+    }
179 179
 
180
-	return ["formulaires/$form", 3600, $contexte];
180
+    return ["formulaires/$form", 3600, $contexte];
181 181
 }
182 182
 
183 183
 /**
@@ -191,84 +191,84 @@  discard block
 block discarded – undo
191 191
  *     Contexte d'environnement à envoyer au squelette
192 192
  **/
193 193
 function balise_FORMULAIRE__contexte($form, $args) {
194
-	// tester si ce formulaire vient d'etre poste (memes arguments)
195
-	// pour ne pas confondre 2 #FORMULAIRES_XX identiques sur une meme page
196
-	// si poste, on recupere les erreurs
197
-
198
-	$je_suis_poste = false;
199
-	if (
200
-		$post_form = _request('formulaire_action')
201
-		and $post_form == $form
202
-		and $p = _request('formulaire_action_args')
203
-		and is_array($p = decoder_contexte_ajax($p, $post_form))
204
-	) {
205
-		// enlever le faux attribut de langue masque
206
-		array_shift($p);
207
-		if (formulaire__identifier($form, $args, $p)) {
208
-			$je_suis_poste = true;
209
-		}
210
-	}
211
-
212
-	$editable = true;
213
-	$erreurs = $post = [];
214
-	if ($je_suis_poste) {
215
-		$post = traiter_formulaires_dynamiques(true);
216
-		$e = "erreurs_$form";
217
-		$erreurs = $post[$e] ?? [];
218
-		$editable = "editable_$form";
219
-		$editable = (!isset($post[$e]))
220
-			|| count($erreurs)
221
-			|| (isset($post[$editable]) && $post[$editable]);
222
-	}
223
-
224
-	$valeurs = formulaire__charger($form, $args, $je_suis_poste);
225
-
226
-	// si $valeurs n'est pas un tableau, le formulaire n'est pas applicable
227
-	// C'est plus fort qu'editable qui est gere par le squelette
228
-	// Idealement $valeur doit etre alors un message explicatif.
229
-	if (!is_array($valeurs)) {
230
-		return is_string($valeurs) ? $valeurs : '';
231
-	}
232
-
233
-	// charger peut passer une action si le formulaire ne tourne pas sur self()
234
-	// ou une action vide si elle ne sert pas
235
-	$action = (isset($valeurs['action'])) ? $valeurs['action'] : self('&amp;', true);
236
-	// bug IEx : si action finit par /
237
-	// IE croit que le <form ... action=../ > est autoferme
238
-	if (substr($action, -1) == '/') {
239
-		// on ajoute une ancre pour feinter IE, au pire ca tue l'ancre qui finit par un /
240
-		$action .= '#';
241
-	}
242
-
243
-	// recuperer la saisie en cours si erreurs
244
-	// seulement si c'est ce formulaire qui est poste
245
-	// ou si on le demande explicitement par le parametre _forcer_request = true
246
-	$dispo = ($je_suis_poste || (isset($valeurs['_forcer_request']) && $valeurs['_forcer_request']));
247
-	foreach (array_keys($valeurs) as $champ) {
248
-		if ($champ[0] !== '_' and !in_array($champ, ['message_ok', 'message_erreur', 'editable'])) {
249
-			if ($dispo and (($v = _request($champ)) !== null)) {
250
-				$valeurs[$champ] = $v;
251
-			}
252
-			// nettoyer l'url des champs qui vont etre saisis
253
-			if ($action) {
254
-				$action = parametre_url($action, $champ, '');
255
-			}
256
-			// proteger les ' et les " dans les champs que l'on va injecter
257
-			$valeurs[$champ] = protege_champ($valeurs[$champ]);
258
-		}
259
-	}
260
-
261
-	if ($action) {
262
-		// nettoyer l'url
263
-		$action = parametre_url($action, 'formulaire_action', '');
264
-		$action = parametre_url($action, 'formulaire_action_args', '');
265
-	}
266
-
267
-	/**
268
-	 * @deprecated
269
-	 * servait pour poster sur les actions de type editer_xxx() qui ne prenaient pas d'argument autrement que par _request('arg') et pour lesquelles il fallait donc passer un hash valide
270
-	 */
271
-	/*
194
+    // tester si ce formulaire vient d'etre poste (memes arguments)
195
+    // pour ne pas confondre 2 #FORMULAIRES_XX identiques sur une meme page
196
+    // si poste, on recupere les erreurs
197
+
198
+    $je_suis_poste = false;
199
+    if (
200
+        $post_form = _request('formulaire_action')
201
+        and $post_form == $form
202
+        and $p = _request('formulaire_action_args')
203
+        and is_array($p = decoder_contexte_ajax($p, $post_form))
204
+    ) {
205
+        // enlever le faux attribut de langue masque
206
+        array_shift($p);
207
+        if (formulaire__identifier($form, $args, $p)) {
208
+            $je_suis_poste = true;
209
+        }
210
+    }
211
+
212
+    $editable = true;
213
+    $erreurs = $post = [];
214
+    if ($je_suis_poste) {
215
+        $post = traiter_formulaires_dynamiques(true);
216
+        $e = "erreurs_$form";
217
+        $erreurs = $post[$e] ?? [];
218
+        $editable = "editable_$form";
219
+        $editable = (!isset($post[$e]))
220
+            || count($erreurs)
221
+            || (isset($post[$editable]) && $post[$editable]);
222
+    }
223
+
224
+    $valeurs = formulaire__charger($form, $args, $je_suis_poste);
225
+
226
+    // si $valeurs n'est pas un tableau, le formulaire n'est pas applicable
227
+    // C'est plus fort qu'editable qui est gere par le squelette
228
+    // Idealement $valeur doit etre alors un message explicatif.
229
+    if (!is_array($valeurs)) {
230
+        return is_string($valeurs) ? $valeurs : '';
231
+    }
232
+
233
+    // charger peut passer une action si le formulaire ne tourne pas sur self()
234
+    // ou une action vide si elle ne sert pas
235
+    $action = (isset($valeurs['action'])) ? $valeurs['action'] : self('&amp;', true);
236
+    // bug IEx : si action finit par /
237
+    // IE croit que le <form ... action=../ > est autoferme
238
+    if (substr($action, -1) == '/') {
239
+        // on ajoute une ancre pour feinter IE, au pire ca tue l'ancre qui finit par un /
240
+        $action .= '#';
241
+    }
242
+
243
+    // recuperer la saisie en cours si erreurs
244
+    // seulement si c'est ce formulaire qui est poste
245
+    // ou si on le demande explicitement par le parametre _forcer_request = true
246
+    $dispo = ($je_suis_poste || (isset($valeurs['_forcer_request']) && $valeurs['_forcer_request']));
247
+    foreach (array_keys($valeurs) as $champ) {
248
+        if ($champ[0] !== '_' and !in_array($champ, ['message_ok', 'message_erreur', 'editable'])) {
249
+            if ($dispo and (($v = _request($champ)) !== null)) {
250
+                $valeurs[$champ] = $v;
251
+            }
252
+            // nettoyer l'url des champs qui vont etre saisis
253
+            if ($action) {
254
+                $action = parametre_url($action, $champ, '');
255
+            }
256
+            // proteger les ' et les " dans les champs que l'on va injecter
257
+            $valeurs[$champ] = protege_champ($valeurs[$champ]);
258
+        }
259
+    }
260
+
261
+    if ($action) {
262
+        // nettoyer l'url
263
+        $action = parametre_url($action, 'formulaire_action', '');
264
+        $action = parametre_url($action, 'formulaire_action_args', '');
265
+    }
266
+
267
+    /**
268
+     * @deprecated
269
+     * servait pour poster sur les actions de type editer_xxx() qui ne prenaient pas d'argument autrement que par _request('arg') et pour lesquelles il fallait donc passer un hash valide
270
+     */
271
+    /*
272 272
 	if (isset($valeurs['_action'])) {
273 273
 		$securiser_action = charger_fonction('securiser_action', 'inc');
274 274
 		$secu = $securiser_action(reset($valeurs['_action']), end($valeurs['_action']), '', -1);
@@ -278,59 +278,59 @@  discard block
 block discarded – undo
278 278
 	}
279 279
 	*/
280 280
 
281
-	// empiler la lang en tant que premier argument implicite du CVT
282
-	// pour permettre de la restaurer au moment du Verifier et du Traiter
283
-	array_unshift($args, $GLOBALS['spip_lang']);
284
-
285
-	$valeurs['formulaire_args'] = encoder_contexte_ajax($args, $form);
286
-	$valeurs['erreurs'] = $erreurs;
287
-	$valeurs['action'] = $action;
288
-	$valeurs['form'] = $form;
289
-
290
-	$valeurs['formulaire_sign'] = '';
291
-	if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
292
-		$securiser_action = charger_fonction('securiser_action', 'inc');
293
-		$secu = $securiser_action($valeurs['form'], $valeurs['formulaire_args'], '', -1);
294
-		$valeurs['formulaire_sign'] = $secu['hash'];
295
-	}
296
-
297
-	if (!isset($valeurs['id'])) {
298
-		$valeurs['id'] = 'new';
299
-	}
300
-	// editable peut venir de charger() ou de traiter() sinon
301
-	if (!isset($valeurs['editable'])) {
302
-		$valeurs['editable'] = $editable;
303
-	}
304
-	// dans tous les cas, renvoyer un espace ou vide (et pas un booleen)
305
-	$valeurs['editable'] = ($valeurs['editable'] ? ' ' : '');
306
-
307
-	if ($je_suis_poste) {
308
-		$valeurs['message_erreur'] = '';
309
-		if (isset($erreurs['message_erreur'])) {
310
-			$valeurs['message_erreur'] = $erreurs['message_erreur'];
311
-		}
312
-
313
-		$valeurs['message_ok'] = '';
314
-		if (isset($post["message_ok_$form"])) {
315
-			$valeurs['message_ok'] = $post["message_ok_$form"];
316
-		} elseif (isset($erreurs['message_ok'])) {
317
-			$valeurs['message_ok'] = $erreurs['message_ok'];
318
-		}
319
-
320
-		// accessibilite : encapsuler toutes les erreurs dans un role='alert'
321
-		// uniquement si c'est une string et au premier niveau (on ne touche pas au tableaux)
322
-		// et si $k ne commence pas par un _ (c'est bien une vrai erreur sur un vrai champ)
323
-		if (html5_permis()) {
324
-			foreach ($erreurs as $k => $v) {
325
-				if (is_string($v) and strlen(trim($v)) and strpos($k, '_') !== 0) {
326
-					// on encapsule dans un span car ces messages sont en general simple, juste du texte, et deja dans un span dans le form
327
-					$valeurs['erreurs'][$k] = "<span role='alert'>" . $erreurs[$k] . '</span>';
328
-				}
329
-			}
330
-		}
331
-	}
332
-
333
-	return $valeurs;
281
+    // empiler la lang en tant que premier argument implicite du CVT
282
+    // pour permettre de la restaurer au moment du Verifier et du Traiter
283
+    array_unshift($args, $GLOBALS['spip_lang']);
284
+
285
+    $valeurs['formulaire_args'] = encoder_contexte_ajax($args, $form);
286
+    $valeurs['erreurs'] = $erreurs;
287
+    $valeurs['action'] = $action;
288
+    $valeurs['form'] = $form;
289
+
290
+    $valeurs['formulaire_sign'] = '';
291
+    if (!empty($GLOBALS['visiteur_session']['id_auteur'])) {
292
+        $securiser_action = charger_fonction('securiser_action', 'inc');
293
+        $secu = $securiser_action($valeurs['form'], $valeurs['formulaire_args'], '', -1);
294
+        $valeurs['formulaire_sign'] = $secu['hash'];
295
+    }
296
+
297
+    if (!isset($valeurs['id'])) {
298
+        $valeurs['id'] = 'new';
299
+    }
300
+    // editable peut venir de charger() ou de traiter() sinon
301
+    if (!isset($valeurs['editable'])) {
302
+        $valeurs['editable'] = $editable;
303
+    }
304
+    // dans tous les cas, renvoyer un espace ou vide (et pas un booleen)
305
+    $valeurs['editable'] = ($valeurs['editable'] ? ' ' : '');
306
+
307
+    if ($je_suis_poste) {
308
+        $valeurs['message_erreur'] = '';
309
+        if (isset($erreurs['message_erreur'])) {
310
+            $valeurs['message_erreur'] = $erreurs['message_erreur'];
311
+        }
312
+
313
+        $valeurs['message_ok'] = '';
314
+        if (isset($post["message_ok_$form"])) {
315
+            $valeurs['message_ok'] = $post["message_ok_$form"];
316
+        } elseif (isset($erreurs['message_ok'])) {
317
+            $valeurs['message_ok'] = $erreurs['message_ok'];
318
+        }
319
+
320
+        // accessibilite : encapsuler toutes les erreurs dans un role='alert'
321
+        // uniquement si c'est une string et au premier niveau (on ne touche pas au tableaux)
322
+        // et si $k ne commence pas par un _ (c'est bien une vrai erreur sur un vrai champ)
323
+        if (html5_permis()) {
324
+            foreach ($erreurs as $k => $v) {
325
+                if (is_string($v) and strlen(trim($v)) and strpos($k, '_') !== 0) {
326
+                    // on encapsule dans un span car ces messages sont en general simple, juste du texte, et deja dans un span dans le form
327
+                    $valeurs['erreurs'][$k] = "<span role='alert'>" . $erreurs[$k] . '</span>';
328
+                }
329
+            }
330
+        }
331
+    }
332
+
333
+    return $valeurs;
334 334
 }
335 335
 
336 336
 /**
@@ -342,51 +342,51 @@  discard block
 block discarded – undo
342 342
  * @return array
343 343
  */
344 344
 function formulaire__charger($form, $args, $poste) {
345
-	if ($charger_valeurs = charger_fonction('charger', "formulaires/$form", true)) {
346
-		$valeurs = call_user_func_array($charger_valeurs, $args);
347
-	} else {
348
-		$valeurs = [];
349
-	}
350
-
351
-	$valeurs = pipeline(
352
-		'formulaire_charger',
353
-		[
354
-			'args' => ['form' => $form, 'args' => $args, 'je_suis_poste' => $poste],
355
-			'data' => $valeurs
356
-		]
357
-	);
358
-
359
-	// prise en charge CVT multi etape
360
-	if (is_array($valeurs) and isset($valeurs['_etapes'])) {
361
-		include_spip('inc/cvt_multietapes');
362
-		$valeurs = cvtmulti_formulaire_charger_etapes(
363
-			['form' => $form, 'args' => $args, 'je_suis_poste' => $poste],
364
-			$valeurs
365
-		);
366
-	}
367
-
368
-	// si $valeurs et false ou une chaine, pas de formulaire, donc pas de pipeline !
369
-	if (is_array($valeurs)) {
370
-		if (!isset($valeurs['_pipelines'])) {
371
-			$valeurs['_pipelines'] = [];
372
-		}
373
-		// l'ancien argument _pipeline devient maintenant _pipelines
374
-		// reinjectons le vieux _pipeline au debut de _pipelines
375
-		if (isset($valeurs['_pipeline'])) {
376
-			$pipe = is_array($valeurs['_pipeline']) ? reset($valeurs['_pipeline']) : $valeurs['_pipeline'];
377
-			$args = is_array($valeurs['_pipeline']) ? end($valeurs['_pipeline']) : [];
378
-
379
-			$pipelines = [$pipe => $args];
380
-			$valeurs['_pipelines'] = array_merge($pipelines, $valeurs['_pipelines']);
381
-		}
382
-
383
-		// et enfin, ajoutons systematiquement un pipeline sur le squelette du formulaire
384
-		// qui constitue le cas le plus courant d'utilisation du pipeline recuperer_fond
385
-		// (performance, cela evite de s'injecter dans recuperer_fond utilise pour *tous* les squelettes)
386
-		$valeurs['_pipelines']['formulaire_fond'] = ['form' => $form, 'args' => $args, 'je_suis_poste' => $poste];
387
-	}
388
-
389
-	return $valeurs;
345
+    if ($charger_valeurs = charger_fonction('charger', "formulaires/$form", true)) {
346
+        $valeurs = call_user_func_array($charger_valeurs, $args);
347
+    } else {
348
+        $valeurs = [];
349
+    }
350
+
351
+    $valeurs = pipeline(
352
+        'formulaire_charger',
353
+        [
354
+            'args' => ['form' => $form, 'args' => $args, 'je_suis_poste' => $poste],
355
+            'data' => $valeurs
356
+        ]
357
+    );
358
+
359
+    // prise en charge CVT multi etape
360
+    if (is_array($valeurs) and isset($valeurs['_etapes'])) {
361
+        include_spip('inc/cvt_multietapes');
362
+        $valeurs = cvtmulti_formulaire_charger_etapes(
363
+            ['form' => $form, 'args' => $args, 'je_suis_poste' => $poste],
364
+            $valeurs
365
+        );
366
+    }
367
+
368
+    // si $valeurs et false ou une chaine, pas de formulaire, donc pas de pipeline !
369
+    if (is_array($valeurs)) {
370
+        if (!isset($valeurs['_pipelines'])) {
371
+            $valeurs['_pipelines'] = [];
372
+        }
373
+        // l'ancien argument _pipeline devient maintenant _pipelines
374
+        // reinjectons le vieux _pipeline au debut de _pipelines
375
+        if (isset($valeurs['_pipeline'])) {
376
+            $pipe = is_array($valeurs['_pipeline']) ? reset($valeurs['_pipeline']) : $valeurs['_pipeline'];
377
+            $args = is_array($valeurs['_pipeline']) ? end($valeurs['_pipeline']) : [];
378
+
379
+            $pipelines = [$pipe => $args];
380
+            $valeurs['_pipelines'] = array_merge($pipelines, $valeurs['_pipelines']);
381
+        }
382
+
383
+        // et enfin, ajoutons systematiquement un pipeline sur le squelette du formulaire
384
+        // qui constitue le cas le plus courant d'utilisation du pipeline recuperer_fond
385
+        // (performance, cela evite de s'injecter dans recuperer_fond utilise pour *tous* les squelettes)
386
+        $valeurs['_pipelines']['formulaire_fond'] = ['form' => $form, 'args' => $args, 'je_suis_poste' => $poste];
387
+    }
388
+
389
+    return $valeurs;
390 390
 }
391 391
 
392 392
 /**
@@ -405,9 +405,9 @@  discard block
 block discarded – undo
405 405
  * @return bool
406 406
  */
407 407
 function formulaire__identifier($form, $args, $p) {
408
-	if ($identifier_args = charger_fonction('identifier', "formulaires/$form", true)) {
409
-		return call_user_func_array($identifier_args, $args) === call_user_func_array($identifier_args, $p);
410
-	}
408
+    if ($identifier_args = charger_fonction('identifier', "formulaires/$form", true)) {
409
+        return call_user_func_array($identifier_args, $args) === call_user_func_array($identifier_args, $p);
410
+    }
411 411
 
412
-	return $args === $p;
412
+    return $args === $p;
413 413
 }
Please login to merge, or discard this patch.
ecrire/balise/formulaire_inscription.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 include_spip('base/abstract_sql');
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
  *     Pile complétée du code compilé
44 44
  **/
45 45
 function balise_FORMULAIRE_INSCRIPTION($p) {
46
-	return calculer_balise_dynamique($p, 'FORMULAIRE_INSCRIPTION', []);
46
+    return calculer_balise_dynamique($p, 'FORMULAIRE_INSCRIPTION', []);
47 47
 }
48 48
 
49 49
 /**
@@ -72,9 +72,9 @@  discard block
 block discarded – undo
72 72
  *   - chaîne vide sinon.
73 73
  */
74 74
 function balise_FORMULAIRE_INSCRIPTION_stat($args, $context_compil) {
75
-	list($mode, $id, $retour) = array_pad($args, 3, null);
76
-	include_spip('action/inscrire_auteur');
77
-	$mode = tester_statut_inscription($mode, $id ?? 0);
75
+    list($mode, $id, $retour) = array_pad($args, 3, null);
76
+    include_spip('action/inscrire_auteur');
77
+    $mode = tester_statut_inscription($mode, $id ?? 0);
78 78
 
79
-	return $mode ? [$mode, $id, $retour] : '';
79
+    return $mode ? [$mode, $id, $retour] : '';
80 80
 }
Please login to merge, or discard this patch.
ecrire/index.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -19,14 +19,14 @@  discard block
 block discarded – undo
19 19
 /** Drapeau indiquant que l'on est dans l'espace privé */
20 20
 define('_ESPACE_PRIVE', true);
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	include 'inc_version.php';
22
+    include 'inc_version.php';
23 23
 }
24 24
 
25 25
 // Verification anti magic_quotes_sybase, pour qui addslashes("'") = "''"
26 26
 // On prefere la faire ici plutot que dans inc_version, c'est moins souvent et
27 27
 // si le reglage est modifie sur un site en prod, ca fait moins mal
28 28
 if (addslashes("'") !== "\\'") {
29
-	die('SPIP incompatible magic_quotes_sybase');
29
+    die('SPIP incompatible magic_quotes_sybase');
30 30
 }
31 31
 
32 32
 include_spip('inc/cookie');
@@ -42,18 +42,18 @@  discard block
 block discarded – undo
42 42
 // alors il faut blinder les variables d'URL
43 43
 //
44 44
 if (autoriser_sans_cookie($exec, false)) {
45
-	if (!isset($reinstall)) {
46
-		$reinstall = 'non';
47
-	}
48
-	$var_auth = true;
45
+    if (!isset($reinstall)) {
46
+        $reinstall = 'non';
47
+    }
48
+    $var_auth = true;
49 49
 } else {
50
-	// Authentification, redefinissable
51
-	$auth = charger_fonction('auth', 'inc');
52
-	$var_auth = $auth();
53
-	if ($var_auth) {
54
-		echo auth_echec($var_auth);
55
-		exit;
56
-	}
50
+    // Authentification, redefinissable
51
+    $auth = charger_fonction('auth', 'inc');
52
+    $var_auth = $auth();
53
+    if ($var_auth) {
54
+        echo auth_echec($var_auth);
55
+        exit;
56
+    }
57 57
 }
58 58
 
59 59
 // initialiser a la langue par defaut
@@ -64,29 +64,29 @@  discard block
 block discarded – undo
64 64
 
65 65
 
66 66
 if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
67
-	if (!autoriser_sans_cookie($exec)) {
68
-		// Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
69
-		include_spip('public/aiguiller');
70
-		if (
71
-			// cas des appels actions ?action=xxx
72
-			traiter_appels_actions()
73
-			or
74
-			// cas des hits ajax sur les inclusions ajax
75
-			traiter_appels_inclusions_ajax()
76
-			or
77
-			// cas des formulaires charger/verifier/traiter
78
-			traiter_formulaires_dynamiques()
79
-		) {
80
-			exit;
81
-		} // le hit est fini !
82
-	}
67
+    if (!autoriser_sans_cookie($exec)) {
68
+        // Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
69
+        include_spip('public/aiguiller');
70
+        if (
71
+            // cas des appels actions ?action=xxx
72
+            traiter_appels_actions()
73
+            or
74
+            // cas des hits ajax sur les inclusions ajax
75
+            traiter_appels_inclusions_ajax()
76
+            or
77
+            // cas des formulaires charger/verifier/traiter
78
+            traiter_formulaires_dynamiques()
79
+        ) {
80
+            exit;
81
+        } // le hit est fini !
82
+    }
83 83
 }
84 84
 // securiser les redirect du back-office
85 85
 if (_request('redirect')) {
86
-	if (!function_exists('securiser_redirect_action')) {
87
-		include_spip('public/aiguiller');
88
-	}
89
-	set_request('redirect', securiser_redirect_action(_request('redirect')));
86
+    if (!function_exists('securiser_redirect_action')) {
87
+        include_spip('public/aiguiller');
88
+    }
89
+    set_request('redirect', securiser_redirect_action(_request('redirect')));
90 90
 }
91 91
 
92 92
 
@@ -96,12 +96,12 @@  discard block
 block discarded – undo
96 96
 
97 97
 // Controle de la version, sauf si on est deja en train de s'en occuper
98 98
 if (
99
-	!$reinstall == 'oui'
100
-	and !_AJAX
101
-	and isset($GLOBALS['meta']['version_installee'])
102
-	and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
99
+    !$reinstall == 'oui'
100
+    and !_AJAX
101
+    and isset($GLOBALS['meta']['version_installee'])
102
+    and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
103 103
 ) {
104
-	$exec = 'demande_mise_a_jour';
104
+    $exec = 'demande_mise_a_jour';
105 105
 }
106 106
 
107 107
 // Quand une action d'administration est en cours (meta "admin"),
@@ -111,39 +111,39 @@  discard block
 block discarded – undo
111 111
 // sinon c'est qu'elle a ete interrompue et il faut la reprendre
112 112
 
113 113
 elseif (isset($GLOBALS['meta']['admin'])) {
114
-	if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
115
-		list(, $var_f, $n) = $l;
116
-	}
117
-	if (
118
-		_AJAX
119
-		or !(
120
-			isset($_COOKIE['spip_admin'])
121
-			or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
122
-		)
123
-	) {
124
-		spip_log('Quand la meta admin vaut ' .
125
-			$GLOBALS['meta']['admin'] .
126
-			' seul un admin peut se connecter et sans AJAX.' .
127
-			' En cas de probleme, detruire cette meta.');
128
-		die(_T('info_travaux_texte'));
129
-	}
130
-	if ($n) {
131
-		list(, $var_f, $n) = $l;
132
-		if (tester_url_ecrire("base_$var_f")) {
133
-			$var_f = "base_$var_f";
134
-		}
135
-		if ($var_f != $exec) {
136
-			spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
137
-			$exec = $var_f;
138
-			set_request('exec', $exec);
139
-		}
140
-	}
114
+    if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
115
+        list(, $var_f, $n) = $l;
116
+    }
117
+    if (
118
+        _AJAX
119
+        or !(
120
+            isset($_COOKIE['spip_admin'])
121
+            or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
122
+        )
123
+    ) {
124
+        spip_log('Quand la meta admin vaut ' .
125
+            $GLOBALS['meta']['admin'] .
126
+            ' seul un admin peut se connecter et sans AJAX.' .
127
+            ' En cas de probleme, detruire cette meta.');
128
+        die(_T('info_travaux_texte'));
129
+    }
130
+    if ($n) {
131
+        list(, $var_f, $n) = $l;
132
+        if (tester_url_ecrire("base_$var_f")) {
133
+            $var_f = "base_$var_f";
134
+        }
135
+        if ($var_f != $exec) {
136
+            spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
137
+            $exec = $var_f;
138
+            set_request('exec', $exec);
139
+        }
140
+    }
141 141
 }
142 142
 // si nom pas plausible, prendre le script par defaut
143 143
 // attention aux deux cas 404/403 qui commencent par un 4 !
144 144
 elseif (!preg_match(',^[a-z4_][0-9a-z_-]*$,i', $exec)) {
145
-	$exec = 'accueil';
146
-	set_request('exec', $exec);
145
+    $exec = 'accueil';
146
+    set_request('exec', $exec);
147 147
 }
148 148
 
149 149
 // compatibilite ascendante : obsolete, ne plus utiliser
@@ -155,19 +155,19 @@  discard block
 block discarded – undo
155 155
 // on appelle directement la fonction, car un appel d'action peut conduire a une boucle infinie
156 156
 // si le cookie n'est pas pose correctement dans l'action
157 157
 if (
158
-	!$var_auth and isset($_COOKIE['spip_lang_ecrire'])
159
-	and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
158
+    !$var_auth and isset($_COOKIE['spip_lang_ecrire'])
159
+    and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
160 160
 ) {
161
-	include_spip('action/converser');
162
-	action_converser_post($GLOBALS['visiteur_session']['lang'], true);
161
+    include_spip('action/converser');
162
+    action_converser_post($GLOBALS['visiteur_session']['lang'], true);
163 163
 }
164 164
 
165 165
 if ($var_f = tester_url_ecrire($exec)) {
166
-	$var_f = charger_fonction($var_f);
167
-	$var_f(); // at last
166
+    $var_f = charger_fonction($var_f);
167
+    $var_f(); // at last
168 168
 } else {
169
-	// Rien de connu: rerouter vers exec=404 au lieu d'echouer
170
-	// ce qui permet de laisser la main a un plugin
171
-	$var_f = charger_fonction('404');
172
-	$var_f($exec);
169
+    // Rien de connu: rerouter vers exec=404 au lieu d'echouer
170
+    // ce qui permet de laisser la main a un plugin
171
+    $var_f = charger_fonction('404');
172
+    $var_f($exec);
173 173
 }
Please login to merge, or discard this patch.
ecrire/public.php 2 patches
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -21,193 +21,193 @@
 block discarded – undo
21 21
 // par souci de compatiilite).
22 22
 
23 23
 if (isset($GLOBALS['_INC_PUBLIC']) and $GLOBALS['_INC_PUBLIC']) {
24
-	echo recuperer_fond($fond, $contexte_inclus, [], _request('connect') ?? '');
24
+    echo recuperer_fond($fond, $contexte_inclus, [], _request('connect') ?? '');
25 25
 } else {
26
-	$GLOBALS['_INC_PUBLIC'] = 1;
27
-	define('_PIPELINE_SUFFIX', test_espace_prive() ? '_prive' : '');
28
-
29
-	// Faut-il initialiser SPIP ? (oui dans le cas general)
30
-	if (!defined('_DIR_RESTREINT_ABS')) {
31
-		if (
32
-			defined('_DIR_RESTREINT')
33
-			and @file_exists(_ROOT_RESTREINT . 'inc_version.php')
34
-		) {
35
-			include_once _ROOT_RESTREINT . 'inc_version.php';
36
-		} else {
37
-			die('inc_version absent ?');
38
-		}
39
-	} // $fond defini dans le fichier d'appel ?
40
-
41
-	else {
42
-		if (isset($fond) and !_request('fond')) {
43
-		} // fond demande dans l'url par page=xxxx ?
44
-		else {
45
-			if (isset($_GET[_SPIP_PAGE])) {
46
-				$fond = (string)$_GET[_SPIP_PAGE];
47
-
48
-				// Securite
49
-				if (
50
-					strstr($fond, '/')
51
-					and !(
52
-						isset($GLOBALS['visiteur_session']) // pour eviter d'evaluer la suite pour les anonymes
53
-						and include_spip('inc/autoriser')
54
-						and autoriser('webmestre'))
55
-				) {
56
-					include_spip('inc/minipres');
57
-					echo minipres();
58
-					exit;
59
-				}
60
-				// l'argument Page a priorite sur l'argument action
61
-				// le cas se presente a cause des RewriteRule d'Apache
62
-				// qui permettent d'ajouter un argument dans la QueryString
63
-				// mais pas d'en retirer un en conservant les autres.
64
-				if (isset($_GET['action']) and $_GET['action'] === $fond) {
65
-					unset($_GET['action']);
66
-				}
67
-				# sinon, fond par defaut
68
-			} else {
69
-				// sinon fond par defaut (cf. assembler.php)
70
-				$fond = pipeline('detecter_fond_par_defaut', '');
71
-			}
72
-		}
73
-	}
74
-
75
-	$tableau_des_temps = [];
76
-
77
-	// Particularites de certains squelettes
78
-	if ($fond == 'login') {
79
-		$forcer_lang = true;
80
-	}
81
-
82
-	if (
83
-		isset($forcer_lang) and $forcer_lang and ($forcer_lang !== 'non')
84
-		and !_request('action')
85
-		and $_SERVER['REQUEST_METHOD'] != 'POST'
86
-	) {
87
-		include_spip('inc/lang');
88
-		verifier_lang_url();
89
-	}
90
-
91
-	$lang = !isset($_GET['lang']) ? '' : lang_select($_GET['lang']);
92
-
93
-	// Charger l'aiguilleur des traitements derogatoires
94
-	// (action en base SQL, formulaires CVT, AJax)
95
-	if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
96
-		include_spip('public/aiguiller');
97
-		if (
98
-			// cas des appels actions ?action=xxx
99
-			traiter_appels_actions()
100
-			or
101
-			// cas des hits ajax sur les inclusions ajax
102
-			traiter_appels_inclusions_ajax()
103
-			or
104
-			// cas des formulaires charger/verifier/traiter
105
-			traiter_formulaires_dynamiques()
106
-		) {
107
-			// lancer les taches sur affichage final, comme le cron
108
-			// mais sans rien afficher
109
-			$GLOBALS['html'] = false; // ne rien afficher
110
-			pipeline('affichage_final' . _PIPELINE_SUFFIX, '');
111
-			exit; // le hit est fini !
112
-		}
113
-	}
114
-
115
-	// Il y a du texte a produire, charger le metteur en page
116
-	include_spip('public/assembler');
117
-	$page = assembler($fond, _request('connect') ?? '');
118
-
119
-	if (isset($page['status'])) {
120
-		include_spip('inc/headers');
121
-		http_response_code($page['status']);
122
-	}
123
-
124
-	// Content-Type ?
125
-	if (!isset($page['entetes']['Content-Type'])) {
126
-		$charset = $GLOBALS['meta']['charset'] ?? 'utf-8';
127
-		$page['entetes']['Content-Type'] = 'text/html; charset=' . $charset;
128
-		$html = true;
129
-	} else {
130
-		$html = preg_match(',^\s*text/html,', $page['entetes']['Content-Type']);
131
-	}
132
-
133
-	// Tester si on est admin et il y a des choses supplementaires a dire
134
-	// type tableau pour y mettre des choses au besoin.
135
-	$debug = ((_request('var_mode') == 'debug') or $tableau_des_temps) ? [1] : [];
136
-
137
-	// affiche-t-on les boutons d'administration ? voir f_admin()
138
-	$affiche_boutons_admin = ($html and (
139
-			(isset($_COOKIE['spip_admin']) and (!isset($flag_preserver) or !$flag_preserver))
140
-			or ($debug and include_spip('inc/autoriser') and autoriser('debug'))
141
-			or (defined('_VAR_PREVIEW') and _VAR_PREVIEW)
142
-		));
143
-
144
-	if ($affiche_boutons_admin) {
145
-		include_spip('balise/formulaire_admin');
146
-	}
147
-
148
-
149
-	// Execution de la page calculee
150
-
151
-	// traitements sur les entetes avant envoi
152
-	// peut servir pour le plugin de stats
153
-	$page['entetes'] = pipeline('affichage_entetes_final' . _PIPELINE_SUFFIX, $page['entetes']);
154
-
155
-
156
-	// eval $page et affecte $res
157
-	include _ROOT_RESTREINT . 'public/evaluer_page.php';
158
-	envoyer_entetes($page['entetes']);
159
-	if ($res === false) {
160
-		include_spip('inc/autoriser');
161
-		$err = _T('zbug_erreur_execution_page');
162
-		if (autoriser('webmestre')) {
163
-			$err .= "\n<hr />\n"
164
-				. highlight_string($page['codephp'], true)
165
-				. "\n<hr />\n";
166
-		}
167
-		$msg = [$err];
168
-		erreur_squelette($msg);
169
-	}
170
-
171
-	//
172
-	// Envoyer le resultat apres post-traitements
173
-	//
174
-	// (c'est ici qu'on fait var_recherche, validation, boutons d'admin,
175
-	// cf. public/assembler.php)
176
-	echo pipeline('affichage_final' . _PIPELINE_SUFFIX, $page['texte']);
177
-
178
-	if ($lang) {
179
-		lang_select();
180
-	}
181
-	// l'affichage de la page a pu lever des erreurs (inclusion manquante)
182
-	// il faut tester a nouveau
183
-	$debug = ((_request('var_mode') == 'debug') or $tableau_des_temps) ? [1] : [];
184
-
185
-	// Appel au debusqueur en cas d'erreurs ou de demande de trace
186
-	// at last
187
-	if ($debug) {
188
-		// en cas d'erreur, retester l'affichage
189
-		if ($html and ($affiche_boutons_admin or $debug)) {
190
-			$var_mode_affiche = _request('var_mode_affiche');
191
-			$var_mode_objet = _request('var_mode_objet');
192
-			$GLOBALS['debug_objets'][$var_mode_affiche][$var_mode_objet . 'tout'] = ($var_mode_affiche == 'validation' ? $page['texte'] : '');
193
-			echo erreur_squelette(false);
194
-		}
195
-	} else {
196
-		if (
197
-			isset($GLOBALS['meta']['date_prochain_postdate'])
198
-			and $GLOBALS['meta']['date_prochain_postdate'] <= time()
199
-		) {
200
-			include_spip('inc/rubriques');
201
-			calculer_prochain_postdate(true);
202
-		}
203
-
204
-		// Effectuer une tache de fond ?
205
-		// si _DIRECT_CRON_FORCE est present, on force l'appel
206
-		if (defined('_DIRECT_CRON_FORCE')) {
207
-			cron();
208
-		}
209
-
210
-		// sauver le cache chemin si necessaire
211
-		save_path_cache();
212
-	}
26
+    $GLOBALS['_INC_PUBLIC'] = 1;
27
+    define('_PIPELINE_SUFFIX', test_espace_prive() ? '_prive' : '');
28
+
29
+    // Faut-il initialiser SPIP ? (oui dans le cas general)
30
+    if (!defined('_DIR_RESTREINT_ABS')) {
31
+        if (
32
+            defined('_DIR_RESTREINT')
33
+            and @file_exists(_ROOT_RESTREINT . 'inc_version.php')
34
+        ) {
35
+            include_once _ROOT_RESTREINT . 'inc_version.php';
36
+        } else {
37
+            die('inc_version absent ?');
38
+        }
39
+    } // $fond defini dans le fichier d'appel ?
40
+
41
+    else {
42
+        if (isset($fond) and !_request('fond')) {
43
+        } // fond demande dans l'url par page=xxxx ?
44
+        else {
45
+            if (isset($_GET[_SPIP_PAGE])) {
46
+                $fond = (string)$_GET[_SPIP_PAGE];
47
+
48
+                // Securite
49
+                if (
50
+                    strstr($fond, '/')
51
+                    and !(
52
+                        isset($GLOBALS['visiteur_session']) // pour eviter d'evaluer la suite pour les anonymes
53
+                        and include_spip('inc/autoriser')
54
+                        and autoriser('webmestre'))
55
+                ) {
56
+                    include_spip('inc/minipres');
57
+                    echo minipres();
58
+                    exit;
59
+                }
60
+                // l'argument Page a priorite sur l'argument action
61
+                // le cas se presente a cause des RewriteRule d'Apache
62
+                // qui permettent d'ajouter un argument dans la QueryString
63
+                // mais pas d'en retirer un en conservant les autres.
64
+                if (isset($_GET['action']) and $_GET['action'] === $fond) {
65
+                    unset($_GET['action']);
66
+                }
67
+                # sinon, fond par defaut
68
+            } else {
69
+                // sinon fond par defaut (cf. assembler.php)
70
+                $fond = pipeline('detecter_fond_par_defaut', '');
71
+            }
72
+        }
73
+    }
74
+
75
+    $tableau_des_temps = [];
76
+
77
+    // Particularites de certains squelettes
78
+    if ($fond == 'login') {
79
+        $forcer_lang = true;
80
+    }
81
+
82
+    if (
83
+        isset($forcer_lang) and $forcer_lang and ($forcer_lang !== 'non')
84
+        and !_request('action')
85
+        and $_SERVER['REQUEST_METHOD'] != 'POST'
86
+    ) {
87
+        include_spip('inc/lang');
88
+        verifier_lang_url();
89
+    }
90
+
91
+    $lang = !isset($_GET['lang']) ? '' : lang_select($_GET['lang']);
92
+
93
+    // Charger l'aiguilleur des traitements derogatoires
94
+    // (action en base SQL, formulaires CVT, AJax)
95
+    if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
96
+        include_spip('public/aiguiller');
97
+        if (
98
+            // cas des appels actions ?action=xxx
99
+            traiter_appels_actions()
100
+            or
101
+            // cas des hits ajax sur les inclusions ajax
102
+            traiter_appels_inclusions_ajax()
103
+            or
104
+            // cas des formulaires charger/verifier/traiter
105
+            traiter_formulaires_dynamiques()
106
+        ) {
107
+            // lancer les taches sur affichage final, comme le cron
108
+            // mais sans rien afficher
109
+            $GLOBALS['html'] = false; // ne rien afficher
110
+            pipeline('affichage_final' . _PIPELINE_SUFFIX, '');
111
+            exit; // le hit est fini !
112
+        }
113
+    }
114
+
115
+    // Il y a du texte a produire, charger le metteur en page
116
+    include_spip('public/assembler');
117
+    $page = assembler($fond, _request('connect') ?? '');
118
+
119
+    if (isset($page['status'])) {
120
+        include_spip('inc/headers');
121
+        http_response_code($page['status']);
122
+    }
123
+
124
+    // Content-Type ?
125
+    if (!isset($page['entetes']['Content-Type'])) {
126
+        $charset = $GLOBALS['meta']['charset'] ?? 'utf-8';
127
+        $page['entetes']['Content-Type'] = 'text/html; charset=' . $charset;
128
+        $html = true;
129
+    } else {
130
+        $html = preg_match(',^\s*text/html,', $page['entetes']['Content-Type']);
131
+    }
132
+
133
+    // Tester si on est admin et il y a des choses supplementaires a dire
134
+    // type tableau pour y mettre des choses au besoin.
135
+    $debug = ((_request('var_mode') == 'debug') or $tableau_des_temps) ? [1] : [];
136
+
137
+    // affiche-t-on les boutons d'administration ? voir f_admin()
138
+    $affiche_boutons_admin = ($html and (
139
+            (isset($_COOKIE['spip_admin']) and (!isset($flag_preserver) or !$flag_preserver))
140
+            or ($debug and include_spip('inc/autoriser') and autoriser('debug'))
141
+            or (defined('_VAR_PREVIEW') and _VAR_PREVIEW)
142
+        ));
143
+
144
+    if ($affiche_boutons_admin) {
145
+        include_spip('balise/formulaire_admin');
146
+    }
147
+
148
+
149
+    // Execution de la page calculee
150
+
151
+    // traitements sur les entetes avant envoi
152
+    // peut servir pour le plugin de stats
153
+    $page['entetes'] = pipeline('affichage_entetes_final' . _PIPELINE_SUFFIX, $page['entetes']);
154
+
155
+
156
+    // eval $page et affecte $res
157
+    include _ROOT_RESTREINT . 'public/evaluer_page.php';
158
+    envoyer_entetes($page['entetes']);
159
+    if ($res === false) {
160
+        include_spip('inc/autoriser');
161
+        $err = _T('zbug_erreur_execution_page');
162
+        if (autoriser('webmestre')) {
163
+            $err .= "\n<hr />\n"
164
+                . highlight_string($page['codephp'], true)
165
+                . "\n<hr />\n";
166
+        }
167
+        $msg = [$err];
168
+        erreur_squelette($msg);
169
+    }
170
+
171
+    //
172
+    // Envoyer le resultat apres post-traitements
173
+    //
174
+    // (c'est ici qu'on fait var_recherche, validation, boutons d'admin,
175
+    // cf. public/assembler.php)
176
+    echo pipeline('affichage_final' . _PIPELINE_SUFFIX, $page['texte']);
177
+
178
+    if ($lang) {
179
+        lang_select();
180
+    }
181
+    // l'affichage de la page a pu lever des erreurs (inclusion manquante)
182
+    // il faut tester a nouveau
183
+    $debug = ((_request('var_mode') == 'debug') or $tableau_des_temps) ? [1] : [];
184
+
185
+    // Appel au debusqueur en cas d'erreurs ou de demande de trace
186
+    // at last
187
+    if ($debug) {
188
+        // en cas d'erreur, retester l'affichage
189
+        if ($html and ($affiche_boutons_admin or $debug)) {
190
+            $var_mode_affiche = _request('var_mode_affiche');
191
+            $var_mode_objet = _request('var_mode_objet');
192
+            $GLOBALS['debug_objets'][$var_mode_affiche][$var_mode_objet . 'tout'] = ($var_mode_affiche == 'validation' ? $page['texte'] : '');
193
+            echo erreur_squelette(false);
194
+        }
195
+    } else {
196
+        if (
197
+            isset($GLOBALS['meta']['date_prochain_postdate'])
198
+            and $GLOBALS['meta']['date_prochain_postdate'] <= time()
199
+        ) {
200
+            include_spip('inc/rubriques');
201
+            calculer_prochain_postdate(true);
202
+        }
203
+
204
+        // Effectuer une tache de fond ?
205
+        // si _DIRECT_CRON_FORCE est present, on force l'appel
206
+        if (defined('_DIRECT_CRON_FORCE')) {
207
+            cron();
208
+        }
209
+
210
+        // sauver le cache chemin si necessaire
211
+        save_path_cache();
212
+    }
213 213
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -30,9 +30,9 @@  discard block
 block discarded – undo
30 30
 	if (!defined('_DIR_RESTREINT_ABS')) {
31 31
 		if (
32 32
 			defined('_DIR_RESTREINT')
33
-			and @file_exists(_ROOT_RESTREINT . 'inc_version.php')
33
+			and @file_exists(_ROOT_RESTREINT.'inc_version.php')
34 34
 		) {
35
-			include_once _ROOT_RESTREINT . 'inc_version.php';
35
+			include_once _ROOT_RESTREINT.'inc_version.php';
36 36
 		} else {
37 37
 			die('inc_version absent ?');
38 38
 		}
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 		} // fond demande dans l'url par page=xxxx ?
44 44
 		else {
45 45
 			if (isset($_GET[_SPIP_PAGE])) {
46
-				$fond = (string)$_GET[_SPIP_PAGE];
46
+				$fond = (string) $_GET[_SPIP_PAGE];
47 47
 
48 48
 				// Securite
49 49
 				if (
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 			// lancer les taches sur affichage final, comme le cron
108 108
 			// mais sans rien afficher
109 109
 			$GLOBALS['html'] = false; // ne rien afficher
110
-			pipeline('affichage_final' . _PIPELINE_SUFFIX, '');
110
+			pipeline('affichage_final'._PIPELINE_SUFFIX, '');
111 111
 			exit; // le hit est fini !
112 112
 		}
113 113
 	}
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 	// Content-Type ?
125 125
 	if (!isset($page['entetes']['Content-Type'])) {
126 126
 		$charset = $GLOBALS['meta']['charset'] ?? 'utf-8';
127
-		$page['entetes']['Content-Type'] = 'text/html; charset=' . $charset;
127
+		$page['entetes']['Content-Type'] = 'text/html; charset='.$charset;
128 128
 		$html = true;
129 129
 	} else {
130 130
 		$html = preg_match(',^\s*text/html,', $page['entetes']['Content-Type']);
@@ -150,11 +150,11 @@  discard block
 block discarded – undo
150 150
 
151 151
 	// traitements sur les entetes avant envoi
152 152
 	// peut servir pour le plugin de stats
153
-	$page['entetes'] = pipeline('affichage_entetes_final' . _PIPELINE_SUFFIX, $page['entetes']);
153
+	$page['entetes'] = pipeline('affichage_entetes_final'._PIPELINE_SUFFIX, $page['entetes']);
154 154
 
155 155
 
156 156
 	// eval $page et affecte $res
157
-	include _ROOT_RESTREINT . 'public/evaluer_page.php';
157
+	include _ROOT_RESTREINT.'public/evaluer_page.php';
158 158
 	envoyer_entetes($page['entetes']);
159 159
 	if ($res === false) {
160 160
 		include_spip('inc/autoriser');
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	//
174 174
 	// (c'est ici qu'on fait var_recherche, validation, boutons d'admin,
175 175
 	// cf. public/assembler.php)
176
-	echo pipeline('affichage_final' . _PIPELINE_SUFFIX, $page['texte']);
176
+	echo pipeline('affichage_final'._PIPELINE_SUFFIX, $page['texte']);
177 177
 
178 178
 	if ($lang) {
179 179
 		lang_select();
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		if ($html and ($affiche_boutons_admin or $debug)) {
190 190
 			$var_mode_affiche = _request('var_mode_affiche');
191 191
 			$var_mode_objet = _request('var_mode_objet');
192
-			$GLOBALS['debug_objets'][$var_mode_affiche][$var_mode_objet . 'tout'] = ($var_mode_affiche == 'validation' ? $page['texte'] : '');
192
+			$GLOBALS['debug_objets'][$var_mode_affiche][$var_mode_objet.'tout'] = ($var_mode_affiche == 'validation' ? $page['texte'] : '');
193 193
 			echo erreur_squelette(false);
194 194
 		}
195 195
 	} else {
Please login to merge, or discard this patch.