Completed
Push — master ( d9afd7...afcd40 )
by cam
01:15
created
ecrire/inc/rechercher.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	if (substr($recherche, 0, 1) == '/' and substr($recherche, -1, 1) == '/' and strlen($recherche) > 2) {
101 101
 		// c'est une preg
102 102
 		$recherche_trans = translitteration($recherche);
103
-		$preg = $recherche_trans . $options['preg_flags'];
103
+		$preg = $recherche_trans.$options['preg_flags'];
104 104
 		$is_preg = true;
105 105
 	} else {
106 106
 		// s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP,
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 			}
121 121
 		}
122 122
 
123
-		if (preg_match(',\s+,' . $u, $recherche_mod)) {
123
+		if (preg_match(',\s+,'.$u, $recherche_mod)) {
124 124
 			$is_preg = true;
125 125
 
126 126
 			$recherche_inter = '|';
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 			foreach ($recherche_mots as $mot) {
131 131
 				if (strlen($mot) >= $min_long) {
132 132
 					// echapper les caracteres de regexp qui sont eventuellement dans la recherche
133
-					$recherche_inter .= preg_quote($mot) . ' ';
133
+					$recherche_inter .= preg_quote($mot).' ';
134 134
 					$petits_mots = false;
135 135
 				}
136 136
 			}
@@ -138,14 +138,14 @@  discard block
 block discarded – undo
138 138
 
139 139
 			// mais on cherche quand même l'expression complète, même si elle
140 140
 			// comporte des mots de moins de quatre lettres
141
-			$recherche = trim(preg_replace(',\s+,' . $u, '|', $recherche_inter), '|');
141
+			$recherche = trim(preg_replace(',\s+,'.$u, '|', $recherche_inter), '|');
142 142
 			if (!$recherche or $petits_mots) {
143 143
 				$recherche = preg_quote($recherche_org);
144 144
 			}
145 145
 			$recherche_trans = translitteration($recherche);
146 146
 		}
147 147
 
148
-		$preg = '/' . str_replace('/', '\\/', $recherche_trans) . '/' . $options['preg_flags'];
148
+		$preg = '/'.str_replace('/', '\\/', $recherche_trans).'/'.$options['preg_flags'];
149 149
 	}
150 150
 
151 151
 	// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
 		}
186 186
 		$q = sql_quote(
187 187
 			'%'
188
-			. preg_replace(',\s+,' . $u, '%', $q)
188
+			. preg_replace(',\s+,'.$u, '%', $q)
189 189
 			. '%'
190 190
 		);
191 191
 
192
-		$preg = '/' . preg_replace(',\s+,' . $u, '.+', trim($recherche_mod)) . '/' . $options['preg_flags'];
192
+		$preg = '/'.preg_replace(',\s+,'.$u, '.+', trim($recherche_mod)).'/'.$options['preg_flags'];
193 193
 	} else {
194 194
 		$methode = 'REGEXP';
195 195
 		$q = sql_quote(trim($recherche, '/'));
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	foreach ($tables as $table => $champs) {
312 312
 		# lock via memoization, si dispo
313 313
 		if (function_exists('cache_lock')) {
314
-			cache_lock($lock = _RECHERCHE_LOCK_KEY . ' ' . $table . ' ' . $recherche);
314
+			cache_lock($lock = _RECHERCHE_LOCK_KEY.' '.$table.' '.$recherche);
315 315
 		}
316 316
 
317 317
 		spip_timer('rech');
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 
327 327
 
328 328
 		spip_log(
329
-			"recherche $table ($recherche) : " . (is_countable($results[$table]) ? count($results[$table]) : 0) . ' resultats ' . spip_timer('rech'),
329
+			"recherche $table ($recherche) : ".(is_countable($results[$table]) ? count($results[$table]) : 0).' resultats '.spip_timer('rech'),
330 330
 			'recherche'
331 331
 		);
332 332
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 
362 362
 	$results = recherche_en_base($recherche, $tables, $options);
363 363
 
364
-	$preg = '/' . str_replace('/', '\\/', $recherche) . '/' . $options['preg_flags'];
364
+	$preg = '/'.str_replace('/', '\\/', $recherche).'/'.$options['preg_flags'];
365 365
 
366 366
 	foreach ($results as $table => $r) {
367 367
 		$_id_table = id_table_objet($table);
Please login to merge, or discard this patch.
Indentation   +317 added lines, -317 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
 defined('_RECHERCHE_LOCK_KEY') || define('_RECHERCHE_LOCK_KEY', 'fulltext');
@@ -35,198 +35,198 @@  discard block
 block discarded – undo
35 35
  * @return array Couples (type d'objet => Couples (champ => score))
36 36
  */
37 37
 function liste_des_champs() {
38
-	static $liste = null;
39
-	if (is_null($liste)) {
40
-		$liste = [];
41
-		// recuperer les tables_objets_sql declarees
42
-		include_spip('base/objets');
43
-		$tables_objets = lister_tables_objets_sql();
44
-		foreach ($tables_objets as $t => $infos) {
45
-			if ($infos['rechercher_champs']) {
46
-				$liste[$infos['type']] = $infos['rechercher_champs'];
47
-			}
48
-		}
49
-		// puis passer dans le pipeline
50
-		$liste = pipeline('rechercher_liste_des_champs', $liste);
51
-	}
52
-
53
-	return $liste;
38
+    static $liste = null;
39
+    if (is_null($liste)) {
40
+        $liste = [];
41
+        // recuperer les tables_objets_sql declarees
42
+        include_spip('base/objets');
43
+        $tables_objets = lister_tables_objets_sql();
44
+        foreach ($tables_objets as $t => $infos) {
45
+            if ($infos['rechercher_champs']) {
46
+                $liste[$infos['type']] = $infos['rechercher_champs'];
47
+            }
48
+        }
49
+        // puis passer dans le pipeline
50
+        $liste = pipeline('rechercher_liste_des_champs', $liste);
51
+    }
52
+
53
+    return $liste;
54 54
 }
55 55
 
56 56
 
57 57
 // Recherche des auteurs et mots-cles associes
58 58
 // en ne regardant que le titre ou le nom
59 59
 function liste_des_jointures() {
60
-	static $liste = null;
61
-	if (is_null($liste)) {
62
-		$liste = [];
63
-		// recuperer les tables_objets_sql declarees
64
-		include_spip('base/objets');
65
-		$tables_objets = lister_tables_objets_sql();
66
-		foreach ($tables_objets as $t => $infos) {
67
-			if ($infos['rechercher_jointures']) {
68
-				$liste[$infos['type']] = $infos['rechercher_jointures'];
69
-			}
70
-		}
71
-		// puis passer dans le pipeline
72
-		$liste = pipeline('rechercher_liste_des_jointures', $liste);
73
-	}
74
-
75
-	return $liste;
60
+    static $liste = null;
61
+    if (is_null($liste)) {
62
+        $liste = [];
63
+        // recuperer les tables_objets_sql declarees
64
+        include_spip('base/objets');
65
+        $tables_objets = lister_tables_objets_sql();
66
+        foreach ($tables_objets as $t => $infos) {
67
+            if ($infos['rechercher_jointures']) {
68
+                $liste[$infos['type']] = $infos['rechercher_jointures'];
69
+            }
70
+        }
71
+        // puis passer dans le pipeline
72
+        $liste = pipeline('rechercher_liste_des_jointures', $liste);
73
+    }
74
+
75
+    return $liste;
76 76
 }
77 77
 
78 78
 function expression_recherche($recherche, $options) {
79
-	// ne calculer qu'une seule fois l'expression par hit
80
-	// (meme si utilisee dans plusieurs boucles)
81
-	static $expression = [];
82
-	$key = serialize([$recherche, $options['preg_flags']]);
83
-	if (isset($expression[$key])) {
84
-		return $expression[$key];
85
-	}
86
-
87
-	$u = $GLOBALS['meta']['pcre_u'];
88
-	if ($u and strpos($options['preg_flags'], (string) $u) === false) {
89
-		$options['preg_flags'] .= $u;
90
-	}
91
-	include_spip('inc/charsets');
92
-	$recherche = trim($recherche);
93
-
94
-	// retirer les + de +truc et les * de truc*
95
-	$recherche = preg_replace(',(^|\s)\+(\w),Uims', '$1$2', $recherche);
96
-	$recherche = preg_replace(',(\w)\*($|\s),Uims', '$1$2', $recherche);
97
-
98
-	$is_preg = false;
99
-	if (substr($recherche, 0, 1) == '/' and substr($recherche, -1, 1) == '/' and strlen($recherche) > 2) {
100
-		// c'est une preg
101
-		$recherche_trans = translitteration($recherche);
102
-		$preg = $recherche_trans . $options['preg_flags'];
103
-		$is_preg = true;
104
-	} else {
105
-		// s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP,
106
-		// sauf ceux de moins de 4 lettres (on supprime ainsi 'le', 'les', 'un',
107
-		// 'une', 'des' ...)
108
-
109
-		// attention : plusieurs mots entre guillemets sont a rechercher tels quels
110
-		$recherche_trans = $recherche_mod = $recherche_org = $recherche;
111
-
112
-		// les expressions entre " " sont un mot a chercher tel quel
113
-		// -> on remplace les espaces par un \x1 et on enleve les guillemets
114
-		if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
115
-			foreach ($matches as $match) {
116
-				$word = preg_replace(',\s+,Uims', "\x1", $match);
117
-				$word = trim($word, '"');
118
-				$recherche_mod = str_replace($match, $word, $recherche_mod);
119
-			}
120
-		}
121
-
122
-		if (preg_match(',\s+,' . $u, $recherche_mod)) {
123
-			$is_preg = true;
124
-
125
-			$recherche_inter = '|';
126
-			$recherche_mots = explode(' ', $recherche_mod);
127
-			$min_long = defined('_RECHERCHE_MIN_CAR') ? _RECHERCHE_MIN_CAR : 4;
128
-			$petits_mots = true;
129
-			foreach ($recherche_mots as $mot) {
130
-				if (strlen($mot) >= $min_long) {
131
-					// echapper les caracteres de regexp qui sont eventuellement dans la recherche
132
-					$recherche_inter .= preg_quote($mot) . ' ';
133
-					$petits_mots = false;
134
-				}
135
-			}
136
-			$recherche_inter = str_replace("\x1", '\s', $recherche_inter);
137
-
138
-			// mais on cherche quand même l'expression complète, même si elle
139
-			// comporte des mots de moins de quatre lettres
140
-			$recherche = trim(preg_replace(',\s+,' . $u, '|', $recherche_inter), '|');
141
-			if (!$recherche or $petits_mots) {
142
-				$recherche = preg_quote($recherche_org);
143
-			}
144
-			$recherche_trans = translitteration($recherche);
145
-		}
146
-
147
-		$preg = '/' . str_replace('/', '\\/', $recherche_trans) . '/' . $options['preg_flags'];
148
-	}
149
-
150
-	// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
151
-	// ou si l'expression reguliere est invalide
152
-	if (
153
-		!$is_preg
154
-		or (@preg_match($preg, '') === false)
155
-	) {
156
-		$methode = 'LIKE';
157
-		$u = $GLOBALS['meta']['pcre_u'];
158
-
159
-		// echapper les % et _
160
-		$q = str_replace(['%', '_'], ['\%', '\_'], trim($recherche));
161
-
162
-		// eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
163
-		$recherche = preg_quote($recherche, '/');
164
-		$recherche_trans = translitteration($recherche);
165
-		$recherche_mod = $recherche_trans;
166
-
167
-		// les expressions entre " " sont un mot a chercher tel quel
168
-		// -> on remplace les espaces par un _ et on enleve les guillemets
169
-		// corriger le like dans le $q
170
-		if (preg_match(',["][^"]+["],Uims', $q, $matches)) {
171
-			foreach ($matches as $match) {
172
-				$word = preg_replace(',\s+,Uims', '_', $match);
173
-				$word = trim($word, '"');
174
-				$q = str_replace($match, $word, $q);
175
-			}
176
-		}
177
-		// corriger la regexp
178
-		if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
179
-			foreach ($matches as $match) {
180
-				$word = preg_replace(',\s+,Uims', '[\s]', $match);
181
-				$word = trim($word, '"');
182
-				$recherche_mod = str_replace($match, $word, $recherche_mod);
183
-			}
184
-		}
185
-		$q = sql_quote(
186
-			'%'
187
-			. preg_replace(',\s+,' . $u, '%', $q)
188
-			. '%'
189
-		);
190
-
191
-		$preg = '/' . preg_replace(',\s+,' . $u, '.+', trim($recherche_mod)) . '/' . $options['preg_flags'];
192
-	} else {
193
-		$methode = 'REGEXP';
194
-		$q = sql_quote(trim($recherche, '/'));
195
-	}
196
-
197
-	// tous les caracteres transliterables de $q sont remplaces par un joker
198
-	// permet de matcher en SQL meme si on est sensible aux accents (SQLite)
199
-	$q_t = $q;
200
-	for ($i = 0; $i < spip_strlen($q); $i++) {
201
-		$char = spip_substr($q, $i, 1);
202
-		if (
203
-			!is_ascii($char)
204
-			and $char_t = translitteration($char)
205
-			and $char_t !== $char
206
-		) {
207
-			// on utilise ..?.? car le char utf peut etre encode sur 1, 2 ou 3 bytes
208
-			// mais c'est un pis aller cf #4354
209
-			$q_t = str_replace($char, $is_preg ? '..?.?' : '_', $q_t);
210
-		}
211
-	}
212
-
213
-	$q = $q_t;
214
-
215
-	// fix : SQLite 3 est sensible aux accents, on jokerise les caracteres
216
-	// les plus frequents qui peuvent etre accentues
217
-	// (oui c'est tres dicustable...)
218
-	if (
219
-		isset($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'])
220
-		and strncmp($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'], 'sqlite', 6) == 0
221
-	) {
222
-		$q_t = strtr($q, 'aeuioc', $is_preg ? '......' : '______');
223
-		// si il reste au moins un char significatif...
224
-		if (preg_match(",[^'%_.],", $q_t)) {
225
-			$q = $q_t;
226
-		}
227
-	}
228
-
229
-	return $expression[$key] = [$methode, $q, $preg];
79
+    // ne calculer qu'une seule fois l'expression par hit
80
+    // (meme si utilisee dans plusieurs boucles)
81
+    static $expression = [];
82
+    $key = serialize([$recherche, $options['preg_flags']]);
83
+    if (isset($expression[$key])) {
84
+        return $expression[$key];
85
+    }
86
+
87
+    $u = $GLOBALS['meta']['pcre_u'];
88
+    if ($u and strpos($options['preg_flags'], (string) $u) === false) {
89
+        $options['preg_flags'] .= $u;
90
+    }
91
+    include_spip('inc/charsets');
92
+    $recherche = trim($recherche);
93
+
94
+    // retirer les + de +truc et les * de truc*
95
+    $recherche = preg_replace(',(^|\s)\+(\w),Uims', '$1$2', $recherche);
96
+    $recherche = preg_replace(',(\w)\*($|\s),Uims', '$1$2', $recherche);
97
+
98
+    $is_preg = false;
99
+    if (substr($recherche, 0, 1) == '/' and substr($recherche, -1, 1) == '/' and strlen($recherche) > 2) {
100
+        // c'est une preg
101
+        $recherche_trans = translitteration($recherche);
102
+        $preg = $recherche_trans . $options['preg_flags'];
103
+        $is_preg = true;
104
+    } else {
105
+        // s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP,
106
+        // sauf ceux de moins de 4 lettres (on supprime ainsi 'le', 'les', 'un',
107
+        // 'une', 'des' ...)
108
+
109
+        // attention : plusieurs mots entre guillemets sont a rechercher tels quels
110
+        $recherche_trans = $recherche_mod = $recherche_org = $recherche;
111
+
112
+        // les expressions entre " " sont un mot a chercher tel quel
113
+        // -> on remplace les espaces par un \x1 et on enleve les guillemets
114
+        if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
115
+            foreach ($matches as $match) {
116
+                $word = preg_replace(',\s+,Uims', "\x1", $match);
117
+                $word = trim($word, '"');
118
+                $recherche_mod = str_replace($match, $word, $recherche_mod);
119
+            }
120
+        }
121
+
122
+        if (preg_match(',\s+,' . $u, $recherche_mod)) {
123
+            $is_preg = true;
124
+
125
+            $recherche_inter = '|';
126
+            $recherche_mots = explode(' ', $recherche_mod);
127
+            $min_long = defined('_RECHERCHE_MIN_CAR') ? _RECHERCHE_MIN_CAR : 4;
128
+            $petits_mots = true;
129
+            foreach ($recherche_mots as $mot) {
130
+                if (strlen($mot) >= $min_long) {
131
+                    // echapper les caracteres de regexp qui sont eventuellement dans la recherche
132
+                    $recherche_inter .= preg_quote($mot) . ' ';
133
+                    $petits_mots = false;
134
+                }
135
+            }
136
+            $recherche_inter = str_replace("\x1", '\s', $recherche_inter);
137
+
138
+            // mais on cherche quand même l'expression complète, même si elle
139
+            // comporte des mots de moins de quatre lettres
140
+            $recherche = trim(preg_replace(',\s+,' . $u, '|', $recherche_inter), '|');
141
+            if (!$recherche or $petits_mots) {
142
+                $recherche = preg_quote($recherche_org);
143
+            }
144
+            $recherche_trans = translitteration($recherche);
145
+        }
146
+
147
+        $preg = '/' . str_replace('/', '\\/', $recherche_trans) . '/' . $options['preg_flags'];
148
+    }
149
+
150
+    // Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
151
+    // ou si l'expression reguliere est invalide
152
+    if (
153
+        !$is_preg
154
+        or (@preg_match($preg, '') === false)
155
+    ) {
156
+        $methode = 'LIKE';
157
+        $u = $GLOBALS['meta']['pcre_u'];
158
+
159
+        // echapper les % et _
160
+        $q = str_replace(['%', '_'], ['\%', '\_'], trim($recherche));
161
+
162
+        // eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
163
+        $recherche = preg_quote($recherche, '/');
164
+        $recherche_trans = translitteration($recherche);
165
+        $recherche_mod = $recherche_trans;
166
+
167
+        // les expressions entre " " sont un mot a chercher tel quel
168
+        // -> on remplace les espaces par un _ et on enleve les guillemets
169
+        // corriger le like dans le $q
170
+        if (preg_match(',["][^"]+["],Uims', $q, $matches)) {
171
+            foreach ($matches as $match) {
172
+                $word = preg_replace(',\s+,Uims', '_', $match);
173
+                $word = trim($word, '"');
174
+                $q = str_replace($match, $word, $q);
175
+            }
176
+        }
177
+        // corriger la regexp
178
+        if (preg_match(',["][^"]+["],Uims', $recherche_mod, $matches)) {
179
+            foreach ($matches as $match) {
180
+                $word = preg_replace(',\s+,Uims', '[\s]', $match);
181
+                $word = trim($word, '"');
182
+                $recherche_mod = str_replace($match, $word, $recherche_mod);
183
+            }
184
+        }
185
+        $q = sql_quote(
186
+            '%'
187
+            . preg_replace(',\s+,' . $u, '%', $q)
188
+            . '%'
189
+        );
190
+
191
+        $preg = '/' . preg_replace(',\s+,' . $u, '.+', trim($recherche_mod)) . '/' . $options['preg_flags'];
192
+    } else {
193
+        $methode = 'REGEXP';
194
+        $q = sql_quote(trim($recherche, '/'));
195
+    }
196
+
197
+    // tous les caracteres transliterables de $q sont remplaces par un joker
198
+    // permet de matcher en SQL meme si on est sensible aux accents (SQLite)
199
+    $q_t = $q;
200
+    for ($i = 0; $i < spip_strlen($q); $i++) {
201
+        $char = spip_substr($q, $i, 1);
202
+        if (
203
+            !is_ascii($char)
204
+            and $char_t = translitteration($char)
205
+            and $char_t !== $char
206
+        ) {
207
+            // on utilise ..?.? car le char utf peut etre encode sur 1, 2 ou 3 bytes
208
+            // mais c'est un pis aller cf #4354
209
+            $q_t = str_replace($char, $is_preg ? '..?.?' : '_', $q_t);
210
+        }
211
+    }
212
+
213
+    $q = $q_t;
214
+
215
+    // fix : SQLite 3 est sensible aux accents, on jokerise les caracteres
216
+    // les plus frequents qui peuvent etre accentues
217
+    // (oui c'est tres dicustable...)
218
+    if (
219
+        isset($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'])
220
+        and strncmp($GLOBALS['connexions'][$options['serveur'] ?: 0]['type'], 'sqlite', 6) == 0
221
+    ) {
222
+        $q_t = strtr($q, 'aeuioc', $is_preg ? '......' : '______');
223
+        // si il reste au moins un char significatif...
224
+        if (preg_match(",[^'%_.],", $q_t)) {
225
+            $q = $q_t;
226
+        }
227
+    }
228
+
229
+    return $expression[$key] = [$methode, $q, $preg];
230 230
 }
231 231
 
232 232
 
@@ -253,142 +253,142 @@  discard block
 block discarded – undo
253 253
  * @return array
254 254
  */
255 255
 function recherche_en_base($recherche = '', $tables = null, $options = [], $serveur = '') {
256
-	include_spip('base/abstract_sql');
257
-
258
-	if (!is_array($tables)) {
259
-		$liste = liste_des_champs();
260
-
261
-		if (
262
-			is_string($tables)
263
-			and $tables != ''
264
-		) {
265
-			$toutes = [];
266
-			foreach (explode(',', $tables) as $t) {
267
-				$t = trim($t);
268
-				if (isset($liste[$t])) {
269
-					$toutes[$t] = $liste[$t];
270
-				}
271
-			}
272
-			$tables = $toutes;
273
-			unset($toutes);
274
-		} else {
275
-			$tables = $liste;
276
-		}
277
-	}
278
-
279
-	if (!strlen($recherche) or !count($tables)) {
280
-		return [];
281
-	}
282
-
283
-	include_spip('inc/autoriser');
284
-
285
-	// options par defaut
286
-	$options = array_merge(
287
-		[
288
-		'preg_flags' => 'UimsS',
289
-		'toutvoir' => false,
290
-		'champs' => false,
291
-		'score' => false,
292
-		'matches' => false,
293
-		'jointures' => false,
294
-		'serveur' => $serveur
295
-		],
296
-		$options
297
-	);
298
-
299
-	$results = [];
300
-
301
-	// Utiliser l'iterateur (DATA:recherche)
302
-	// pour recuperer les couples (id_objet, score)
303
-	// Le resultat est au format {
304
-	//      id1 = { 'score' => x, attrs => { } },
305
-	//      id2 = { 'score' => x, attrs => { } },
306
-	// }
307
-
308
-	include_spip('inc/recherche_to_array');
309
-
310
-	foreach ($tables as $table => $champs) {
311
-		# lock via memoization, si dispo
312
-		if (function_exists('cache_lock')) {
313
-			cache_lock($lock = _RECHERCHE_LOCK_KEY . ' ' . $table . ' ' . $recherche);
314
-		}
315
-
316
-		spip_timer('rech');
317
-
318
-		# TODO : ici plutot charger un iterateur via l'API iterateurs
319
-		$to_array = charger_fonction('recherche_to_array', 'inc');
320
-		$results[$table] = $to_array(
321
-			$recherche,
322
-			array_merge($options, ['table' => $table, 'champs' => $champs])
323
-		);
324
-		##var_dump($results[$table]);
325
-
326
-
327
-		spip_log(
328
-			"recherche $table ($recherche) : " . (is_countable($results[$table]) ? count($results[$table]) : 0) . ' resultats ' . spip_timer('rech'),
329
-			'recherche'
330
-		);
331
-
332
-		if (isset($lock)) {
333
-			cache_unlock($lock);
334
-		}
335
-	}
336
-
337
-	return $results;
256
+    include_spip('base/abstract_sql');
257
+
258
+    if (!is_array($tables)) {
259
+        $liste = liste_des_champs();
260
+
261
+        if (
262
+            is_string($tables)
263
+            and $tables != ''
264
+        ) {
265
+            $toutes = [];
266
+            foreach (explode(',', $tables) as $t) {
267
+                $t = trim($t);
268
+                if (isset($liste[$t])) {
269
+                    $toutes[$t] = $liste[$t];
270
+                }
271
+            }
272
+            $tables = $toutes;
273
+            unset($toutes);
274
+        } else {
275
+            $tables = $liste;
276
+        }
277
+    }
278
+
279
+    if (!strlen($recherche) or !count($tables)) {
280
+        return [];
281
+    }
282
+
283
+    include_spip('inc/autoriser');
284
+
285
+    // options par defaut
286
+    $options = array_merge(
287
+        [
288
+        'preg_flags' => 'UimsS',
289
+        'toutvoir' => false,
290
+        'champs' => false,
291
+        'score' => false,
292
+        'matches' => false,
293
+        'jointures' => false,
294
+        'serveur' => $serveur
295
+        ],
296
+        $options
297
+    );
298
+
299
+    $results = [];
300
+
301
+    // Utiliser l'iterateur (DATA:recherche)
302
+    // pour recuperer les couples (id_objet, score)
303
+    // Le resultat est au format {
304
+    //      id1 = { 'score' => x, attrs => { } },
305
+    //      id2 = { 'score' => x, attrs => { } },
306
+    // }
307
+
308
+    include_spip('inc/recherche_to_array');
309
+
310
+    foreach ($tables as $table => $champs) {
311
+        # lock via memoization, si dispo
312
+        if (function_exists('cache_lock')) {
313
+            cache_lock($lock = _RECHERCHE_LOCK_KEY . ' ' . $table . ' ' . $recherche);
314
+        }
315
+
316
+        spip_timer('rech');
317
+
318
+        # TODO : ici plutot charger un iterateur via l'API iterateurs
319
+        $to_array = charger_fonction('recherche_to_array', 'inc');
320
+        $results[$table] = $to_array(
321
+            $recherche,
322
+            array_merge($options, ['table' => $table, 'champs' => $champs])
323
+        );
324
+        ##var_dump($results[$table]);
325
+
326
+
327
+        spip_log(
328
+            "recherche $table ($recherche) : " . (is_countable($results[$table]) ? count($results[$table]) : 0) . ' resultats ' . spip_timer('rech'),
329
+            'recherche'
330
+        );
331
+
332
+        if (isset($lock)) {
333
+            cache_unlock($lock);
334
+        }
335
+    }
336
+
337
+    return $results;
338 338
 }
339 339
 
340 340
 
341 341
 // Effectue une recherche sur toutes les tables de la base de donnees
342 342
 function remplace_en_base($recherche = '', $remplace = null, $tables = null, $options = []) {
343
-	include_spip('inc/modifier');
344
-
345
-	// options par defaut
346
-	$options = array_merge(
347
-		[
348
-		'preg_flags' => 'UimsS',
349
-		'toutmodifier' => false
350
-		],
351
-		$options
352
-	);
353
-	$options['champs'] = true;
354
-
355
-
356
-	if (!is_array($tables)) {
357
-		$tables = liste_des_champs();
358
-	}
359
-
360
-	$results = recherche_en_base($recherche, $tables, $options);
361
-
362
-	$preg = '/' . str_replace('/', '\\/', $recherche) . '/' . $options['preg_flags'];
363
-
364
-	foreach ($results as $table => $r) {
365
-		$_id_table = id_table_objet($table);
366
-		foreach ($r as $id => $x) {
367
-			if (
368
-				$options['toutmodifier']
369
-				or autoriser('modifier', $table, $id)
370
-			) {
371
-				$modifs = [];
372
-				foreach ($x['champs'] as $key => $val) {
373
-					if ($key == $_id_table) {
374
-						continue;
375
-					}
376
-					$repl = preg_replace($preg, $remplace, $val);
377
-					if ($repl <> $val) {
378
-						$modifs[$key] = $repl;
379
-					}
380
-				}
381
-				if ($modifs) {
382
-					objet_modifier_champs(
383
-						$table,
384
-						$id,
385
-						[
386
-							'champs' => array_keys($modifs),
387
-						],
388
-						$modifs
389
-					);
390
-				}
391
-			}
392
-		}
393
-	}
343
+    include_spip('inc/modifier');
344
+
345
+    // options par defaut
346
+    $options = array_merge(
347
+        [
348
+        'preg_flags' => 'UimsS',
349
+        'toutmodifier' => false
350
+        ],
351
+        $options
352
+    );
353
+    $options['champs'] = true;
354
+
355
+
356
+    if (!is_array($tables)) {
357
+        $tables = liste_des_champs();
358
+    }
359
+
360
+    $results = recherche_en_base($recherche, $tables, $options);
361
+
362
+    $preg = '/' . str_replace('/', '\\/', $recherche) . '/' . $options['preg_flags'];
363
+
364
+    foreach ($results as $table => $r) {
365
+        $_id_table = id_table_objet($table);
366
+        foreach ($r as $id => $x) {
367
+            if (
368
+                $options['toutmodifier']
369
+                or autoriser('modifier', $table, $id)
370
+            ) {
371
+                $modifs = [];
372
+                foreach ($x['champs'] as $key => $val) {
373
+                    if ($key == $_id_table) {
374
+                        continue;
375
+                    }
376
+                    $repl = preg_replace($preg, $remplace, $val);
377
+                    if ($repl <> $val) {
378
+                        $modifs[$key] = $repl;
379
+                    }
380
+                }
381
+                if ($modifs) {
382
+                    objet_modifier_champs(
383
+                        $table,
384
+                        $id,
385
+                        [
386
+                            'champs' => array_keys($modifs),
387
+                        ],
388
+                        $modifs
389
+                    );
390
+                }
391
+            }
392
+        }
393
+    }
394 394
 }
Please login to merge, or discard this patch.
ecrire/inc/invalideur.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 	$n = 0;
46 46
 	$time = $GLOBALS['meta']['cache_mark'] ?? 0;
47 47
 	for ($i = 0; $i < 256; $i++) {
48
-		$dir = _DIR_CACHE . sprintf('%02s', dechex($i));
48
+		$dir = _DIR_CACHE.sprintf('%02s', dechex($i));
49 49
 		if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
50 50
 			while (($f = readdir($d)) !== false) {
51 51
 				if (preg_match(',^[[0-9a-f]+\.cache$,S', $f) and $a = stat("$dir/$f")) {
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 
103 103
 	// stocker la date_modif_$objet (ne sert a rien pour le moment)
104 104
 	if (isset($objet)) {
105
-		ecrire_meta('derniere_modif_' . $objet, time());
105
+		ecrire_meta('derniere_modif_'.$objet, time());
106 106
 	}
107 107
 
108 108
 	// si $derniere_modif_invalide est un array('article', 'rubrique')
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 
146 146
 	// sur certains sites on veut absolument garder certains caches référencés dans un CDN
147 147
 	// on peut donc inhiber la purge de ces répertoires pour eviter tout probleme
148
-	if (file_exists(rtrim($dir, '/') . '/inhib_purger_repertoire.txt')) {
148
+	if (file_exists(rtrim($dir, '/').'/inhib_purger_repertoire.txt')) {
149 149
 		return 0;
150 150
 	}
151 151
 
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 		)
209 209
 	) {
210 210
 		// supprimer le fichier (de facon propre)
211
-		supprimer_fichier(_DIR_CACHE . $cache);
211
+		supprimer_fichier(_DIR_CACHE.$cache);
212 212
 	} else {
213 213
 		spip_log("Nom de fichier cache incorrect : $cache");
214 214
 	}
Please login to merge, or discard this patch.
Indentation   +138 added lines, -138 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/serial');
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
  * en droit de l'éliminer
28 28
  */
29 29
 if (!defined('_AGE_CACHE_ATIME')) {
30
-	define('_AGE_CACHE_ATIME', 3600);
30
+    define('_AGE_CACHE_ATIME', 3600);
31 31
 }
32 32
 
33 33
 
@@ -40,31 +40,31 @@  discard block
 block discarded – undo
40 40
  * @return int Taille approximative en octets
41 41
  **/
42 42
 function taille_du_cache() {
43
-	# check dirs until we reach > 500 files
44
-	$t = 0;
45
-	$n = 0;
46
-	$time = $GLOBALS['meta']['cache_mark'] ?? 0;
47
-	for ($i = 0; $i < 256; $i++) {
48
-		$dir = _DIR_CACHE . sprintf('%02s', dechex($i));
49
-		if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
50
-			while (($f = readdir($d)) !== false) {
51
-				if (preg_match(',^[[0-9a-f]+\.cache$,S', $f) and $a = stat("$dir/$f")) {
52
-					$n++;
53
-					if ($a['mtime'] >= $time) {
54
-						if ($a['blocks'] > 0) {
55
-							$t += 512 * $a['blocks'];
56
-						} else {
57
-							$t += $a['size'];
58
-						}
59
-					}
60
-				}
61
-			}
62
-		}
63
-		if ($n > 500) {
64
-			return intval(256 * $t / (1 + $i));
65
-		}
66
-	}
67
-	return $t;
43
+    # check dirs until we reach > 500 files
44
+    $t = 0;
45
+    $n = 0;
46
+    $time = $GLOBALS['meta']['cache_mark'] ?? 0;
47
+    for ($i = 0; $i < 256; $i++) {
48
+        $dir = _DIR_CACHE . sprintf('%02s', dechex($i));
49
+        if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
50
+            while (($f = readdir($d)) !== false) {
51
+                if (preg_match(',^[[0-9a-f]+\.cache$,S', $f) and $a = stat("$dir/$f")) {
52
+                    $n++;
53
+                    if ($a['mtime'] >= $time) {
54
+                        if ($a['blocks'] > 0) {
55
+                            $t += 512 * $a['blocks'];
56
+                        } else {
57
+                            $t += $a['size'];
58
+                        }
59
+                    }
60
+                }
61
+            }
62
+        }
63
+        if ($n > 500) {
64
+            return intval(256 * $t / (1 + $i));
65
+        }
66
+    }
67
+    return $t;
68 68
 }
69 69
 
70 70
 
@@ -91,30 +91,30 @@  discard block
 block discarded – undo
91 91
  *     Inutilisé
92 92
  **/
93 93
 function inc_suivre_invalideur_dist($cond, $modif = true) {
94
-	if (!$modif) {
95
-		return;
96
-	}
97
-
98
-	// determiner l'objet modifie : forum, article, etc
99
-	if (preg_match(',["\']([a-z_]+)[/"\'],', $cond, $r)) {
100
-		$objet = objet_type($r[1]);
101
-	}
102
-
103
-	// stocker la date_modif_$objet (ne sert a rien pour le moment)
104
-	if (isset($objet)) {
105
-		ecrire_meta('derniere_modif_' . $objet, time());
106
-	}
107
-
108
-	// si $derniere_modif_invalide est un array('article', 'rubrique')
109
-	// n'affecter la meta que si un de ces objets est modifie
110
-	if (is_array($GLOBALS['derniere_modif_invalide'])) {
111
-		if (in_array($objet, $GLOBALS['derniere_modif_invalide'])) {
112
-			ecrire_meta('derniere_modif', time());
113
-		}
114
-	} // sinon, cas standard, toujours affecter la meta
115
-	else {
116
-		ecrire_meta('derniere_modif', time());
117
-	}
94
+    if (!$modif) {
95
+        return;
96
+    }
97
+
98
+    // determiner l'objet modifie : forum, article, etc
99
+    if (preg_match(',["\']([a-z_]+)[/"\'],', $cond, $r)) {
100
+        $objet = objet_type($r[1]);
101
+    }
102
+
103
+    // stocker la date_modif_$objet (ne sert a rien pour le moment)
104
+    if (isset($objet)) {
105
+        ecrire_meta('derniere_modif_' . $objet, time());
106
+    }
107
+
108
+    // si $derniere_modif_invalide est un array('article', 'rubrique')
109
+    // n'affecter la meta que si un de ces objets est modifie
110
+    if (is_array($GLOBALS['derniere_modif_invalide'])) {
111
+        if (in_array($objet, $GLOBALS['derniere_modif_invalide'])) {
112
+            ecrire_meta('derniere_modif', time());
113
+        }
114
+    } // sinon, cas standard, toujours affecter la meta
115
+    else {
116
+        ecrire_meta('derniere_modif', time());
117
+    }
118 118
 }
119 119
 
120 120
 
@@ -139,57 +139,57 @@  discard block
 block discarded – undo
139 139
  *     Nombre de fichiers supprimés
140 140
  **/
141 141
 function purger_repertoire($dir, $options = []) {
142
-	if (!is_dir($dir) or !is_readable($dir)) {
143
-		return 0;
144
-	}
145
-
146
-	// sur certains sites on veut absolument garder certains caches référencés dans un CDN
147
-	// on peut donc inhiber la purge de ces répertoires pour eviter tout probleme
148
-	if (file_exists(rtrim($dir, '/') . '/inhib_purger_repertoire.txt')) {
149
-		return 0;
150
-	}
151
-
152
-	$handle = opendir($dir);
153
-	if (!$handle) {
154
-		return 0;
155
-	}
156
-
157
-	$total = 0;
158
-
159
-	while (($fichier = @readdir($handle)) !== false) {
160
-		// Eviter ".", "..", ".htaccess", ".svn" etc & CACHEDIR.TAG
161
-		if ($fichier[0] == '.' or $fichier == 'CACHEDIR.TAG') {
162
-			continue;
163
-		}
164
-		$chemin = "$dir/$fichier";
165
-		if (is_file($chemin)) {
166
-			if (
167
-				(!isset($options['atime']) or (@fileatime($chemin) < $options['atime']))
168
-				and (!isset($options['mtime']) or (@filemtime($chemin) < $options['mtime']))
169
-			) {
170
-				supprimer_fichier($chemin);
171
-				$total++;
172
-			}
173
-		} else {
174
-			if (is_dir($chemin)) {
175
-				$opts = $options;
176
-				if (isset($options['limit'])) {
177
-					$opts['limit'] = $options['limit'] - $total;
178
-				}
179
-				$total += purger_repertoire($chemin, $opts);
180
-				if (isset($options['subdir']) && $options['subdir']) {
181
-					spip_unlink($chemin);
182
-				}
183
-			}
184
-		}
185
-
186
-		if (isset($options['limit']) and $total >= $options['limit']) {
187
-			break;
188
-		}
189
-	}
190
-	closedir($handle);
191
-
192
-	return $total;
142
+    if (!is_dir($dir) or !is_readable($dir)) {
143
+        return 0;
144
+    }
145
+
146
+    // sur certains sites on veut absolument garder certains caches référencés dans un CDN
147
+    // on peut donc inhiber la purge de ces répertoires pour eviter tout probleme
148
+    if (file_exists(rtrim($dir, '/') . '/inhib_purger_repertoire.txt')) {
149
+        return 0;
150
+    }
151
+
152
+    $handle = opendir($dir);
153
+    if (!$handle) {
154
+        return 0;
155
+    }
156
+
157
+    $total = 0;
158
+
159
+    while (($fichier = @readdir($handle)) !== false) {
160
+        // Eviter ".", "..", ".htaccess", ".svn" etc & CACHEDIR.TAG
161
+        if ($fichier[0] == '.' or $fichier == 'CACHEDIR.TAG') {
162
+            continue;
163
+        }
164
+        $chemin = "$dir/$fichier";
165
+        if (is_file($chemin)) {
166
+            if (
167
+                (!isset($options['atime']) or (@fileatime($chemin) < $options['atime']))
168
+                and (!isset($options['mtime']) or (@filemtime($chemin) < $options['mtime']))
169
+            ) {
170
+                supprimer_fichier($chemin);
171
+                $total++;
172
+            }
173
+        } else {
174
+            if (is_dir($chemin)) {
175
+                $opts = $options;
176
+                if (isset($options['limit'])) {
177
+                    $opts['limit'] = $options['limit'] - $total;
178
+                }
179
+                $total += purger_repertoire($chemin, $opts);
180
+                if (isset($options['subdir']) && $options['subdir']) {
181
+                    spip_unlink($chemin);
182
+                }
183
+            }
184
+        }
185
+
186
+        if (isset($options['limit']) and $total >= $options['limit']) {
187
+            break;
188
+        }
189
+    }
190
+    closedir($handle);
191
+
192
+    return $total;
193 193
 }
194 194
 
195 195
 
@@ -200,26 +200,26 @@  discard block
 block discarded – undo
200 200
 // Securite : est sur que c'est un cache
201 201
 function retire_cache($cache) {
202 202
 
203
-	if (
204
-		preg_match(
205
-			',^([0-9a-f]/)?([0-9]+/)?[0-9a-f]+\.cache(\.gz)?$,i',
206
-			$cache
207
-		)
208
-	) {
209
-		// supprimer le fichier (de facon propre)
210
-		supprimer_fichier(_DIR_CACHE . $cache);
211
-	} else {
212
-		spip_log("Nom de fichier cache incorrect : $cache");
213
-	}
203
+    if (
204
+        preg_match(
205
+            ',^([0-9a-f]/)?([0-9]+/)?[0-9a-f]+\.cache(\.gz)?$,i',
206
+            $cache
207
+        )
208
+    ) {
209
+        // supprimer le fichier (de facon propre)
210
+        supprimer_fichier(_DIR_CACHE . $cache);
211
+    } else {
212
+        spip_log("Nom de fichier cache incorrect : $cache");
213
+    }
214 214
 }
215 215
 
216 216
 // Supprimer les caches marques "x"
217 217
 // A priori dans cette version la fonction ne sera pas appelee, car
218 218
 // la meta est toujours false ; mais evitons un bug si elle est appellee
219 219
 function inc_retire_caches_dist($chemin = '') {
220
-	if (isset($GLOBALS['meta']['invalider_caches'])) {
221
-		effacer_meta('invalider_caches');
222
-	} # concurrence
220
+    if (isset($GLOBALS['meta']['invalider_caches'])) {
221
+        effacer_meta('invalider_caches');
222
+    } # concurrence
223 223
 }
224 224
 
225 225
 #######################################################################
@@ -230,9 +230,9 @@  discard block
 block discarded – undo
230 230
 ##
231 231
 
232 232
 function retire_caches($chemin = '') {
233
-	if ($retire_caches = charger_fonction('retire_caches', 'inc', true)) {
234
-		return $retire_caches($chemin);
235
-	}
233
+    if ($retire_caches = charger_fonction('retire_caches', 'inc', true)) {
234
+        return $retire_caches($chemin);
235
+    }
236 236
 }
237 237
 
238 238
 
@@ -240,10 +240,10 @@  discard block
 block discarded – undo
240 240
 // (note: si absente, n'est pas appellee)
241 241
 
242 242
 function calcul_invalideurs($corps, $primary, &$boucles, $id_boucle) {
243
-	if ($calcul_invalideurs = charger_fonction('calcul_invalideurs', 'inc', true)) {
244
-		return $calcul_invalideurs($corps, $primary, $boucles, $id_boucle);
245
-	}
246
-	return $corps;
243
+    if ($calcul_invalideurs = charger_fonction('calcul_invalideurs', 'inc', true)) {
244
+        return $calcul_invalideurs($corps, $primary, $boucles, $id_boucle);
245
+    }
246
+    return $corps;
247 247
 }
248 248
 
249 249
 
@@ -252,41 +252,41 @@  discard block
 block discarded – undo
252 252
 // invoquee quand on vide tout le cache en bloc (action/purger)
253 253
 //
254 254
 function supprime_invalideurs() {
255
-	if ($supprime_invalideurs = charger_fonction('supprime_invalideurs', 'inc', true)) {
256
-		return $supprime_invalideurs();
257
-	}
255
+    if ($supprime_invalideurs = charger_fonction('supprime_invalideurs', 'inc', true)) {
256
+        return $supprime_invalideurs();
257
+    }
258 258
 }
259 259
 
260 260
 
261 261
 // Calcul des pages : noter dans la base les liens d'invalidation
262 262
 function maj_invalideurs($fichier, &$page) {
263
-	if ($maj_invalideurs = charger_fonction('maj_invalideurs', 'inc', true)) {
264
-		return $maj_invalideurs($fichier, $page);
265
-	}
263
+    if ($maj_invalideurs = charger_fonction('maj_invalideurs', 'inc', true)) {
264
+        return $maj_invalideurs($fichier, $page);
265
+    }
266 266
 }
267 267
 
268 268
 
269 269
 // les invalideurs sont de la forme "objet/id_objet"
270 270
 function insere_invalideur($inval, $fichier) {
271
-	if ($insere_invalideur = charger_fonction('insere_invalideur', 'inc', true)) {
272
-		return $insere_invalideur($inval, $fichier);
273
-	}
271
+    if ($insere_invalideur = charger_fonction('insere_invalideur', 'inc', true)) {
272
+        return $insere_invalideur($inval, $fichier);
273
+    }
274 274
 }
275 275
 
276 276
 //
277 277
 // Marquer les fichiers caches invalides comme etant a supprimer
278 278
 //
279 279
 function applique_invalideur($depart) {
280
-	if ($applique_invalideur = charger_fonction('applique_invalideur', 'inc', true)) {
281
-		return $applique_invalideur($depart);
282
-	}
280
+    if ($applique_invalideur = charger_fonction('applique_invalideur', 'inc', true)) {
281
+        return $applique_invalideur($depart);
282
+    }
283 283
 }
284 284
 
285 285
 //
286 286
 // Invalider les caches liés à telle condition
287 287
 //
288 288
 function suivre_invalideur($cond, $modif = true) {
289
-	if ($suivre_invalideur = charger_fonction('suivre_invalideur', 'inc', true)) {
290
-		return $suivre_invalideur($cond, $modif);
291
-	}
289
+    if ($suivre_invalideur = charger_fonction('suivre_invalideur', 'inc', true)) {
290
+        return $suivre_invalideur($cond, $modif);
291
+    }
292 292
 }
Please login to merge, or discard this patch.
ecrire/inc/charsets.php 2 patches
Indentation   +733 added lines, -733 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 
23 23
 // securité
24 24
 if (!defined('_ECRIRE_INC_VERSION')) {
25
-	return;
25
+    return;
26 26
 }
27 27
 
28 28
 // se faciliter la lecture du charset
@@ -42,45 +42,45 @@  discard block
 block discarded – undo
42 42
  *     - false si le charset n'est pas décrit dans le répertoire charsets/
43 43
  **/
44 44
 function load_charset($charset = 'AUTO') {
45
-	if ($charset == 'AUTO') {
46
-		$charset = $GLOBALS['meta']['charset'];
47
-	}
48
-	$charset = trim(strtolower($charset));
49
-	if (isset($GLOBALS['CHARSET'][$charset])) {
50
-		return $charset;
51
-	}
52
-
53
-	if ($charset == 'utf-8') {
54
-		$GLOBALS['CHARSET'][$charset] = [];
55
-
56
-		return $charset;
57
-	}
58
-
59
-	// Quelques synonymes
60
-	if ($charset == '') {
61
-		$charset = 'iso-8859-1';
62
-	} else {
63
-		if ($charset == 'windows-1250') {
64
-			$charset = 'cp1250';
65
-		} else {
66
-			if ($charset == 'windows-1251') {
67
-				$charset = 'cp1251';
68
-			} else {
69
-				if ($charset == 'windows-1256') {
70
-					$charset = 'cp1256';
71
-				}
72
-			}
73
-		}
74
-	}
75
-
76
-	if (find_in_path($charset . '.php', 'charsets/', true)) {
77
-		return $charset;
78
-	} else {
79
-		spip_log("Erreur: pas de fichier de conversion 'charsets/$charset'");
80
-		$GLOBALS['CHARSET'][$charset] = [];
81
-
82
-		return false;
83
-	}
45
+    if ($charset == 'AUTO') {
46
+        $charset = $GLOBALS['meta']['charset'];
47
+    }
48
+    $charset = trim(strtolower($charset));
49
+    if (isset($GLOBALS['CHARSET'][$charset])) {
50
+        return $charset;
51
+    }
52
+
53
+    if ($charset == 'utf-8') {
54
+        $GLOBALS['CHARSET'][$charset] = [];
55
+
56
+        return $charset;
57
+    }
58
+
59
+    // Quelques synonymes
60
+    if ($charset == '') {
61
+        $charset = 'iso-8859-1';
62
+    } else {
63
+        if ($charset == 'windows-1250') {
64
+            $charset = 'cp1250';
65
+        } else {
66
+            if ($charset == 'windows-1251') {
67
+                $charset = 'cp1251';
68
+            } else {
69
+                if ($charset == 'windows-1256') {
70
+                    $charset = 'cp1256';
71
+                }
72
+            }
73
+        }
74
+    }
75
+
76
+    if (find_in_path($charset . '.php', 'charsets/', true)) {
77
+        return $charset;
78
+    } else {
79
+        spip_log("Erreur: pas de fichier de conversion 'charsets/$charset'");
80
+        $GLOBALS['CHARSET'][$charset] = [];
81
+
82
+        return false;
83
+    }
84 84
 }
85 85
 
86 86
 
@@ -91,31 +91,31 @@  discard block
 block discarded – undo
91 91
  *     true si toutes les fonctions mb nécessaires sont présentes
92 92
  **/
93 93
 function init_mb_string() {
94
-	static $mb;
95
-
96
-	// verifier que tout est present (fonctions mb_string pour php >= 4.0.6)
97
-	// et que le charset interne est connu de mb_string
98
-	if (!$mb) {
99
-		if (
100
-			function_exists('mb_internal_encoding')
101
-			and function_exists('mb_detect_order')
102
-			and function_exists('mb_substr')
103
-			and function_exists('mb_strlen')
104
-			and function_exists('mb_strtolower')
105
-			and function_exists('mb_strtoupper')
106
-			and function_exists('mb_encode_mimeheader')
107
-			and function_exists('mb_encode_numericentity')
108
-			and function_exists('mb_decode_numericentity')
109
-			and mb_detect_order(lire_config('charset', _DEFAULT_CHARSET))
110
-		) {
111
-			mb_internal_encoding('utf-8');
112
-			$mb = 1;
113
-		} else {
114
-			$mb = -1;
115
-		}
116
-	}
117
-
118
-	return ($mb == 1);
94
+    static $mb;
95
+
96
+    // verifier que tout est present (fonctions mb_string pour php >= 4.0.6)
97
+    // et que le charset interne est connu de mb_string
98
+    if (!$mb) {
99
+        if (
100
+            function_exists('mb_internal_encoding')
101
+            and function_exists('mb_detect_order')
102
+            and function_exists('mb_substr')
103
+            and function_exists('mb_strlen')
104
+            and function_exists('mb_strtolower')
105
+            and function_exists('mb_strtoupper')
106
+            and function_exists('mb_encode_mimeheader')
107
+            and function_exists('mb_encode_numericentity')
108
+            and function_exists('mb_decode_numericentity')
109
+            and mb_detect_order(lire_config('charset', _DEFAULT_CHARSET))
110
+        ) {
111
+            mb_internal_encoding('utf-8');
112
+            $mb = 1;
113
+        } else {
114
+            $mb = -1;
115
+        }
116
+    }
117
+
118
+    return ($mb == 1);
119 119
 }
120 120
 
121 121
 /**
@@ -130,21 +130,21 @@  discard block
 block discarded – undo
130 130
  *     true si iconv fonctionne correctement
131 131
  **/
132 132
 function test_iconv() {
133
-	static $iconv_ok;
134
-
135
-	if (!$iconv_ok) {
136
-		if (!function_exists('iconv')) {
137
-			$iconv_ok = -1;
138
-		} else {
139
-			if (utf_32_to_unicode(@iconv('utf-8', 'utf-32', 'chaine de test')) == 'chaine de test') {
140
-				$iconv_ok = 1;
141
-			} else {
142
-				$iconv_ok = -1;
143
-			}
144
-		}
145
-	}
146
-
147
-	return ($iconv_ok == 1);
133
+    static $iconv_ok;
134
+
135
+    if (!$iconv_ok) {
136
+        if (!function_exists('iconv')) {
137
+            $iconv_ok = -1;
138
+        } else {
139
+            if (utf_32_to_unicode(@iconv('utf-8', 'utf-32', 'chaine de test')) == 'chaine de test') {
140
+                $iconv_ok = 1;
141
+            } else {
142
+                $iconv_ok = -1;
143
+            }
144
+        }
145
+    }
146
+
147
+    return ($iconv_ok == 1);
148 148
 }
149 149
 
150 150
 
@@ -157,18 +157,18 @@  discard block
 block discarded – undo
157 157
  *     true si PCRE supporte l'UTF-8 correctement
158 158
  **/
159 159
 function test_pcre_unicode() {
160
-	static $pcre_ok = 0;
161
-
162
-	if (!$pcre_ok) {
163
-		$s = ' ' . chr(195) . chr(169) . 't' . chr(195) . chr(169) . ' ';
164
-		if (preg_match(',\W...\W,u', $s)) {
165
-			$pcre_ok = 1;
166
-		} else {
167
-			$pcre_ok = -1;
168
-		}
169
-	}
170
-
171
-	return $pcre_ok == 1;
160
+    static $pcre_ok = 0;
161
+
162
+    if (!$pcre_ok) {
163
+        $s = ' ' . chr(195) . chr(169) . 't' . chr(195) . chr(169) . ' ';
164
+        if (preg_match(',\W...\W,u', $s)) {
165
+            $pcre_ok = 1;
166
+        } else {
167
+            $pcre_ok = -1;
168
+        }
169
+    }
170
+
171
+    return $pcre_ok == 1;
172 172
 }
173 173
 
174 174
 /**
@@ -184,22 +184,22 @@  discard block
 block discarded – undo
184 184
  *    Plage de caractères
185 185
  **/
186 186
 function pcre_lettres_unicode() {
187
-	static $plage_unicode;
188
-
189
-	if (!$plage_unicode) {
190
-		if (test_pcre_unicode()) {
191
-			// cf. http://www.unicode.org/charts/
192
-			$plage_unicode = '\w' // iso-latin
193
-				. '\x{100}-\x{24f}' // europeen etendu
194
-				. '\x{300}-\x{1cff}' // des tas de trucs
195
-			;
196
-		} else {
197
-			// fallback a trois sous
198
-			$plage_unicode = '\w';
199
-		}
200
-	}
201
-
202
-	return $plage_unicode;
187
+    static $plage_unicode;
188
+
189
+    if (!$plage_unicode) {
190
+        if (test_pcre_unicode()) {
191
+            // cf. http://www.unicode.org/charts/
192
+            $plage_unicode = '\w' // iso-latin
193
+                . '\x{100}-\x{24f}' // europeen etendu
194
+                . '\x{300}-\x{1cff}' // des tas de trucs
195
+            ;
196
+        } else {
197
+            // fallback a trois sous
198
+            $plage_unicode = '\w';
199
+        }
200
+    }
201
+
202
+    return $plage_unicode;
203 203
 }
204 204
 
205 205
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
  *    Plage de caractères
218 218
  **/
219 219
 function plage_punct_unicode() {
220
-	return '\xE2(\x80[\x80-\xBF]|\x81[\x80-\xAF])';
220
+    return '\xE2(\x80[\x80-\xBF]|\x81[\x80-\xAF])';
221 221
 }
222 222
 
223 223
 /**
@@ -237,75 +237,75 @@  discard block
 block discarded – undo
237 237
  *     Texte corrigé
238 238
  **/
239 239
 function corriger_caracteres_windows($texte, $charset = 'AUTO', $charset_cible = 'unicode') {
240
-	static $trans;
241
-
242
-	if (is_array($texte)) {
243
-		return array_map('corriger_caracteres_windows', $texte);
244
-	}
245
-
246
-	if ($charset == 'AUTO') {
247
-		$charset = lire_config('charset', _DEFAULT_CHARSET);
248
-	}
249
-	if ($charset == 'utf-8') {
250
-		$p = chr(194);
251
-		if (strpos($texte, $p) == false) {
252
-			return $texte;
253
-		}
254
-	} else {
255
-		if ($charset == 'iso-8859-1') {
256
-			$p = '';
257
-		} else {
258
-			return $texte;
259
-		}
260
-	}
261
-
262
-	if (!isset($trans[$charset][$charset_cible])) {
263
-		$trans[$charset][$charset_cible] = [
264
-			$p . chr(128) => '&#8364;',
265
-			$p . chr(129) => ' ', # pas affecte
266
-			$p . chr(130) => '&#8218;',
267
-			$p . chr(131) => '&#402;',
268
-			$p . chr(132) => '&#8222;',
269
-			$p . chr(133) => '&#8230;',
270
-			$p . chr(134) => '&#8224;',
271
-			$p . chr(135) => '&#8225;',
272
-			$p . chr(136) => '&#710;',
273
-			$p . chr(137) => '&#8240;',
274
-			$p . chr(138) => '&#352;',
275
-			$p . chr(139) => '&#8249;',
276
-			$p . chr(140) => '&#338;',
277
-			$p . chr(141) => ' ', # pas affecte
278
-			$p . chr(142) => '&#381;',
279
-			$p . chr(143) => ' ', # pas affecte
280
-			$p . chr(144) => ' ', # pas affecte
281
-			$p . chr(145) => '&#8216;',
282
-			$p . chr(146) => '&#8217;',
283
-			$p . chr(147) => '&#8220;',
284
-			$p . chr(148) => '&#8221;',
285
-			$p . chr(149) => '&#8226;',
286
-			$p . chr(150) => '&#8211;',
287
-			$p . chr(151) => '&#8212;',
288
-			$p . chr(152) => '&#732;',
289
-			$p . chr(153) => '&#8482;',
290
-			$p . chr(154) => '&#353;',
291
-			$p . chr(155) => '&#8250;',
292
-			$p . chr(156) => '&#339;',
293
-			$p . chr(157) => ' ', # pas affecte
294
-			$p . chr(158) => '&#382;',
295
-			$p . chr(159) => '&#376;',
296
-		];
297
-		if ($charset_cible != 'unicode') {
298
-			foreach ($trans[$charset][$charset_cible] as $k => $c) {
299
-				$trans[$charset][$charset_cible][$k] = unicode2charset($c, $charset_cible);
300
-			}
301
-		}
302
-	}
303
-
304
-	return @str_replace(
305
-		array_keys($trans[$charset][$charset_cible]),
306
-		array_values($trans[$charset][$charset_cible]),
307
-		$texte
308
-	);
240
+    static $trans;
241
+
242
+    if (is_array($texte)) {
243
+        return array_map('corriger_caracteres_windows', $texte);
244
+    }
245
+
246
+    if ($charset == 'AUTO') {
247
+        $charset = lire_config('charset', _DEFAULT_CHARSET);
248
+    }
249
+    if ($charset == 'utf-8') {
250
+        $p = chr(194);
251
+        if (strpos($texte, $p) == false) {
252
+            return $texte;
253
+        }
254
+    } else {
255
+        if ($charset == 'iso-8859-1') {
256
+            $p = '';
257
+        } else {
258
+            return $texte;
259
+        }
260
+    }
261
+
262
+    if (!isset($trans[$charset][$charset_cible])) {
263
+        $trans[$charset][$charset_cible] = [
264
+            $p . chr(128) => '&#8364;',
265
+            $p . chr(129) => ' ', # pas affecte
266
+            $p . chr(130) => '&#8218;',
267
+            $p . chr(131) => '&#402;',
268
+            $p . chr(132) => '&#8222;',
269
+            $p . chr(133) => '&#8230;',
270
+            $p . chr(134) => '&#8224;',
271
+            $p . chr(135) => '&#8225;',
272
+            $p . chr(136) => '&#710;',
273
+            $p . chr(137) => '&#8240;',
274
+            $p . chr(138) => '&#352;',
275
+            $p . chr(139) => '&#8249;',
276
+            $p . chr(140) => '&#338;',
277
+            $p . chr(141) => ' ', # pas affecte
278
+            $p . chr(142) => '&#381;',
279
+            $p . chr(143) => ' ', # pas affecte
280
+            $p . chr(144) => ' ', # pas affecte
281
+            $p . chr(145) => '&#8216;',
282
+            $p . chr(146) => '&#8217;',
283
+            $p . chr(147) => '&#8220;',
284
+            $p . chr(148) => '&#8221;',
285
+            $p . chr(149) => '&#8226;',
286
+            $p . chr(150) => '&#8211;',
287
+            $p . chr(151) => '&#8212;',
288
+            $p . chr(152) => '&#732;',
289
+            $p . chr(153) => '&#8482;',
290
+            $p . chr(154) => '&#353;',
291
+            $p . chr(155) => '&#8250;',
292
+            $p . chr(156) => '&#339;',
293
+            $p . chr(157) => ' ', # pas affecte
294
+            $p . chr(158) => '&#382;',
295
+            $p . chr(159) => '&#376;',
296
+        ];
297
+        if ($charset_cible != 'unicode') {
298
+            foreach ($trans[$charset][$charset_cible] as $k => $c) {
299
+                $trans[$charset][$charset_cible][$k] = unicode2charset($c, $charset_cible);
300
+            }
301
+        }
302
+    }
303
+
304
+    return @str_replace(
305
+        array_keys($trans[$charset][$charset_cible]),
306
+        array_values($trans[$charset][$charset_cible]),
307
+        $texte
308
+    );
309 309
 }
310 310
 
311 311
 
@@ -322,26 +322,26 @@  discard block
 block discarded – undo
322 322
  *     Texte converti
323 323
  **/
324 324
 function html2unicode($texte, $secure = false) {
325
-	if (strpos($texte, '&') === false) {
326
-		return $texte;
327
-	}
328
-	static $trans = [];
329
-	if (!$trans) {
330
-		load_charset('html');
331
-		foreach ($GLOBALS['CHARSET']['html'] as $key => $val) {
332
-			$trans["&$key;"] = $val;
333
-		}
334
-	}
335
-
336
-	if ($secure) {
337
-		return str_replace(array_keys($trans), array_values($trans), $texte);
338
-	} else {
339
-		return str_replace(
340
-			['&amp;', '&quot;', '&lt;', '&gt;'],
341
-			['&', '"', '<', '>'],
342
-			str_replace(array_keys($trans), array_values($trans), $texte)
343
-		);
344
-	}
325
+    if (strpos($texte, '&') === false) {
326
+        return $texte;
327
+    }
328
+    static $trans = [];
329
+    if (!$trans) {
330
+        load_charset('html');
331
+        foreach ($GLOBALS['CHARSET']['html'] as $key => $val) {
332
+            $trans["&$key;"] = $val;
333
+        }
334
+    }
335
+
336
+    if ($secure) {
337
+        return str_replace(array_keys($trans), array_values($trans), $texte);
338
+    } else {
339
+        return str_replace(
340
+            ['&amp;', '&quot;', '&lt;', '&gt;'],
341
+            ['&', '"', '<', '>'],
342
+            str_replace(array_keys($trans), array_values($trans), $texte)
343
+        );
344
+    }
345 345
 }
346 346
 
347 347
 
@@ -356,16 +356,16 @@  discard block
 block discarded – undo
356 356
  *     Texte converti
357 357
  **/
358 358
 function mathml2unicode($texte) {
359
-	static $trans;
360
-	if (!$trans) {
361
-		load_charset('mathml');
359
+    static $trans;
360
+    if (!$trans) {
361
+        load_charset('mathml');
362 362
 
363
-		foreach ($GLOBALS['CHARSET']['mathml'] as $key => $val) {
364
-			$trans["&$key;"] = $val;
365
-		}
366
-	}
363
+        foreach ($GLOBALS['CHARSET']['mathml'] as $key => $val) {
364
+            $trans["&$key;"] = $val;
365
+        }
366
+    }
367 367
 
368
-	return str_replace(array_keys($trans), array_values($trans), $texte);
368
+    return str_replace(array_keys($trans), array_values($trans), $texte);
369 369
 }
370 370
 
371 371
 
@@ -387,75 +387,75 @@  discard block
 block discarded – undo
387 387
  *     Texte converti en unicode
388 388
  **/
389 389
 function charset2unicode($texte, $charset = 'AUTO' /* $forcer: obsolete*/) {
390
-	static $trans;
391
-
392
-	if ($charset == 'AUTO') {
393
-		$charset = lire_config('charset', _DEFAULT_CHARSET);
394
-	}
395
-
396
-	if ($charset == '') {
397
-		$charset = 'iso-8859-1';
398
-	}
399
-	$charset = strtolower($charset);
400
-
401
-	switch ($charset) {
402
-		case 'utf-8':
403
-		case 'utf8':
404
-			return utf_8_to_unicode($texte);
405
-
406
-		case 'iso-8859-1':
407
-			$texte = corriger_caracteres_windows($texte, 'iso-8859-1');
408
-		// pas de break; ici, on suit sur default:
409
-
410
-		default:
411
-			// mbstring presente ?
412
-			if (init_mb_string()) {
413
-				$order = mb_detect_order();
414
-				try {
415
-					# mb_string connait-il $charset?
416
-					if ($order and mb_detect_order($charset)) {
417
-						$s = mb_convert_encoding($texte, 'utf-8', $charset);
418
-						if ($s && $s != $texte) {
419
-							return utf_8_to_unicode($s);
420
-						}
421
-					}
422
-				} catch (\Error $e) {
423
-					// Le charset n'existe probablement pas
424
-				} finally {
425
-					mb_detect_order($order); # remettre comme precedemment
426
-				}
427
-			}
428
-
429
-			// Sinon, peut-etre connaissons-nous ce charset ?
430
-			if (!isset($trans[$charset])) {
431
-				if (
432
-					$cset = load_charset($charset)
433
-					and is_array($GLOBALS['CHARSET'][$cset])
434
-				) {
435
-					foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
436
-						$trans[$charset][chr($key)] = '&#' . $val . ';';
437
-					}
438
-				}
439
-			}
440
-			if (isset($trans[$charset]) and is_countable($trans[$charset]) ? count($trans[$charset]) : 0) {
441
-				return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
442
-			}
443
-
444
-			// Sinon demander a iconv (malgre le fait qu'il coupe quand un
445
-			// caractere n'appartient pas au charset, mais c'est un probleme
446
-			// surtout en utf-8, gere ci-dessus)
447
-			if (test_iconv()) {
448
-				$s = iconv($charset, 'utf-32le', $texte);
449
-				if ($s) {
450
-					return utf_32_to_unicode($s);
451
-				}
452
-			}
453
-
454
-			// Au pire ne rien faire
455
-			spip_log("erreur charset '$charset' non supporte");
456
-
457
-			return $texte;
458
-	}
390
+    static $trans;
391
+
392
+    if ($charset == 'AUTO') {
393
+        $charset = lire_config('charset', _DEFAULT_CHARSET);
394
+    }
395
+
396
+    if ($charset == '') {
397
+        $charset = 'iso-8859-1';
398
+    }
399
+    $charset = strtolower($charset);
400
+
401
+    switch ($charset) {
402
+        case 'utf-8':
403
+        case 'utf8':
404
+            return utf_8_to_unicode($texte);
405
+
406
+        case 'iso-8859-1':
407
+            $texte = corriger_caracteres_windows($texte, 'iso-8859-1');
408
+        // pas de break; ici, on suit sur default:
409
+
410
+        default:
411
+            // mbstring presente ?
412
+            if (init_mb_string()) {
413
+                $order = mb_detect_order();
414
+                try {
415
+                    # mb_string connait-il $charset?
416
+                    if ($order and mb_detect_order($charset)) {
417
+                        $s = mb_convert_encoding($texte, 'utf-8', $charset);
418
+                        if ($s && $s != $texte) {
419
+                            return utf_8_to_unicode($s);
420
+                        }
421
+                    }
422
+                } catch (\Error $e) {
423
+                    // Le charset n'existe probablement pas
424
+                } finally {
425
+                    mb_detect_order($order); # remettre comme precedemment
426
+                }
427
+            }
428
+
429
+            // Sinon, peut-etre connaissons-nous ce charset ?
430
+            if (!isset($trans[$charset])) {
431
+                if (
432
+                    $cset = load_charset($charset)
433
+                    and is_array($GLOBALS['CHARSET'][$cset])
434
+                ) {
435
+                    foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
436
+                        $trans[$charset][chr($key)] = '&#' . $val . ';';
437
+                    }
438
+                }
439
+            }
440
+            if (isset($trans[$charset]) and is_countable($trans[$charset]) ? count($trans[$charset]) : 0) {
441
+                return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
442
+            }
443
+
444
+            // Sinon demander a iconv (malgre le fait qu'il coupe quand un
445
+            // caractere n'appartient pas au charset, mais c'est un probleme
446
+            // surtout en utf-8, gere ci-dessus)
447
+            if (test_iconv()) {
448
+                $s = iconv($charset, 'utf-32le', $texte);
449
+                if ($s) {
450
+                    return utf_32_to_unicode($s);
451
+                }
452
+            }
453
+
454
+            // Au pire ne rien faire
455
+            spip_log("erreur charset '$charset' non supporte");
456
+
457
+            return $texte;
458
+    }
459 459
 }
460 460
 
461 461
 
@@ -474,44 +474,44 @@  discard block
 block discarded – undo
474 474
  *     Texte transformé dans le charset souhaité
475 475
  **/
476 476
 function unicode2charset($texte, $charset = 'AUTO') {
477
-	static $CHARSET_REVERSE = [];
478
-	static $trans = [];
479
-
480
-	if ($charset == 'AUTO') {
481
-		$charset = lire_config('charset', _DEFAULT_CHARSET);
482
-	}
483
-
484
-	switch ($charset) {
485
-		case 'utf-8':
486
-			return unicode_to_utf_8($texte);
487
-			break;
488
-
489
-		default:
490
-			$charset = load_charset($charset);
491
-
492
-			if (empty($CHARSET_REVERSE[$charset])) {
493
-				$CHARSET_REVERSE[$charset] = array_flip($GLOBALS['CHARSET'][$charset]);
494
-			}
495
-
496
-			if (!isset($trans[$charset])) {
497
-				$trans[$charset] = [];
498
-				$t = &$trans[$charset];
499
-				for ($e = 128; $e < 255; $e++) {
500
-					$h = dechex($e);
501
-					if ($s = isset($CHARSET_REVERSE[$charset][$e])) {
502
-						$s = $CHARSET_REVERSE[$charset][$e];
503
-						$t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($s);
504
-						$t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($s);
505
-					} else {
506
-						$t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($e);
507
-						$t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($e);
508
-					}
509
-				}
510
-			}
511
-			$texte = str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
512
-
513
-			return $texte;
514
-	}
477
+    static $CHARSET_REVERSE = [];
478
+    static $trans = [];
479
+
480
+    if ($charset == 'AUTO') {
481
+        $charset = lire_config('charset', _DEFAULT_CHARSET);
482
+    }
483
+
484
+    switch ($charset) {
485
+        case 'utf-8':
486
+            return unicode_to_utf_8($texte);
487
+            break;
488
+
489
+        default:
490
+            $charset = load_charset($charset);
491
+
492
+            if (empty($CHARSET_REVERSE[$charset])) {
493
+                $CHARSET_REVERSE[$charset] = array_flip($GLOBALS['CHARSET'][$charset]);
494
+            }
495
+
496
+            if (!isset($trans[$charset])) {
497
+                $trans[$charset] = [];
498
+                $t = &$trans[$charset];
499
+                for ($e = 128; $e < 255; $e++) {
500
+                    $h = dechex($e);
501
+                    if ($s = isset($CHARSET_REVERSE[$charset][$e])) {
502
+                        $s = $CHARSET_REVERSE[$charset][$e];
503
+                        $t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($s);
504
+                        $t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($s);
505
+                    } else {
506
+                        $t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($e);
507
+                        $t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($e);
508
+                    }
509
+                }
510
+            }
511
+            $texte = str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
512
+
513
+            return $texte;
514
+    }
515 515
 }
516 516
 
517 517
 
@@ -529,40 +529,40 @@  discard block
 block discarded – undo
529 529
  *     Texte transformé dans le charset site
530 530
  **/
531 531
 function importer_charset($texte, $charset = 'AUTO') {
532
-	$s = null;
533
-	static $trans = [];
534
-	// on traite le cas le plus frequent iso-8859-1 vers utf directement pour aller plus vite !
535
-	if (($charset == 'iso-8859-1') && ($GLOBALS['meta']['charset'] == 'utf-8')) {
536
-		$texte = corriger_caracteres_windows($texte, 'iso-8859-1', $GLOBALS['meta']['charset']);
537
-		if (init_mb_string()) {
538
-			if (
539
-				$order = mb_detect_order() # mb_string connait-il $charset?
540
-				and mb_detect_order($charset)
541
-			) {
542
-				$s = mb_convert_encoding($texte, 'utf-8', $charset);
543
-			}
544
-			mb_detect_order($order); # remettre comme precedemment
545
-			return $s;
546
-		}
547
-		// Sinon, peut-etre connaissons-nous ce charset ?
548
-		if (!isset($trans[$charset])) {
549
-			if (
550
-				$cset = load_charset($charset)
551
-				and is_array($GLOBALS['CHARSET'][$cset])
552
-			) {
553
-				foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
554
-					$trans[$charset][chr($key)] = unicode2charset('&#' . $val . ';');
555
-				}
556
-			}
557
-		}
558
-		if (is_countable($trans[$charset]) ? count($trans[$charset]) : 0) {
559
-			return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
560
-		}
561
-
562
-		return $texte;
563
-	}
564
-
565
-	return unicode2charset(charset2unicode($texte, $charset));
532
+    $s = null;
533
+    static $trans = [];
534
+    // on traite le cas le plus frequent iso-8859-1 vers utf directement pour aller plus vite !
535
+    if (($charset == 'iso-8859-1') && ($GLOBALS['meta']['charset'] == 'utf-8')) {
536
+        $texte = corriger_caracteres_windows($texte, 'iso-8859-1', $GLOBALS['meta']['charset']);
537
+        if (init_mb_string()) {
538
+            if (
539
+                $order = mb_detect_order() # mb_string connait-il $charset?
540
+                and mb_detect_order($charset)
541
+            ) {
542
+                $s = mb_convert_encoding($texte, 'utf-8', $charset);
543
+            }
544
+            mb_detect_order($order); # remettre comme precedemment
545
+            return $s;
546
+        }
547
+        // Sinon, peut-etre connaissons-nous ce charset ?
548
+        if (!isset($trans[$charset])) {
549
+            if (
550
+                $cset = load_charset($charset)
551
+                and is_array($GLOBALS['CHARSET'][$cset])
552
+            ) {
553
+                foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
554
+                    $trans[$charset][chr($key)] = unicode2charset('&#' . $val . ';');
555
+                }
556
+            }
557
+        }
558
+        if (is_countable($trans[$charset]) ? count($trans[$charset]) : 0) {
559
+            return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
560
+        }
561
+
562
+        return $texte;
563
+    }
564
+
565
+    return unicode2charset(charset2unicode($texte, $charset));
566 566
 }
567 567
 
568 568
 
@@ -578,92 +578,92 @@  discard block
 block discarded – undo
578 578
  **/
579 579
 function utf_8_to_unicode($source) {
580 580
 
581
-	// mb_string : methode rapide
582
-	if (init_mb_string()) {
583
-		$convmap = [0x7F, 0xFFFFFF, 0x0, 0xFFFFFF];
584
-
585
-		return mb_encode_numericentity($source, $convmap, 'UTF-8');
586
-	}
587
-
588
-	// Sinon methode pas a pas
589
-	static $decrement;
590
-	static $shift;
591
-
592
-	// Cf. php.net, par Ronen. Adapte pour compatibilite < php4
593
-	if (!is_array($decrement)) {
594
-		// array used to figure what number to decrement from character order value
595
-		// according to number of characters used to map unicode to ascii by utf-8
596
-		$decrement[4] = 240;
597
-		$decrement[3] = 224;
598
-		$decrement[2] = 192;
599
-		$decrement[1] = 0;
600
-		// the number of bits to shift each charNum by
601
-		$shift[1][0] = 0;
602
-		$shift[2][0] = 6;
603
-		$shift[2][1] = 0;
604
-		$shift[3][0] = 12;
605
-		$shift[3][1] = 6;
606
-		$shift[3][2] = 0;
607
-		$shift[4][0] = 18;
608
-		$shift[4][1] = 12;
609
-		$shift[4][2] = 6;
610
-		$shift[4][3] = 0;
611
-	}
612
-
613
-	$pos = 0;
614
-	$len = strlen($source);
615
-	$encodedString = '';
616
-	while ($pos < $len) {
617
-		$char = '';
618
-		$ischar = false;
619
-		$asciiPos = ord(substr($source, $pos, 1));
620
-		if (($asciiPos >= 240) && ($asciiPos <= 255)) {
621
-			// 4 chars representing one unicode character
622
-			$thisLetter = substr($source, $pos, 4);
623
-			$pos += 4;
624
-		} else {
625
-			if (($asciiPos >= 224) && ($asciiPos <= 239)) {
626
-				// 3 chars representing one unicode character
627
-				$thisLetter = substr($source, $pos, 3);
628
-				$pos += 3;
629
-			} else {
630
-				if (($asciiPos >= 192) && ($asciiPos <= 223)) {
631
-					// 2 chars representing one unicode character
632
-					$thisLetter = substr($source, $pos, 2);
633
-					$pos += 2;
634
-				} else {
635
-					// 1 char (lower ascii)
636
-					$thisLetter = substr($source, $pos, 1);
637
-					$pos += 1;
638
-					$char = $thisLetter;
639
-					$ischar = true;
640
-				}
641
-			}
642
-		}
643
-
644
-		if ($ischar) {
645
-			$encodedString .= $char;
646
-		} else {  // process the string representing the letter to a unicode entity
647
-			$thisLen = strlen($thisLetter);
648
-			$thisPos = 0;
649
-			$decimalCode = 0;
650
-			while ($thisPos < $thisLen) {
651
-				$thisCharOrd = ord(substr($thisLetter, $thisPos, 1));
652
-				if ($thisPos == 0) {
653
-					$charNum = intval($thisCharOrd - $decrement[$thisLen]);
654
-					$decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
655
-				} else {
656
-					$charNum = intval($thisCharOrd - 128);
657
-					$decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
658
-				}
659
-				$thisPos++;
660
-			}
661
-			$encodedLetter = '&#' . preg_replace('/^0+/', '', $decimalCode) . ';';
662
-			$encodedString .= $encodedLetter;
663
-		}
664
-	}
665
-
666
-	return $encodedString;
581
+    // mb_string : methode rapide
582
+    if (init_mb_string()) {
583
+        $convmap = [0x7F, 0xFFFFFF, 0x0, 0xFFFFFF];
584
+
585
+        return mb_encode_numericentity($source, $convmap, 'UTF-8');
586
+    }
587
+
588
+    // Sinon methode pas a pas
589
+    static $decrement;
590
+    static $shift;
591
+
592
+    // Cf. php.net, par Ronen. Adapte pour compatibilite < php4
593
+    if (!is_array($decrement)) {
594
+        // array used to figure what number to decrement from character order value
595
+        // according to number of characters used to map unicode to ascii by utf-8
596
+        $decrement[4] = 240;
597
+        $decrement[3] = 224;
598
+        $decrement[2] = 192;
599
+        $decrement[1] = 0;
600
+        // the number of bits to shift each charNum by
601
+        $shift[1][0] = 0;
602
+        $shift[2][0] = 6;
603
+        $shift[2][1] = 0;
604
+        $shift[3][0] = 12;
605
+        $shift[3][1] = 6;
606
+        $shift[3][2] = 0;
607
+        $shift[4][0] = 18;
608
+        $shift[4][1] = 12;
609
+        $shift[4][2] = 6;
610
+        $shift[4][3] = 0;
611
+    }
612
+
613
+    $pos = 0;
614
+    $len = strlen($source);
615
+    $encodedString = '';
616
+    while ($pos < $len) {
617
+        $char = '';
618
+        $ischar = false;
619
+        $asciiPos = ord(substr($source, $pos, 1));
620
+        if (($asciiPos >= 240) && ($asciiPos <= 255)) {
621
+            // 4 chars representing one unicode character
622
+            $thisLetter = substr($source, $pos, 4);
623
+            $pos += 4;
624
+        } else {
625
+            if (($asciiPos >= 224) && ($asciiPos <= 239)) {
626
+                // 3 chars representing one unicode character
627
+                $thisLetter = substr($source, $pos, 3);
628
+                $pos += 3;
629
+            } else {
630
+                if (($asciiPos >= 192) && ($asciiPos <= 223)) {
631
+                    // 2 chars representing one unicode character
632
+                    $thisLetter = substr($source, $pos, 2);
633
+                    $pos += 2;
634
+                } else {
635
+                    // 1 char (lower ascii)
636
+                    $thisLetter = substr($source, $pos, 1);
637
+                    $pos += 1;
638
+                    $char = $thisLetter;
639
+                    $ischar = true;
640
+                }
641
+            }
642
+        }
643
+
644
+        if ($ischar) {
645
+            $encodedString .= $char;
646
+        } else {  // process the string representing the letter to a unicode entity
647
+            $thisLen = strlen($thisLetter);
648
+            $thisPos = 0;
649
+            $decimalCode = 0;
650
+            while ($thisPos < $thisLen) {
651
+                $thisCharOrd = ord(substr($thisLetter, $thisPos, 1));
652
+                if ($thisPos == 0) {
653
+                    $charNum = intval($thisCharOrd - $decrement[$thisLen]);
654
+                    $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
655
+                } else {
656
+                    $charNum = intval($thisCharOrd - 128);
657
+                    $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
658
+                }
659
+                $thisPos++;
660
+            }
661
+            $encodedLetter = '&#' . preg_replace('/^0+/', '', $decimalCode) . ';';
662
+            $encodedString .= $encodedLetter;
663
+        }
664
+    }
665
+
666
+    return $encodedString;
667 667
 }
668 668
 
669 669
 /**
@@ -682,32 +682,32 @@  discard block
 block discarded – undo
682 682
  **/
683 683
 function utf_32_to_unicode($source) {
684 684
 
685
-	// mb_string : methode rapide
686
-	if (init_mb_string()) {
687
-		$convmap = [0x7F, 0xFFFFFF, 0x0, 0xFFFFFF];
688
-		$source = mb_encode_numericentity($source, $convmap, 'UTF-32LE');
689
-
690
-		return str_replace(chr(0), '', $source);
691
-	}
692
-
693
-	// Sinon methode lente
694
-	$texte = '';
695
-	while ($source) {
696
-		$words = unpack('V*', substr($source, 0, 1024));
697
-		$source = substr($source, 1024);
698
-		foreach ($words as $word) {
699
-			if ($word < 128) {
700
-				$texte .= chr($word);
701
-			} // ignorer le BOM - http://www.unicode.org/faq/utf_bom.html
702
-			else {
703
-				if ($word != 65279) {
704
-					$texte .= '&#' . $word . ';';
705
-				}
706
-			}
707
-		}
708
-	}
709
-
710
-	return $texte;
685
+    // mb_string : methode rapide
686
+    if (init_mb_string()) {
687
+        $convmap = [0x7F, 0xFFFFFF, 0x0, 0xFFFFFF];
688
+        $source = mb_encode_numericentity($source, $convmap, 'UTF-32LE');
689
+
690
+        return str_replace(chr(0), '', $source);
691
+    }
692
+
693
+    // Sinon methode lente
694
+    $texte = '';
695
+    while ($source) {
696
+        $words = unpack('V*', substr($source, 0, 1024));
697
+        $source = substr($source, 1024);
698
+        foreach ($words as $word) {
699
+            if ($word < 128) {
700
+                $texte .= chr($word);
701
+            } // ignorer le BOM - http://www.unicode.org/faq/utf_bom.html
702
+            else {
703
+                if ($word != 65279) {
704
+                    $texte .= '&#' . $word . ';';
705
+                }
706
+            }
707
+        }
708
+    }
709
+
710
+    return $texte;
711 711
 }
712 712
 
713 713
 
@@ -724,21 +724,21 @@  discard block
 block discarded – undo
724 724
  *    Caractère utf8 si trouvé, '' sinon
725 725
  **/
726 726
 function caractere_utf_8($num) {
727
-	$num = intval($num);
728
-	if ($num < 128) {
729
-		return chr($num);
730
-	}
731
-	if ($num < 2048) {
732
-		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
733
-	}
734
-	if ($num < 65536) {
735
-		return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
736
-	}
737
-	if ($num < 1_114_112) {
738
-		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
739
-	}
740
-
741
-	return '';
727
+    $num = intval($num);
728
+    if ($num < 128) {
729
+        return chr($num);
730
+    }
731
+    if ($num < 2048) {
732
+        return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
733
+    }
734
+    if ($num < 65536) {
735
+        return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
736
+    }
737
+    if ($num < 1_114_112) {
738
+        return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
739
+    }
740
+
741
+    return '';
742 742
 }
743 743
 
744 744
 /**
@@ -751,42 +751,42 @@  discard block
 block discarded – undo
751 751
  **/
752 752
 function unicode_to_utf_8($texte) {
753 753
 
754
-	// 1. Entites &#128; et suivantes
755
-	$vu = [];
756
-	if (
757
-		preg_match_all(
758
-			',&#0*([1-9][0-9][0-9]+);,S',
759
-			$texte,
760
-			$regs,
761
-			PREG_SET_ORDER
762
-		)
763
-	) {
764
-		foreach ($regs as $reg) {
765
-			if ($reg[1] > 127 and !isset($vu[$reg[0]])) {
766
-				$vu[$reg[0]] = caractere_utf_8($reg[1]);
767
-			}
768
-		}
769
-	}
770
-	//$texte = str_replace(array_keys($vu), array_values($vu), $texte);
771
-
772
-	// 2. Entites > &#xFF;
773
-	//$vu = array();
774
-	if (
775
-		preg_match_all(
776
-			',&#x0*([1-9a-f][0-9a-f][0-9a-f]+);,iS',
777
-			$texte,
778
-			$regs,
779
-			PREG_SET_ORDER
780
-		)
781
-	) {
782
-		foreach ($regs as $reg) {
783
-			if (!isset($vu[$reg[0]])) {
784
-				$vu[$reg[0]] = caractere_utf_8(hexdec($reg[1]));
785
-			}
786
-		}
787
-	}
788
-
789
-	return str_replace(array_keys($vu), array_values($vu), $texte);
754
+    // 1. Entites &#128; et suivantes
755
+    $vu = [];
756
+    if (
757
+        preg_match_all(
758
+            ',&#0*([1-9][0-9][0-9]+);,S',
759
+            $texte,
760
+            $regs,
761
+            PREG_SET_ORDER
762
+        )
763
+    ) {
764
+        foreach ($regs as $reg) {
765
+            if ($reg[1] > 127 and !isset($vu[$reg[0]])) {
766
+                $vu[$reg[0]] = caractere_utf_8($reg[1]);
767
+            }
768
+        }
769
+    }
770
+    //$texte = str_replace(array_keys($vu), array_values($vu), $texte);
771
+
772
+    // 2. Entites > &#xFF;
773
+    //$vu = array();
774
+    if (
775
+        preg_match_all(
776
+            ',&#x0*([1-9a-f][0-9a-f][0-9a-f]+);,iS',
777
+            $texte,
778
+            $regs,
779
+            PREG_SET_ORDER
780
+        )
781
+    ) {
782
+        foreach ($regs as $reg) {
783
+            if (!isset($vu[$reg[0]])) {
784
+                $vu[$reg[0]] = caractere_utf_8(hexdec($reg[1]));
785
+            }
786
+        }
787
+    }
788
+
789
+    return str_replace(array_keys($vu), array_values($vu), $texte);
790 790
 }
791 791
 
792 792
 /**
@@ -798,15 +798,15 @@  discard block
 block discarded – undo
798 798
  *     Texte converti
799 799
  **/
800 800
 function unicode_to_javascript($texte) {
801
-	$vu = [];
802
-	while (preg_match(',&#0*([0-9]+);,S', $texte, $regs) and !isset($vu[$regs[1]])) {
803
-		$num = $regs[1];
804
-		$vu[$num] = true;
805
-		$s = '\u' . sprintf('%04x', $num);
806
-		$texte = str_replace($regs[0], $s, $texte);
807
-	}
808
-
809
-	return $texte;
801
+    $vu = [];
802
+    while (preg_match(',&#0*([0-9]+);,S', $texte, $regs) and !isset($vu[$regs[1]])) {
803
+        $num = $regs[1];
804
+        $vu[$num] = true;
805
+        $s = '\u' . sprintf('%04x', $num);
806
+        $texte = str_replace($regs[0], $s, $texte);
807
+    }
808
+
809
+    return $texte;
810 810
 }
811 811
 
812 812
 /**
@@ -818,11 +818,11 @@  discard block
 block discarded – undo
818 818
  *     Texte converti
819 819
  **/
820 820
 function javascript_to_unicode($texte) {
821
-	while (preg_match(',%u([0-9A-F][0-9A-F][0-9A-F][0-9A-F]),', $texte, $regs)) {
822
-		$texte = str_replace($regs[0], '&#' . hexdec($regs[1]) . ';', $texte);
823
-	}
821
+    while (preg_match(',%u([0-9A-F][0-9A-F][0-9A-F][0-9A-F]),', $texte, $regs)) {
822
+        $texte = str_replace($regs[0], '&#' . hexdec($regs[1]) . ';', $texte);
823
+    }
824 824
 
825
-	return $texte;
825
+    return $texte;
826 826
 }
827 827
 
828 828
 /**
@@ -834,11 +834,11 @@  discard block
 block discarded – undo
834 834
  *     Texte converti
835 835
  **/
836 836
 function javascript_to_binary($texte) {
837
-	while (preg_match(',%([0-9A-F][0-9A-F]),', $texte, $regs)) {
838
-		$texte = str_replace($regs[0], chr(hexdec($regs[1])), $texte);
839
-	}
837
+    while (preg_match(',%([0-9A-F][0-9A-F]),', $texte, $regs)) {
838
+        $texte = str_replace($regs[0], chr(hexdec($regs[1])), $texte);
839
+    }
840 840
 
841
-	return $texte;
841
+    return $texte;
842 842
 }
843 843
 
844 844
 
@@ -856,26 +856,26 @@  discard block
 block discarded – undo
856 856
  * @return string
857 857
  */
858 858
 function translitteration_rapide($texte, $charset = 'AUTO', $complexe = '') {
859
-	static $trans = [];
860
-	if ($charset == 'AUTO') {
861
-		$charset = $GLOBALS['meta']['charset'];
862
-	}
863
-	if (!strlen($texte)) {
864
-		return $texte;
865
-	}
866
-
867
-	$table_translit = 'translit' . $complexe;
868
-
869
-	// 2. Translitterer grace a la table predefinie
870
-	if (!isset($trans[$complexe])) {
871
-		$trans[$complexe] = [];
872
-		load_charset($table_translit);
873
-		foreach ($GLOBALS['CHARSET'][$table_translit] as $key => $val) {
874
-			$trans[$complexe][caractere_utf_8($key)] = $val;
875
-		}
876
-	}
877
-
878
-	return str_replace(array_keys($trans[$complexe]), array_values($trans[$complexe]), $texte);
859
+    static $trans = [];
860
+    if ($charset == 'AUTO') {
861
+        $charset = $GLOBALS['meta']['charset'];
862
+    }
863
+    if (!strlen($texte)) {
864
+        return $texte;
865
+    }
866
+
867
+    $table_translit = 'translit' . $complexe;
868
+
869
+    // 2. Translitterer grace a la table predefinie
870
+    if (!isset($trans[$complexe])) {
871
+        $trans[$complexe] = [];
872
+        load_charset($table_translit);
873
+        foreach ($GLOBALS['CHARSET'][$table_translit] as $key => $val) {
874
+            $trans[$complexe][caractere_utf_8($key)] = $val;
875
+        }
876
+    }
877
+
878
+    return str_replace(array_keys($trans[$complexe]), array_values($trans[$complexe]), $texte);
879 879
 }
880 880
 
881 881
 /**
@@ -898,14 +898,14 @@  discard block
 block discarded – undo
898 898
  * @return string
899 899
  */
900 900
 function translitteration($texte, $charset = 'AUTO', $complexe = '') {
901
-	// 0. Supprimer les caracteres illegaux
902
-	include_spip('inc/filtres');
903
-	$texte = corriger_caracteres($texte);
901
+    // 0. Supprimer les caracteres illegaux
902
+    include_spip('inc/filtres');
903
+    $texte = corriger_caracteres($texte);
904 904
 
905
-	// 1. Passer le charset et les &eacute en utf-8
906
-	$texte = unicode_to_utf_8(html2unicode(charset2unicode($texte, $charset)));
905
+    // 1. Passer le charset et les &eacute en utf-8
906
+    $texte = unicode_to_utf_8(html2unicode(charset2unicode($texte, $charset)));
907 907
 
908
-	return translitteration_rapide($texte, $charset, $complexe);
908
+    return translitteration_rapide($texte, $charset, $complexe);
909 909
 }
910 910
 
911 911
 /**
@@ -920,17 +920,17 @@  discard block
 block discarded – undo
920 920
  * @return string
921 921
  */
922 922
 function translitteration_complexe($texte, $chiffres = false) {
923
-	$texte = translitteration($texte, 'AUTO', 'complexe');
923
+    $texte = translitteration($texte, 'AUTO', 'complexe');
924 924
 
925
-	if ($chiffres) {
926
-		$texte = preg_replace_callback(
927
-			"/[aeiuoyd]['`?~.^+(-]{1,2}/S",
928
-			fn($m) => translitteration_chiffree($m[0]),
929
-			$texte
930
-		);
931
-	}
925
+    if ($chiffres) {
926
+        $texte = preg_replace_callback(
927
+            "/[aeiuoyd]['`?~.^+(-]{1,2}/S",
928
+            fn($m) => translitteration_chiffree($m[0]),
929
+            $texte
930
+        );
931
+    }
932 932
 
933
-	return $texte;
933
+    return $texte;
934 934
 }
935 935
 
936 936
 /**
@@ -942,7 +942,7 @@  discard block
 block discarded – undo
942 942
  * @return string
943 943
  */
944 944
 function translitteration_chiffree($car) {
945
-	return strtr($car, "'`?~.^+(-", '123456789');
945
+    return strtr($car, "'`?~.^+(-", '123456789');
946 946
 }
947 947
 
948 948
 
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
  *    true s'il a un BOM
956 956
  **/
957 957
 function bom_utf8($texte) {
958
-	return (substr($texte, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF));
958
+    return (substr($texte, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF));
959 959
 }
960 960
 
961 961
 /**
@@ -972,21 +972,21 @@  discard block
 block discarded – undo
972 972
  *     true si c'est le cas
973 973
  **/
974 974
 function is_utf8($string) {
975
-	return !strlen(
976
-		preg_replace(
977
-			',[\x09\x0A\x0D\x20-\x7E]'            # ASCII
978
-			. '|[\xC2-\xDF][\x80-\xBF]'             # non-overlong 2-byte
979
-			. '|\xE0[\xA0-\xBF][\x80-\xBF]'         # excluding overlongs
980
-			. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'  # straight 3-byte
981
-			. '|\xED[\x80-\x9F][\x80-\xBF]'         # excluding surrogates
982
-			. '|\xF0[\x90-\xBF][\x80-\xBF]{2}'      # planes 1-3
983
-			. '|[\xF1-\xF3][\x80-\xBF]{3}'          # planes 4-15
984
-			. '|\xF4[\x80-\x8F][\x80-\xBF]{2}'      # plane 16
985
-			. ',sS',
986
-			'',
987
-			$string
988
-		)
989
-	);
975
+    return !strlen(
976
+        preg_replace(
977
+            ',[\x09\x0A\x0D\x20-\x7E]'            # ASCII
978
+            . '|[\xC2-\xDF][\x80-\xBF]'             # non-overlong 2-byte
979
+            . '|\xE0[\xA0-\xBF][\x80-\xBF]'         # excluding overlongs
980
+            . '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'  # straight 3-byte
981
+            . '|\xED[\x80-\x9F][\x80-\xBF]'         # excluding surrogates
982
+            . '|\xF0[\x90-\xBF][\x80-\xBF]{2}'      # planes 1-3
983
+            . '|[\xF1-\xF3][\x80-\xBF]{3}'          # planes 4-15
984
+            . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'      # plane 16
985
+            . ',sS',
986
+            '',
987
+            $string
988
+        )
989
+    );
990 990
 }
991 991
 
992 992
 /**
@@ -998,13 +998,13 @@  discard block
 block discarded – undo
998 998
  *     true si c'est le cas
999 999
  **/
1000 1000
 function is_ascii($string) {
1001
-	return !strlen(
1002
-		preg_replace(
1003
-			',[\x09\x0A\x0D\x20-\x7E],sS',
1004
-			'',
1005
-			$string
1006
-		)
1007
-	);
1001
+    return !strlen(
1002
+        preg_replace(
1003
+            ',[\x09\x0A\x0D\x20-\x7E],sS',
1004
+            '',
1005
+            $string
1006
+        )
1007
+    );
1008 1008
 }
1009 1009
 
1010 1010
 /**
@@ -1023,53 +1023,53 @@  discard block
 block discarded – undo
1023 1023
  **/
1024 1024
 function transcoder_page($texte, $headers = '') {
1025 1025
 
1026
-	// Si tout est < 128 pas la peine d'aller plus loin
1027
-	if (is_ascii($texte)) {
1028
-		#spip_log('charset: ascii');
1029
-		return $texte;
1030
-	}
1031
-
1032
-	if (bom_utf8($texte)) {
1033
-		// Reconnaitre le BOM utf-8 (0xEFBBBF)
1034
-		$charset = 'utf-8';
1035
-		$texte = substr($texte, 3);
1036
-	} elseif (preg_match(',<[?]xml[^>]*encoding[^>]*=[^>]*([-_a-z0-9]+?),UimsS', $texte, $regs)) {
1037
-		// charset precise par le contenu (xml)
1038
-		$charset = trim(strtolower($regs[1]));
1039
-	} elseif (
1040
-		// charset precise par le contenu (html)
1041
-		preg_match(',<(meta|html|body)[^>]*charset[^>]*=[^>]*([#-_a-z0-9]+?),UimsS', $texte, $regs)
1042
-		# eviter toute balise SPIP tel que #CHARSET ou #CONFIG d'un squelette
1043
-		and false === strpos($regs[2], '#')
1044
-		and $tmp = trim(strtolower($regs[2]))
1045
-	) {
1046
-		$charset = $tmp;
1047
-	} elseif (preg_match(',charset=([-_a-z0-9]+),i', $headers, $regs)) {
1048
-		// charset de la reponse http
1049
-		$charset = trim(strtolower($regs[1]));
1050
-	} else {
1051
-		$charset = '';
1052
-	}
1053
-
1054
-
1055
-	// normaliser les noms du shif-jis japonais
1056
-	if (preg_match(',^(x|shift)[_-]s?jis$,i', $charset)) {
1057
-		$charset = 'shift-jis';
1058
-	}
1059
-
1060
-	if ($charset) {
1061
-		spip_log("charset: $charset");
1062
-	} else {
1063
-		// valeur par defaut
1064
-		if (is_utf8($texte)) {
1065
-			$charset = 'utf-8';
1066
-		} else {
1067
-			$charset = 'iso-8859-1';
1068
-		}
1069
-		spip_log("charset probable: $charset");
1070
-	}
1071
-
1072
-	return importer_charset($texte, $charset);
1026
+    // Si tout est < 128 pas la peine d'aller plus loin
1027
+    if (is_ascii($texte)) {
1028
+        #spip_log('charset: ascii');
1029
+        return $texte;
1030
+    }
1031
+
1032
+    if (bom_utf8($texte)) {
1033
+        // Reconnaitre le BOM utf-8 (0xEFBBBF)
1034
+        $charset = 'utf-8';
1035
+        $texte = substr($texte, 3);
1036
+    } elseif (preg_match(',<[?]xml[^>]*encoding[^>]*=[^>]*([-_a-z0-9]+?),UimsS', $texte, $regs)) {
1037
+        // charset precise par le contenu (xml)
1038
+        $charset = trim(strtolower($regs[1]));
1039
+    } elseif (
1040
+        // charset precise par le contenu (html)
1041
+        preg_match(',<(meta|html|body)[^>]*charset[^>]*=[^>]*([#-_a-z0-9]+?),UimsS', $texte, $regs)
1042
+        # eviter toute balise SPIP tel que #CHARSET ou #CONFIG d'un squelette
1043
+        and false === strpos($regs[2], '#')
1044
+        and $tmp = trim(strtolower($regs[2]))
1045
+    ) {
1046
+        $charset = $tmp;
1047
+    } elseif (preg_match(',charset=([-_a-z0-9]+),i', $headers, $regs)) {
1048
+        // charset de la reponse http
1049
+        $charset = trim(strtolower($regs[1]));
1050
+    } else {
1051
+        $charset = '';
1052
+    }
1053
+
1054
+
1055
+    // normaliser les noms du shif-jis japonais
1056
+    if (preg_match(',^(x|shift)[_-]s?jis$,i', $charset)) {
1057
+        $charset = 'shift-jis';
1058
+    }
1059
+
1060
+    if ($charset) {
1061
+        spip_log("charset: $charset");
1062
+    } else {
1063
+        // valeur par defaut
1064
+        if (is_utf8($texte)) {
1065
+            $charset = 'utf-8';
1066
+        } else {
1067
+            $charset = 'iso-8859-1';
1068
+        }
1069
+        spip_log("charset probable: $charset");
1070
+    }
1071
+
1072
+    return importer_charset($texte, $charset);
1073 1073
 }
1074 1074
 
1075 1075
 
@@ -1093,26 +1093,26 @@  discard block
 block discarded – undo
1093 1093
  *     Le texte coupé
1094 1094
  **/
1095 1095
 function spip_substr($c, $start = 0, $length = null) {
1096
-	// Si ce n'est pas utf-8, utiliser substr
1097
-	if ($GLOBALS['meta']['charset'] != 'utf-8') {
1098
-		if ($length) {
1099
-			return substr($c, $start, $length);
1100
-		} else {
1101
-			substr($c, $start);
1102
-		}
1103
-	}
1104
-
1105
-	// Si utf-8, voir si on dispose de mb_string
1106
-	if (init_mb_string()) {
1107
-		if ($length) {
1108
-			return mb_substr($c, $start, $length);
1109
-		} else {
1110
-			return mb_substr($c, $start);
1111
-		}
1112
-	}
1113
-
1114
-	// Version manuelle (cf. ci-dessous)
1115
-	return spip_substr_manuelle($c, $start, $length);
1096
+    // Si ce n'est pas utf-8, utiliser substr
1097
+    if ($GLOBALS['meta']['charset'] != 'utf-8') {
1098
+        if ($length) {
1099
+            return substr($c, $start, $length);
1100
+        } else {
1101
+            substr($c, $start);
1102
+        }
1103
+    }
1104
+
1105
+    // Si utf-8, voir si on dispose de mb_string
1106
+    if (init_mb_string()) {
1107
+        if ($length) {
1108
+            return mb_substr($c, $start, $length);
1109
+        } else {
1110
+            return mb_substr($c, $start);
1111
+        }
1112
+    }
1113
+
1114
+    // Version manuelle (cf. ci-dessous)
1115
+    return spip_substr_manuelle($c, $start, $length);
1116 1116
 }
1117 1117
 
1118 1118
 
@@ -1131,40 +1131,40 @@  discard block
 block discarded – undo
1131 1131
  **/
1132 1132
 function spip_substr_manuelle($c, $start, $length = null) {
1133 1133
 
1134
-	// Cas pathologique
1135
-	if ($length === 0) {
1136
-		return '';
1137
-	}
1138
-
1139
-	// S'il y a un demarrage, on se positionne
1140
-	if ($start > 0) {
1141
-		$c = substr($c, strlen(spip_substr_manuelle($c, 0, $start)));
1142
-	} elseif ($start < 0) {
1143
-		return spip_substr_manuelle($c, spip_strlen($c) + $start, $length);
1144
-	}
1145
-
1146
-	if (!$length) {
1147
-		return $c;
1148
-	}
1149
-
1150
-	if ($length > 0) {
1151
-		// on prend n fois la longueur desiree, pour etre surs d'avoir tout
1152
-		// (un caractere utf-8 prenant au maximum n bytes)
1153
-		$n = 0;
1154
-		while (preg_match(',[\x80-\xBF]{' . (++$n) . '},', $c)) {
1155
-			;
1156
-		}
1157
-		$c = substr($c, 0, $n * $length);
1158
-		// puis, tant qu'on est trop long, on coupe...
1159
-		while (($l = spip_strlen($c)) > $length) {
1160
-			$c = substr($c, 0, $length - $l);
1161
-		}
1162
-
1163
-		return $c;
1164
-	}
1165
-
1166
-	// $length < 0
1167
-	return spip_substr_manuelle($c, 0, spip_strlen($c) + $length);
1134
+    // Cas pathologique
1135
+    if ($length === 0) {
1136
+        return '';
1137
+    }
1138
+
1139
+    // S'il y a un demarrage, on se positionne
1140
+    if ($start > 0) {
1141
+        $c = substr($c, strlen(spip_substr_manuelle($c, 0, $start)));
1142
+    } elseif ($start < 0) {
1143
+        return spip_substr_manuelle($c, spip_strlen($c) + $start, $length);
1144
+    }
1145
+
1146
+    if (!$length) {
1147
+        return $c;
1148
+    }
1149
+
1150
+    if ($length > 0) {
1151
+        // on prend n fois la longueur desiree, pour etre surs d'avoir tout
1152
+        // (un caractere utf-8 prenant au maximum n bytes)
1153
+        $n = 0;
1154
+        while (preg_match(',[\x80-\xBF]{' . (++$n) . '},', $c)) {
1155
+            ;
1156
+        }
1157
+        $c = substr($c, 0, $n * $length);
1158
+        // puis, tant qu'on est trop long, on coupe...
1159
+        while (($l = spip_strlen($c)) > $length) {
1160
+            $c = substr($c, 0, $length - $l);
1161
+        }
1162
+
1163
+        return $c;
1164
+    }
1165
+
1166
+    // $length < 0
1167
+    return spip_substr_manuelle($c, 0, spip_strlen($c) + $length);
1168 1168
 }
1169 1169
 
1170 1170
 /**
@@ -1178,14 +1178,14 @@  discard block
 block discarded – undo
1178 1178
  *     La chaîne avec une majuscule sur le premier mot
1179 1179
  */
1180 1180
 function spip_ucfirst($c) {
1181
-	// Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser ucfirst
1182
-	if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1183
-		return ucfirst($c);
1184
-	}
1181
+    // Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser ucfirst
1182
+    if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1183
+        return ucfirst($c);
1184
+    }
1185 1185
 
1186
-	$lettre1 = mb_strtoupper(spip_substr($c, 0, 1));
1186
+    $lettre1 = mb_strtoupper(spip_substr($c, 0, 1));
1187 1187
 
1188
-	return $lettre1 . spip_substr($c, 1);
1188
+    return $lettre1 . spip_substr($c, 1);
1189 1189
 }
1190 1190
 
1191 1191
 /**
@@ -1199,12 +1199,12 @@  discard block
 block discarded – undo
1199 1199
  *     La chaîne en minuscules
1200 1200
  */
1201 1201
 function spip_strtolower($c) {
1202
-	// Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser strtolower
1203
-	if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1204
-		return strtolower($c);
1205
-	}
1202
+    // Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser strtolower
1203
+    if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1204
+        return strtolower($c);
1205
+    }
1206 1206
 
1207
-	return mb_strtolower($c);
1207
+    return mb_strtolower($c);
1208 1208
 }
1209 1209
 
1210 1210
 /**
@@ -1218,23 +1218,23 @@  discard block
 block discarded – undo
1218 1218
  *     Longueur de la chaîne
1219 1219
  */
1220 1220
 function spip_strlen($c) {
1221
-	// On transforme les sauts de ligne pour ne pas compter deux caractères
1222
-	$c = str_replace("\r\n", "\n", $c);
1223
-
1224
-	// Si ce n'est pas utf-8, utiliser strlen
1225
-	if ($GLOBALS['meta']['charset'] != 'utf-8') {
1226
-		return strlen($c);
1227
-	}
1228
-
1229
-	// Sinon, utiliser mb_strlen() si disponible
1230
-	if (init_mb_string()) {
1231
-		return mb_strlen($c);
1232
-	}
1233
-
1234
-	// Methode manuelle : on supprime les bytes 10......,
1235
-	// on compte donc les ascii (0.......) et les demarrages
1236
-	// de caracteres utf-8 (11......)
1237
-	return strlen(preg_replace(',[\x80-\xBF],S', '', $c));
1221
+    // On transforme les sauts de ligne pour ne pas compter deux caractères
1222
+    $c = str_replace("\r\n", "\n", $c);
1223
+
1224
+    // Si ce n'est pas utf-8, utiliser strlen
1225
+    if ($GLOBALS['meta']['charset'] != 'utf-8') {
1226
+        return strlen($c);
1227
+    }
1228
+
1229
+    // Sinon, utiliser mb_strlen() si disponible
1230
+    if (init_mb_string()) {
1231
+        return mb_strlen($c);
1232
+    }
1233
+
1234
+    // Methode manuelle : on supprime les bytes 10......,
1235
+    // on compte donc les ascii (0.......) et les demarrages
1236
+    // de caracteres utf-8 (11......)
1237
+    return strlen(preg_replace(',[\x80-\xBF],S', '', $c));
1238 1238
 }
1239 1239
 
1240 1240
 // Initialisation
@@ -1244,16 +1244,16 @@  discard block
 block discarded – undo
1244 1244
 // dans les preg_replace pour ne pas casser certaines lettres accentuees :
1245 1245
 // en utf-8 chr(195).chr(160) = a` alors qu'en iso-latin chr(160) = nbsp
1246 1246
 if (
1247
-	!isset($GLOBALS['meta']['pcre_u'])
1248
-	or (isset($_GET['var_mode']) and !isset($_GET['var_profile']))
1247
+    !isset($GLOBALS['meta']['pcre_u'])
1248
+    or (isset($_GET['var_mode']) and !isset($_GET['var_profile']))
1249 1249
 ) {
1250
-	include_spip('inc/meta');
1251
-	ecrire_meta(
1252
-		'pcre_u',
1253
-		$u = (lire_config('charset', _DEFAULT_CHARSET) == 'utf-8'
1254
-			and test_pcre_unicode())
1255
-			? 'u' : ''
1256
-	);
1250
+    include_spip('inc/meta');
1251
+    ecrire_meta(
1252
+        'pcre_u',
1253
+        $u = (lire_config('charset', _DEFAULT_CHARSET) == 'utf-8'
1254
+            and test_pcre_unicode())
1255
+            ? 'u' : ''
1256
+    );
1257 1257
 }
1258 1258
 
1259 1259
 
@@ -1269,17 +1269,17 @@  discard block
 block discarded – undo
1269 1269
  *     en unicode : &#128169;
1270 1270
  */
1271 1271
 function utf8_noplanes($x) {
1272
-	$regexp_utf8_4bytes = '/(
1272
+    $regexp_utf8_4bytes = '/(
1273 1273
       \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
1274 1274
    | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
1275 1275
    |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
1276 1276
 )/xS';
1277
-	if (preg_match_all($regexp_utf8_4bytes, $x, $z, PREG_PATTERN_ORDER)) {
1278
-		foreach ($z[0] as $k) {
1279
-			$ku = utf_8_to_unicode($k);
1280
-			$x = str_replace($k, $ku, $x);
1281
-		}
1282
-	}
1283
-
1284
-	return $x;
1277
+    if (preg_match_all($regexp_utf8_4bytes, $x, $z, PREG_PATTERN_ORDER)) {
1278
+        foreach ($z[0] as $k) {
1279
+            $ku = utf_8_to_unicode($k);
1280
+            $x = str_replace($k, $ku, $x);
1281
+        }
1282
+    }
1283
+
1284
+    return $x;
1285 1285
 }
Please login to merge, or discard this patch.
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		}
74 74
 	}
75 75
 
76
-	if (find_in_path($charset . '.php', 'charsets/', true)) {
76
+	if (find_in_path($charset.'.php', 'charsets/', true)) {
77 77
 		return $charset;
78 78
 	} else {
79 79
 		spip_log("Erreur: pas de fichier de conversion 'charsets/$charset'");
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	static $pcre_ok = 0;
161 161
 
162 162
 	if (!$pcre_ok) {
163
-		$s = ' ' . chr(195) . chr(169) . 't' . chr(195) . chr(169) . ' ';
163
+		$s = ' '.chr(195).chr(169).'t'.chr(195).chr(169).' ';
164 164
 		if (preg_match(',\W...\W,u', $s)) {
165 165
 			$pcre_ok = 1;
166 166
 		} else {
@@ -261,38 +261,38 @@  discard block
 block discarded – undo
261 261
 
262 262
 	if (!isset($trans[$charset][$charset_cible])) {
263 263
 		$trans[$charset][$charset_cible] = [
264
-			$p . chr(128) => '&#8364;',
265
-			$p . chr(129) => ' ', # pas affecte
266
-			$p . chr(130) => '&#8218;',
267
-			$p . chr(131) => '&#402;',
268
-			$p . chr(132) => '&#8222;',
269
-			$p . chr(133) => '&#8230;',
270
-			$p . chr(134) => '&#8224;',
271
-			$p . chr(135) => '&#8225;',
272
-			$p . chr(136) => '&#710;',
273
-			$p . chr(137) => '&#8240;',
274
-			$p . chr(138) => '&#352;',
275
-			$p . chr(139) => '&#8249;',
276
-			$p . chr(140) => '&#338;',
277
-			$p . chr(141) => ' ', # pas affecte
278
-			$p . chr(142) => '&#381;',
279
-			$p . chr(143) => ' ', # pas affecte
280
-			$p . chr(144) => ' ', # pas affecte
281
-			$p . chr(145) => '&#8216;',
282
-			$p . chr(146) => '&#8217;',
283
-			$p . chr(147) => '&#8220;',
284
-			$p . chr(148) => '&#8221;',
285
-			$p . chr(149) => '&#8226;',
286
-			$p . chr(150) => '&#8211;',
287
-			$p . chr(151) => '&#8212;',
288
-			$p . chr(152) => '&#732;',
289
-			$p . chr(153) => '&#8482;',
290
-			$p . chr(154) => '&#353;',
291
-			$p . chr(155) => '&#8250;',
292
-			$p . chr(156) => '&#339;',
293
-			$p . chr(157) => ' ', # pas affecte
294
-			$p . chr(158) => '&#382;',
295
-			$p . chr(159) => '&#376;',
264
+			$p.chr(128) => '&#8364;',
265
+			$p.chr(129) => ' ', # pas affecte
266
+			$p.chr(130) => '&#8218;',
267
+			$p.chr(131) => '&#402;',
268
+			$p.chr(132) => '&#8222;',
269
+			$p.chr(133) => '&#8230;',
270
+			$p.chr(134) => '&#8224;',
271
+			$p.chr(135) => '&#8225;',
272
+			$p.chr(136) => '&#710;',
273
+			$p.chr(137) => '&#8240;',
274
+			$p.chr(138) => '&#352;',
275
+			$p.chr(139) => '&#8249;',
276
+			$p.chr(140) => '&#338;',
277
+			$p.chr(141) => ' ', # pas affecte
278
+			$p.chr(142) => '&#381;',
279
+			$p.chr(143) => ' ', # pas affecte
280
+			$p.chr(144) => ' ', # pas affecte
281
+			$p.chr(145) => '&#8216;',
282
+			$p.chr(146) => '&#8217;',
283
+			$p.chr(147) => '&#8220;',
284
+			$p.chr(148) => '&#8221;',
285
+			$p.chr(149) => '&#8226;',
286
+			$p.chr(150) => '&#8211;',
287
+			$p.chr(151) => '&#8212;',
288
+			$p.chr(152) => '&#732;',
289
+			$p.chr(153) => '&#8482;',
290
+			$p.chr(154) => '&#353;',
291
+			$p.chr(155) => '&#8250;',
292
+			$p.chr(156) => '&#339;',
293
+			$p.chr(157) => ' ', # pas affecte
294
+			$p.chr(158) => '&#382;',
295
+			$p.chr(159) => '&#376;',
296 296
 		];
297 297
 		if ($charset_cible != 'unicode') {
298 298
 			foreach ($trans[$charset][$charset_cible] as $k => $c) {
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 					and is_array($GLOBALS['CHARSET'][$cset])
434 434
 				) {
435 435
 					foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
436
-						$trans[$charset][chr($key)] = '&#' . $val . ';';
436
+						$trans[$charset][chr($key)] = '&#'.$val.';';
437 437
 					}
438 438
 				}
439 439
 			}
@@ -500,11 +500,11 @@  discard block
 block discarded – undo
500 500
 					$h = dechex($e);
501 501
 					if ($s = isset($CHARSET_REVERSE[$charset][$e])) {
502 502
 						$s = $CHARSET_REVERSE[$charset][$e];
503
-						$t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($s);
504
-						$t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($s);
503
+						$t['&#'.$e.';'] = $t['&#0'.$e.';'] = $t['&#00'.$e.';'] = chr($s);
504
+						$t['&#x'.$h.';'] = $t['&#x0'.$h.';'] = $t['&#x00'.$h.';'] = chr($s);
505 505
 					} else {
506
-						$t['&#' . $e . ';'] = $t['&#0' . $e . ';'] = $t['&#00' . $e . ';'] = chr($e);
507
-						$t['&#x' . $h . ';'] = $t['&#x0' . $h . ';'] = $t['&#x00' . $h . ';'] = chr($e);
506
+						$t['&#'.$e.';'] = $t['&#0'.$e.';'] = $t['&#00'.$e.';'] = chr($e);
507
+						$t['&#x'.$h.';'] = $t['&#x0'.$h.';'] = $t['&#x00'.$h.';'] = chr($e);
508 508
 					}
509 509
 				}
510 510
 			}
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 				and is_array($GLOBALS['CHARSET'][$cset])
552 552
 			) {
553 553
 				foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
554
-					$trans[$charset][chr($key)] = unicode2charset('&#' . $val . ';');
554
+					$trans[$charset][chr($key)] = unicode2charset('&#'.$val.';');
555 555
 				}
556 556
 			}
557 557
 		}
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 				}
659 659
 				$thisPos++;
660 660
 			}
661
-			$encodedLetter = '&#' . preg_replace('/^0+/', '', $decimalCode) . ';';
661
+			$encodedLetter = '&#'.preg_replace('/^0+/', '', $decimalCode).';';
662 662
 			$encodedString .= $encodedLetter;
663 663
 		}
664 664
 	}
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
 			} // ignorer le BOM - http://www.unicode.org/faq/utf_bom.html
702 702
 			else {
703 703
 				if ($word != 65279) {
704
-					$texte .= '&#' . $word . ';';
704
+					$texte .= '&#'.$word.';';
705 705
 				}
706 706
 			}
707 707
 		}
@@ -729,13 +729,13 @@  discard block
 block discarded – undo
729 729
 		return chr($num);
730 730
 	}
731 731
 	if ($num < 2048) {
732
-		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
732
+		return chr(($num >> 6) + 192).chr(($num & 63) + 128);
733 733
 	}
734 734
 	if ($num < 65536) {
735
-		return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
735
+		return chr(($num >> 12) + 224).chr((($num >> 6) & 63) + 128).chr(($num & 63) + 128);
736 736
 	}
737 737
 	if ($num < 1_114_112) {
738
-		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
738
+		return chr(($num >> 18) + 240).chr((($num >> 12) & 63) + 128).chr((($num >> 6) & 63) + 128).chr(($num & 63) + 128);
739 739
 	}
740 740
 
741 741
 	return '';
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 	while (preg_match(',&#0*([0-9]+);,S', $texte, $regs) and !isset($vu[$regs[1]])) {
803 803
 		$num = $regs[1];
804 804
 		$vu[$num] = true;
805
-		$s = '\u' . sprintf('%04x', $num);
805
+		$s = '\u'.sprintf('%04x', $num);
806 806
 		$texte = str_replace($regs[0], $s, $texte);
807 807
 	}
808 808
 
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
  **/
820 820
 function javascript_to_unicode($texte) {
821 821
 	while (preg_match(',%u([0-9A-F][0-9A-F][0-9A-F][0-9A-F]),', $texte, $regs)) {
822
-		$texte = str_replace($regs[0], '&#' . hexdec($regs[1]) . ';', $texte);
822
+		$texte = str_replace($regs[0], '&#'.hexdec($regs[1]).';', $texte);
823 823
 	}
824 824
 
825 825
 	return $texte;
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
 		return $texte;
865 865
 	}
866 866
 
867
-	$table_translit = 'translit' . $complexe;
867
+	$table_translit = 'translit'.$complexe;
868 868
 
869 869
 	// 2. Translitterer grace a la table predefinie
870 870
 	if (!isset($trans[$complexe])) {
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
  *    true s'il a un BOM
956 956
  **/
957 957
 function bom_utf8($texte) {
958
-	return (substr($texte, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF));
958
+	return (substr($texte, 0, 3) == chr(0xEF).chr(0xBB).chr(0xBF));
959 959
 }
960 960
 
961 961
 /**
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
 		// on prend n fois la longueur desiree, pour etre surs d'avoir tout
1152 1152
 		// (un caractere utf-8 prenant au maximum n bytes)
1153 1153
 		$n = 0;
1154
-		while (preg_match(',[\x80-\xBF]{' . (++$n) . '},', $c)) {
1154
+		while (preg_match(',[\x80-\xBF]{'.(++$n).'},', $c)) {
1155 1155
 			;
1156 1156
 		}
1157 1157
 		$c = substr($c, 0, $n * $length);
@@ -1185,7 +1185,7 @@  discard block
 block discarded – undo
1185 1185
 
1186 1186
 	$lettre1 = mb_strtoupper(spip_substr($c, 0, 1));
1187 1187
 
1188
-	return $lettre1 . spip_substr($c, 1);
1188
+	return $lettre1.spip_substr($c, 1);
1189 1189
 }
1190 1190
 
1191 1191
 /**
Please login to merge, or discard this patch.
ecrire/inc/plonger.php 2 patches
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -35,9 +35,9 @@  discard block
 block discarded – undo
35 35
 	$res = sql_select(
36 36
 		'rub1.id_rubrique, rub1.titre, rub1.id_parent, rub1.lang, rub1.langue_choisie, rub2.id_rubrique AS id_enfant',
37 37
 		'spip_rubriques AS rub1 LEFT JOIN spip_rubriques AS rub2 ON (rub1.id_rubrique = rub2.id_parent)',
38
-		'rub1.id_parent = ' . sql_quote($id_rubrique) . '
39
-			AND rub1.id_rubrique!=' . sql_quote($exclu) . '
40
-			AND (rub2.id_rubrique IS NULL OR rub2.id_rubrique!=' . sql_quote($exclu) . ')',
38
+		'rub1.id_parent = '.sql_quote($id_rubrique).'
39
+			AND rub1.id_rubrique!=' . sql_quote($exclu).'
40
+			AND (rub2.id_rubrique IS NULL OR rub2.id_rubrique!=' . sql_quote($exclu).')',
41 41
 		'',
42 42
 		'0+rub1.titre,rub1.titre'
43 43
 	);
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 				if ($row['langue_choisie'] != 'oui') {
51 51
 					$t .= ' <small title="'
52 52
 						. traduire_nom_langue($row['lang'])
53
-						. '">[' . $row['lang'] . ']</small>';
53
+						. '">['.$row['lang'].']</small>';
54 54
 				}
55 55
 				$ordre[$row['id_rubrique']] = $t;
56 56
 			}
@@ -58,14 +58,14 @@  discard block
 block discarded – undo
58 58
 	}
59 59
 	$next = $list[$col] ?? 0;
60 60
 	if ($ordre) {
61
-		$rec = generer_url_ecrire('plonger', "rac=$idom&exclus=$exclu&do=$do&col=" . ($col + 1));
61
+		$rec = generer_url_ecrire('plonger', "rac=$idom&exclus=$exclu&do=$do&col=".($col + 1));
62 62
 		$info = generer_url_ecrire('informer', "type=rubrique&rac=$idom&do=$do&id=");
63
-		$args = "'$idom',this,$col,'" . $GLOBALS['spip_lang_left'] . "','$info',event";
63
+		$args = "'$idom',this,$col,'".$GLOBALS['spip_lang_left']."','$info',event";
64 64
 
65 65
 		foreach ($ordre as $id => $titrebrut) {
66 66
 			$titre = supprimer_numero($titrebrut);
67 67
 
68
-			$classe1 = 'petit-item ' . ($id_rubrique ? 'petite-rubrique' : 'petit-secteur');
68
+			$classe1 = 'petit-item '.($id_rubrique ? 'petite-rubrique' : 'petit-secteur');
69 69
 			if (isset($rub[$id]['enfants'])) {
70 70
 				$classe2 = " class='rub-ouverte'";
71 71
 				$url = "\nhref='$rec&amp;id=$id'";
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 				$url = "\nhref='javascript:void(0)'";
75 75
 			}
76 76
 
77
-			$js_func = $do . '_selection_titre';
77
+			$js_func = $do.'_selection_titre';
78 78
 			$click = "\nonclick=\"changerhighlight(this.parentNode.parentNode.parentNode);\nreturn "
79 79
 				. (!is_array($list) ? ' false'
80 80
 					: "aff_selection_provisoire($id,$args)")
@@ -101,17 +101,17 @@  discard block
 block discarded – undo
101 101
 		}
102 102
 	}
103 103
 
104
-	$idom2 = $idom . '_col_' . ($col + 1);
104
+	$idom2 = $idom.'_col_'.($col + 1);
105 105
 	$left = ($col * 250);
106 106
 
107 107
 	return http_img_pack(
108 108
 		'loader.svg',
109 109
 		'',
110
-		"class='loader' style='visibility: hidden; position: absolute; " . $GLOBALS['spip_lang_left'] . ': '
110
+		"class='loader' style='visibility: hidden; position: absolute; ".$GLOBALS['spip_lang_left'].': '
111 111
 		. ($left - 30)
112 112
 		. "px; top: 2px; z-index: 2;' id='img_$idom2'"
113 113
 	)
114
-	. "<div style='width: 250px; height: 100%; overflow: auto; position: absolute; top: 0px; " . $GLOBALS['spip_lang_left'] . ': '
114
+	. "<div style='width: 250px; height: 100%; overflow: auto; position: absolute; top: 0px; ".$GLOBALS['spip_lang_left'].': '
115 115
 	. ($left - 250)
116 116
 	. "px;'>"
117 117
 	. $ret
Please login to merge, or discard this patch.
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -11,112 +11,112 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('inc/texte');
18 18
 
19 19
 function inc_plonger_dist($id_rubrique, $idom = '', $list = [], $col = 1, $exclu = 0, $do = 'aff') {
20 20
 
21
-	if ($list) {
22
-		$id_rubrique = $list[$col - 1];
23
-	}
21
+    if ($list) {
22
+        $id_rubrique = $list[$col - 1];
23
+    }
24 24
 
25
-	$ret = '';
25
+    $ret = '';
26 26
 
27
-	# recherche les filles et petites-filles de la rubrique donnee
28
-	# en excluant une eventuelle rubrique interdite (par exemple, lorsqu'on
29
-	# deplace une rubrique, on peut la deplacer partout a partir de la
30
-	# racine... sauf vers elle-meme ou sa propre branche)
31
-	$ordre = [];
32
-	$rub = [];
27
+    # recherche les filles et petites-filles de la rubrique donnee
28
+    # en excluant une eventuelle rubrique interdite (par exemple, lorsqu'on
29
+    # deplace une rubrique, on peut la deplacer partout a partir de la
30
+    # racine... sauf vers elle-meme ou sa propre branche)
31
+    $ordre = [];
32
+    $rub = [];
33 33
 
34
-	$res = sql_select(
35
-		'rub1.id_rubrique, rub1.titre, rub1.id_parent, rub1.lang, rub1.langue_choisie, rub2.id_rubrique AS id_enfant',
36
-		'spip_rubriques AS rub1 LEFT JOIN spip_rubriques AS rub2 ON (rub1.id_rubrique = rub2.id_parent)',
37
-		'rub1.id_parent = ' . sql_quote($id_rubrique) . '
34
+    $res = sql_select(
35
+        'rub1.id_rubrique, rub1.titre, rub1.id_parent, rub1.lang, rub1.langue_choisie, rub2.id_rubrique AS id_enfant',
36
+        'spip_rubriques AS rub1 LEFT JOIN spip_rubriques AS rub2 ON (rub1.id_rubrique = rub2.id_parent)',
37
+        'rub1.id_parent = ' . sql_quote($id_rubrique) . '
38 38
 			AND rub1.id_rubrique!=' . sql_quote($exclu) . '
39 39
 			AND (rub2.id_rubrique IS NULL OR rub2.id_rubrique!=' . sql_quote($exclu) . ')',
40
-		'',
41
-		'0+rub1.titre,rub1.titre'
42
-	);
40
+        '',
41
+        '0+rub1.titre,rub1.titre'
42
+    );
43 43
 
44
-	while ($row = sql_fetch($res)) {
45
-		if (autoriser('voir', 'rubrique', $row['id_rubrique'])) {
46
-			$rub[$row['id_rubrique']]['enfants'] = $row['id_enfant'];
47
-			if ($row['id_parent'] == $id_rubrique) {
48
-				$t = trim(typo(supprimer_numero($row['titre'])));
49
-				if ($row['langue_choisie'] != 'oui') {
50
-					$t .= ' <small title="'
51
-						. traduire_nom_langue($row['lang'])
52
-						. '">[' . $row['lang'] . ']</small>';
53
-				}
54
-				$ordre[$row['id_rubrique']] = $t;
55
-			}
56
-		}
57
-	}
58
-	$next = $list[$col] ?? 0;
59
-	if ($ordre) {
60
-		$rec = generer_url_ecrire('plonger', "rac=$idom&exclus=$exclu&do=$do&col=" . ($col + 1));
61
-		$info = generer_url_ecrire('informer', "type=rubrique&rac=$idom&do=$do&id=");
62
-		$args = "'$idom',this,$col,'" . $GLOBALS['spip_lang_left'] . "','$info',event";
44
+    while ($row = sql_fetch($res)) {
45
+        if (autoriser('voir', 'rubrique', $row['id_rubrique'])) {
46
+            $rub[$row['id_rubrique']]['enfants'] = $row['id_enfant'];
47
+            if ($row['id_parent'] == $id_rubrique) {
48
+                $t = trim(typo(supprimer_numero($row['titre'])));
49
+                if ($row['langue_choisie'] != 'oui') {
50
+                    $t .= ' <small title="'
51
+                        . traduire_nom_langue($row['lang'])
52
+                        . '">[' . $row['lang'] . ']</small>';
53
+                }
54
+                $ordre[$row['id_rubrique']] = $t;
55
+            }
56
+        }
57
+    }
58
+    $next = $list[$col] ?? 0;
59
+    if ($ordre) {
60
+        $rec = generer_url_ecrire('plonger', "rac=$idom&exclus=$exclu&do=$do&col=" . ($col + 1));
61
+        $info = generer_url_ecrire('informer', "type=rubrique&rac=$idom&do=$do&id=");
62
+        $args = "'$idom',this,$col,'" . $GLOBALS['spip_lang_left'] . "','$info',event";
63 63
 
64
-		foreach ($ordre as $id => $titrebrut) {
65
-			$titre = supprimer_numero($titrebrut);
64
+        foreach ($ordre as $id => $titrebrut) {
65
+            $titre = supprimer_numero($titrebrut);
66 66
 
67
-			$classe1 = 'petit-item ' . ($id_rubrique ? 'petite-rubrique' : 'petit-secteur');
68
-			if (isset($rub[$id]['enfants'])) {
69
-				$classe2 = " class='rub-ouverte'";
70
-				$url = "\nhref='$rec&amp;id=$id'";
71
-			} else {
72
-				$classe2 = $url = '';
73
-				$url = "\nhref='javascript:void(0)'";
74
-			}
67
+            $classe1 = 'petit-item ' . ($id_rubrique ? 'petite-rubrique' : 'petit-secteur');
68
+            if (isset($rub[$id]['enfants'])) {
69
+                $classe2 = " class='rub-ouverte'";
70
+                $url = "\nhref='$rec&amp;id=$id'";
71
+            } else {
72
+                $classe2 = $url = '';
73
+                $url = "\nhref='javascript:void(0)'";
74
+            }
75 75
 
76
-			$js_func = $do . '_selection_titre';
77
-			$click = "\nonclick=\"changerhighlight(this.parentNode.parentNode.parentNode);\nreturn "
78
-				. (!is_array($list) ? ' false'
79
-					: "aff_selection_provisoire($id,$args)")
76
+            $js_func = $do . '_selection_titre';
77
+            $click = "\nonclick=\"changerhighlight(this.parentNode.parentNode.parentNode);\nreturn "
78
+                . (!is_array($list) ? ' false'
79
+                    : "aff_selection_provisoire($id,$args)")
80 80
 # ce lien provoque la selection (directe) de la rubrique cliquee
81 81
 # et l'affichage de son titre dans le bandeau
82
-				. "\"\nondblclick=\""
83
-				. "$js_func(this."
84
-				. 'firstChild.nodeValue,'
85
-				. $id
86
-				. ",'selection_rubrique','id_parent');"
87
-				. "\nreturn aff_selection_provisoire($id,$args);"
88
-				. '"';
82
+                . "\"\nondblclick=\""
83
+                . "$js_func(this."
84
+                . 'firstChild.nodeValue,'
85
+                . $id
86
+                . ",'selection_rubrique','id_parent');"
87
+                . "\nreturn aff_selection_provisoire($id,$args);"
88
+                . '"';
89 89
 
90
-			$ret .= "<div class='"
91
-				. (($id == $next) ? 'item on' : 'item')
92
-				. "'><div class='"
93
-				. $classe1
94
-				. "'><div$classe2><a"
95
-				. $url
96
-				. $click
97
-				. '>'
98
-				. $titre
99
-				. '</a></div></div></div>';
100
-		}
101
-	}
90
+            $ret .= "<div class='"
91
+                . (($id == $next) ? 'item on' : 'item')
92
+                . "'><div class='"
93
+                . $classe1
94
+                . "'><div$classe2><a"
95
+                . $url
96
+                . $click
97
+                . '>'
98
+                . $titre
99
+                . '</a></div></div></div>';
100
+        }
101
+    }
102 102
 
103
-	$idom2 = $idom . '_col_' . ($col + 1);
104
-	$left = ($col * 250);
103
+    $idom2 = $idom . '_col_' . ($col + 1);
104
+    $left = ($col * 250);
105 105
 
106
-	return http_img_pack(
107
-		'loader.svg',
108
-		'',
109
-		"class='loader' style='visibility: hidden; position: absolute; " . $GLOBALS['spip_lang_left'] . ': '
110
-		. ($left - 30)
111
-		. "px; top: 2px; z-index: 2;' id='img_$idom2'"
112
-	)
113
-	. "<div style='width: 250px; height: 100%; overflow: auto; position: absolute; top: 0px; " . $GLOBALS['spip_lang_left'] . ': '
114
-	. ($left - 250)
115
-	. "px;'>"
116
-	. $ret
117
-	. "\n</div>\n<div id='$idom2'>"
118
-	. ($next
119
-		? inc_plonger_dist($id_rubrique, $idom, $list, $col + 1, $exclu)
120
-		: '')
121
-	. "\n</div>";
106
+    return http_img_pack(
107
+        'loader.svg',
108
+        '',
109
+        "class='loader' style='visibility: hidden; position: absolute; " . $GLOBALS['spip_lang_left'] . ': '
110
+        . ($left - 30)
111
+        . "px; top: 2px; z-index: 2;' id='img_$idom2'"
112
+    )
113
+    . "<div style='width: 250px; height: 100%; overflow: auto; position: absolute; top: 0px; " . $GLOBALS['spip_lang_left'] . ': '
114
+    . ($left - 250)
115
+    . "px;'>"
116
+    . $ret
117
+    . "\n</div>\n<div id='$idom2'>"
118
+    . ($next
119
+        ? inc_plonger_dist($id_rubrique, $idom, $list, $col + 1, $exclu)
120
+        : '')
121
+    . "\n</div>";
122 122
 }
Please login to merge, or discard this patch.
ecrire/inc/texte.php 2 patches
Indentation   +227 added lines, -227 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('inc/texte_mini');
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  * @return array Tablea ('','')
35 35
  */
36 36
 function definir_raccourcis_alineas() {
37
-	return ['', ''];
37
+    return ['', ''];
38 38
 }
39 39
 
40 40
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  * @return string
48 48
  */
49 49
 function traiter_tableau($bloc) {
50
-	return $bloc;
50
+    return $bloc;
51 51
 }
52 52
 
53 53
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
  * @return string
62 62
  */
63 63
 function traiter_listes($texte) {
64
-	return $texte;
64
+    return $texte;
65 65
 }
66 66
 
67 67
 /**
@@ -77,16 +77,16 @@  discard block
 block discarded – undo
77 77
  */
78 78
 function traiter_raccourcis($letexte) {
79 79
 
80
-	// Appeler les fonctions de pre_traitement
81
-	$letexte = pipeline('pre_propre', $letexte);
80
+    // Appeler les fonctions de pre_traitement
81
+    $letexte = pipeline('pre_propre', $letexte);
82 82
 
83
-	// APPELER ICI UN PIPELINE traiter_raccourcis ?
84
-	// $letexte = pipeline('traiter_raccourcis', $letexte);
83
+    // APPELER ICI UN PIPELINE traiter_raccourcis ?
84
+    // $letexte = pipeline('traiter_raccourcis', $letexte);
85 85
 
86
-	// Appeler les fonctions de post-traitement
87
-	$letexte = pipeline('post_propre', $letexte);
86
+    // Appeler les fonctions de post-traitement
87
+    $letexte = pipeline('post_propre', $letexte);
88 88
 
89
-	return $letexte;
89
+    return $letexte;
90 90
 }
91 91
 
92 92
 /*************************************************************************************************************************
@@ -102,22 +102,22 @@  discard block
 block discarded – undo
102 102
  * @return string
103 103
  */
104 104
 function echappe_js($t, $class = ' class = "echappe-js"') {
105
-	foreach (['script', 'iframe'] as $tag) {
106
-		if (
107
-			stripos($t, (string) "<$tag") !== false
108
-			and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
109
-		) {
110
-			foreach ($r as $regs) {
111
-				$t = str_replace(
112
-					$regs[0],
113
-					"<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
114
-					$t
115
-				);
116
-			}
117
-		}
118
-	}
119
-
120
-	return $t;
105
+    foreach (['script', 'iframe'] as $tag) {
106
+        if (
107
+            stripos($t, (string) "<$tag") !== false
108
+            and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
109
+        ) {
110
+            foreach ($r as $regs) {
111
+                $t = str_replace(
112
+                    $regs[0],
113
+                    "<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
114
+                    $t
115
+                );
116
+            }
117
+        }
118
+    }
119
+
120
+    return $t;
121 121
 }
122 122
 
123 123
 
@@ -146,55 +146,55 @@  discard block
 block discarded – undo
146 146
  *     Code protégé
147 147
  **/
148 148
 function interdire_scripts($arg, $mode_filtre = null) {
149
-	// on memorise le resultat sur les arguments non triviaux
150
-	static $dejavu = [];
151
-
152
-	// Attention, si ce n'est pas une chaine, laisser intact
153
-	if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
154
-		return $arg;
155
-	}
156
-
157
-	if (is_null($mode_filtre) or !in_array($mode_filtre, [-1, 0, 1])) {
158
-		$mode_filtre = $GLOBALS['filtrer_javascript'];
159
-	}
160
-
161
-	if (isset($dejavu[$mode_filtre][$arg])) {
162
-		return $dejavu[$mode_filtre][$arg];
163
-	}
164
-
165
-	// echapper les tags asp/php
166
-	$t = str_replace('<' . '%', '&lt;%', $arg);
167
-
168
-	// echapper le php
169
-	$t = str_replace('<' . '?', '&lt;?', $t);
170
-
171
-	// echapper le < script language=php >
172
-	$t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
173
-
174
-	// Pour le js, trois modes : parano (-1), prive (0), ok (1)
175
-	switch ($mode_filtre) {
176
-		case 0:
177
-			if (!_DIR_RESTREINT) {
178
-				$t = echappe_js($t);
179
-			}
180
-			break;
181
-		case -1:
182
-			$t = echappe_js($t);
183
-			break;
184
-	}
185
-
186
-	// pas de <base href /> svp !
187
-	$t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
188
-
189
-	// Reinserer les echappements des modeles
190
-	if (defined('_PROTEGE_JS_MODELES')) {
191
-		$t = echappe_retour($t, 'javascript' . _PROTEGE_JS_MODELES);
192
-	}
193
-	if (defined('_PROTEGE_PHP_MODELES')) {
194
-		$t = echappe_retour($t, 'php' . _PROTEGE_PHP_MODELES);
195
-	}
196
-
197
-	return $dejavu[$mode_filtre][$arg] = $t;
149
+    // on memorise le resultat sur les arguments non triviaux
150
+    static $dejavu = [];
151
+
152
+    // Attention, si ce n'est pas une chaine, laisser intact
153
+    if (!$arg or !is_string($arg) or !strstr($arg, '<')) {
154
+        return $arg;
155
+    }
156
+
157
+    if (is_null($mode_filtre) or !in_array($mode_filtre, [-1, 0, 1])) {
158
+        $mode_filtre = $GLOBALS['filtrer_javascript'];
159
+    }
160
+
161
+    if (isset($dejavu[$mode_filtre][$arg])) {
162
+        return $dejavu[$mode_filtre][$arg];
163
+    }
164
+
165
+    // echapper les tags asp/php
166
+    $t = str_replace('<' . '%', '&lt;%', $arg);
167
+
168
+    // echapper le php
169
+    $t = str_replace('<' . '?', '&lt;?', $t);
170
+
171
+    // echapper le < script language=php >
172
+    $t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
173
+
174
+    // Pour le js, trois modes : parano (-1), prive (0), ok (1)
175
+    switch ($mode_filtre) {
176
+        case 0:
177
+            if (!_DIR_RESTREINT) {
178
+                $t = echappe_js($t);
179
+            }
180
+            break;
181
+        case -1:
182
+            $t = echappe_js($t);
183
+            break;
184
+    }
185
+
186
+    // pas de <base href /> svp !
187
+    $t = preg_replace(',<(base\b),iS', '&lt;\1', $t);
188
+
189
+    // Reinserer les echappements des modeles
190
+    if (defined('_PROTEGE_JS_MODELES')) {
191
+        $t = echappe_retour($t, 'javascript' . _PROTEGE_JS_MODELES);
192
+    }
193
+    if (defined('_PROTEGE_PHP_MODELES')) {
194
+        $t = echappe_retour($t, 'php' . _PROTEGE_PHP_MODELES);
195
+    }
196
+
197
+    return $dejavu[$mode_filtre][$arg] = $t;
198 198
 }
199 199
 
200 200
 
@@ -223,66 +223,66 @@  discard block
 block discarded – undo
223 223
  *     Texte transformé
224 224
  **/
225 225
 function typo($letexte, $echapper = true, $connect = null, $env = []) {
226
-	// Plus vite !
227
-	if (!$letexte) {
228
-		return $letexte;
229
-	}
230
-
231
-	// les appels directs a cette fonction depuis le php de l'espace
232
-	// prive etant historiquement ecrit sans argment $connect
233
-	// on utilise la presence de celui-ci pour distinguer les cas
234
-	// ou il faut passer interdire_script explicitement
235
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
236
-	// ne seront pas perturbes
237
-	$interdire_script = false;
238
-	if (is_null($connect)) {
239
-		$connect = '';
240
-		$interdire_script = true;
241
-		$env['espace_prive'] = test_espace_prive();
242
-	}
243
-
244
-	// Echapper les codes <html> etc
245
-	if ($echapper) {
246
-		$letexte = echappe_html($letexte, 'TYPO');
247
-	}
248
-
249
-	//
250
-	// Installer les modeles, notamment images et documents ;
251
-	//
252
-	// NOTE : propre() ne passe pas par ici mais directement par corriger_typo
253
-	// cf. inc/lien
254
-
255
-	$letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect, null, $env);
256
-	if ($letexte != $mem) {
257
-		$echapper = true;
258
-	}
259
-	unset($mem);
260
-
261
-	$letexte = corriger_typo($letexte);
262
-	$letexte = echapper_faux_tags($letexte);
263
-
264
-	// reintegrer les echappements
265
-	if ($echapper) {
266
-		$letexte = echappe_retour($letexte, 'TYPO');
267
-	}
268
-
269
-	// Dans les appels directs hors squelette, securiser ici aussi
270
-	if ($interdire_script) {
271
-		$letexte = interdire_scripts($letexte);
272
-	}
273
-
274
-	// Dans l'espace prive on se mefie de tout contenu dangereux
275
-	// https://core.spip.net/issues/3371
276
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
277
-	// https://core.spip.net/issues/4166
278
-	if (
279
-		$GLOBALS['filtrer_javascript'] == -1
280
-		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
281
-	) {
282
-		$letexte = echapper_html_suspect($letexte);
283
-	}
284
-
285
-	return $letexte;
226
+    // Plus vite !
227
+    if (!$letexte) {
228
+        return $letexte;
229
+    }
230
+
231
+    // les appels directs a cette fonction depuis le php de l'espace
232
+    // prive etant historiquement ecrit sans argment $connect
233
+    // on utilise la presence de celui-ci pour distinguer les cas
234
+    // ou il faut passer interdire_script explicitement
235
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
236
+    // ne seront pas perturbes
237
+    $interdire_script = false;
238
+    if (is_null($connect)) {
239
+        $connect = '';
240
+        $interdire_script = true;
241
+        $env['espace_prive'] = test_espace_prive();
242
+    }
243
+
244
+    // Echapper les codes <html> etc
245
+    if ($echapper) {
246
+        $letexte = echappe_html($letexte, 'TYPO');
247
+    }
248
+
249
+    //
250
+    // Installer les modeles, notamment images et documents ;
251
+    //
252
+    // NOTE : propre() ne passe pas par ici mais directement par corriger_typo
253
+    // cf. inc/lien
254
+
255
+    $letexte = traiter_modeles($mem = $letexte, false, $echapper ? 'TYPO' : '', $connect, null, $env);
256
+    if ($letexte != $mem) {
257
+        $echapper = true;
258
+    }
259
+    unset($mem);
260
+
261
+    $letexte = corriger_typo($letexte);
262
+    $letexte = echapper_faux_tags($letexte);
263
+
264
+    // reintegrer les echappements
265
+    if ($echapper) {
266
+        $letexte = echappe_retour($letexte, 'TYPO');
267
+    }
268
+
269
+    // Dans les appels directs hors squelette, securiser ici aussi
270
+    if ($interdire_script) {
271
+        $letexte = interdire_scripts($letexte);
272
+    }
273
+
274
+    // Dans l'espace prive on se mefie de tout contenu dangereux
275
+    // https://core.spip.net/issues/3371
276
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
277
+    // https://core.spip.net/issues/4166
278
+    if (
279
+        $GLOBALS['filtrer_javascript'] == -1
280
+        or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
281
+    ) {
282
+        $letexte = echapper_html_suspect($letexte);
283
+    }
284
+
285
+    return $letexte;
286 286
 }
287 287
 
288 288
 // Correcteur typographique
@@ -307,57 +307,57 @@  discard block
 block discarded – undo
307 307
  */
308 308
 function corriger_typo($letexte, $lang = '') {
309 309
 
310
-	// Plus vite !
311
-	if (!$letexte) {
312
-		return $letexte;
313
-	}
314
-
315
-	$letexte = pipeline('pre_typo', $letexte);
316
-
317
-	// Caracteres de controle "illegaux"
318
-	$letexte = corriger_caracteres($letexte);
319
-
320
-	// Proteger les caracteres typographiques a l'interieur des tags html
321
-	if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
322
-		foreach ($regs as $reg) {
323
-			$insert = $reg[0];
324
-			// hack: on transforme les caracteres a proteger en les remplacant
325
-			// par des caracteres "illegaux". (cf corriger_caracteres())
326
-			$insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
327
-			$letexte = str_replace($reg[0], $insert, $letexte);
328
-		}
329
-	}
330
-
331
-	// trouver les blocs idiomes et les traiter à part
332
-	$letexte = extraire_idiome($ei = $letexte, $lang, true);
333
-	$ei = ($ei !== $letexte);
334
-
335
-	// trouver les blocs multi et les traiter a part
336
-	$letexte = extraire_multi($em = $letexte, $lang, true);
337
-	$em = ($em !== $letexte);
338
-
339
-	// Charger & appliquer les fonctions de typographie
340
-	$typographie = charger_fonction(lang_typo($lang), 'typographie');
341
-	$letexte = $typographie($letexte);
342
-
343
-	// Les citations en une autre langue, s'il y a lieu
344
-	if ($em) {
345
-		$letexte = echappe_retour($letexte, 'multi');
346
-	}
347
-	if ($ei) {
348
-		$letexte = echappe_retour($letexte, 'idiome');
349
-	}
350
-
351
-	// Retablir les caracteres proteges
352
-	$letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
353
-
354
-	// pipeline
355
-	$letexte = pipeline('post_typo', $letexte);
356
-
357
-	# un message pour abs_url - on est passe en mode texte
358
-	$GLOBALS['mode_abs_url'] = 'texte';
359
-
360
-	return $letexte;
310
+    // Plus vite !
311
+    if (!$letexte) {
312
+        return $letexte;
313
+    }
314
+
315
+    $letexte = pipeline('pre_typo', $letexte);
316
+
317
+    // Caracteres de controle "illegaux"
318
+    $letexte = corriger_caracteres($letexte);
319
+
320
+    // Proteger les caracteres typographiques a l'interieur des tags html
321
+    if (preg_match_all(_TYPO_BALISE, $letexte, $regs, PREG_SET_ORDER)) {
322
+        foreach ($regs as $reg) {
323
+            $insert = $reg[0];
324
+            // hack: on transforme les caracteres a proteger en les remplacant
325
+            // par des caracteres "illegaux". (cf corriger_caracteres())
326
+            $insert = strtr($insert, _TYPO_PROTEGER, _TYPO_PROTECTEUR);
327
+            $letexte = str_replace($reg[0], $insert, $letexte);
328
+        }
329
+    }
330
+
331
+    // trouver les blocs idiomes et les traiter à part
332
+    $letexte = extraire_idiome($ei = $letexte, $lang, true);
333
+    $ei = ($ei !== $letexte);
334
+
335
+    // trouver les blocs multi et les traiter a part
336
+    $letexte = extraire_multi($em = $letexte, $lang, true);
337
+    $em = ($em !== $letexte);
338
+
339
+    // Charger & appliquer les fonctions de typographie
340
+    $typographie = charger_fonction(lang_typo($lang), 'typographie');
341
+    $letexte = $typographie($letexte);
342
+
343
+    // Les citations en une autre langue, s'il y a lieu
344
+    if ($em) {
345
+        $letexte = echappe_retour($letexte, 'multi');
346
+    }
347
+    if ($ei) {
348
+        $letexte = echappe_retour($letexte, 'idiome');
349
+    }
350
+
351
+    // Retablir les caracteres proteges
352
+    $letexte = strtr($letexte, _TYPO_PROTECTEUR, _TYPO_PROTEGER);
353
+
354
+    // pipeline
355
+    $letexte = pipeline('post_typo', $letexte);
356
+
357
+    # un message pour abs_url - on est passe en mode texte
358
+    $GLOBALS['mode_abs_url'] = 'texte';
359
+
360
+    return $letexte;
361 361
 }
362 362
 
363 363
 
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
  * @return string
374 374
  */
375 375
 function paragrapher($letexte, $forcer = true) {
376
-	return $letexte;
376
+    return $letexte;
377 377
 }
378 378
 
379 379
 /**
@@ -385,11 +385,11 @@  discard block
 block discarded – undo
385 385
  * @return string Texte
386 386
  **/
387 387
 function traiter_retours_chariots($letexte) {
388
-	$letexte = preg_replace(",\r\n?,S", "\n", $letexte);
389
-	$letexte = preg_replace(',<p[>[:space:]],iS', "\n\n\\0", $letexte);
390
-	$letexte = preg_replace(',</p[>[:space:]],iS', "\\0\n\n", $letexte);
388
+    $letexte = preg_replace(",\r\n?,S", "\n", $letexte);
389
+    $letexte = preg_replace(',<p[>[:space:]],iS', "\n\n\\0", $letexte);
390
+    $letexte = preg_replace(',</p[>[:space:]],iS', "\\0\n\n", $letexte);
391 391
 
392
-	return $letexte;
392
+    return $letexte;
393 393
 }
394 394
 
395 395
 
@@ -415,39 +415,39 @@  discard block
 block discarded – undo
415 415
  *     Texte transformé
416 416
  **/
417 417
 function propre($t, $connect = null, $env = []) {
418
-	// les appels directs a cette fonction depuis le php de l'espace
419
-	// prive etant historiquement ecrits sans argment $connect
420
-	// on utilise la presence de celui-ci pour distinguer les cas
421
-	// ou il faut passer interdire_script explicitement
422
-	// les appels dans les squelettes (de l'espace prive) fournissant un $connect
423
-	// ne seront pas perturbes
424
-	$interdire_script = false;
425
-	if (is_null($connect)) {
426
-		$connect = '';
427
-		$interdire_script = true;
428
-	}
429
-
430
-	if (!$t) {
431
-		return strval($t);
432
-	}
433
-
434
-	// Dans l'espace prive on se mefie de tout contenu dangereux
435
-	// avant echappement des balises <html>
436
-	// https://core.spip.net/issues/3371
437
-	// et aussi dans l'espace public si la globale filtrer_javascript = -1
438
-	// https://core.spip.net/issues/4166
439
-	if (
440
-		$interdire_script
441
-		or $GLOBALS['filtrer_javascript'] == -1
442
-		or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
443
-		or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript'] <= 0)
444
-	) {
445
-		$t = echapper_html_suspect($t, false);
446
-	}
447
-	$t = echappe_html($t);
448
-	$t = expanser_liens($t, $connect, $env);
449
-	$t = traiter_raccourcis($t);
450
-	$t = echappe_retour_modeles($t, $interdire_script);
451
-
452
-	return $t;
418
+    // les appels directs a cette fonction depuis le php de l'espace
419
+    // prive etant historiquement ecrits sans argment $connect
420
+    // on utilise la presence de celui-ci pour distinguer les cas
421
+    // ou il faut passer interdire_script explicitement
422
+    // les appels dans les squelettes (de l'espace prive) fournissant un $connect
423
+    // ne seront pas perturbes
424
+    $interdire_script = false;
425
+    if (is_null($connect)) {
426
+        $connect = '';
427
+        $interdire_script = true;
428
+    }
429
+
430
+    if (!$t) {
431
+        return strval($t);
432
+    }
433
+
434
+    // Dans l'espace prive on se mefie de tout contenu dangereux
435
+    // avant echappement des balises <html>
436
+    // https://core.spip.net/issues/3371
437
+    // et aussi dans l'espace public si la globale filtrer_javascript = -1
438
+    // https://core.spip.net/issues/4166
439
+    if (
440
+        $interdire_script
441
+        or $GLOBALS['filtrer_javascript'] == -1
442
+        or (isset($env['espace_prive']) and $env['espace_prive'] and $GLOBALS['filtrer_javascript'] <= 0)
443
+        or (isset($env['wysiwyg']) and $env['wysiwyg'] and $GLOBALS['filtrer_javascript'] <= 0)
444
+    ) {
445
+        $t = echapper_html_suspect($t, false);
446
+    }
447
+    $t = echappe_html($t);
448
+    $t = expanser_liens($t, $connect, $env);
449
+    $t = traiter_raccourcis($t);
450
+    $t = echappe_retour_modeles($t, $interdire_script);
451
+
452
+    return $t;
453 453
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
 	foreach (['script', 'iframe'] as $tag) {
106 106
 		if (
107 107
 			stripos($t, (string) "<$tag") !== false
108
-			and preg_match_all(',<' . $tag . '.*?($|</' . $tag . '.),isS', $t, $r, PREG_SET_ORDER)
108
+			and preg_match_all(',<'.$tag.'.*?($|</'.$tag.'.),isS', $t, $r, PREG_SET_ORDER)
109 109
 		) {
110 110
 			foreach ($r as $regs) {
111 111
 				$t = str_replace(
112 112
 					$regs[0],
113
-					"<code$class>" . nl2br(spip_htmlspecialchars($regs[0])) . '</code>',
113
+					"<code$class>".nl2br(spip_htmlspecialchars($regs[0])).'</code>',
114 114
 					$t
115 115
 				);
116 116
 			}
@@ -163,10 +163,10 @@  discard block
 block discarded – undo
163 163
 	}
164 164
 
165 165
 	// echapper les tags asp/php
166
-	$t = str_replace('<' . '%', '&lt;%', $arg);
166
+	$t = str_replace('<'.'%', '&lt;%', $arg);
167 167
 
168 168
 	// echapper le php
169
-	$t = str_replace('<' . '?', '&lt;?', $t);
169
+	$t = str_replace('<'.'?', '&lt;?', $t);
170 170
 
171 171
 	// echapper le < script language=php >
172 172
 	$t = preg_replace(',<(script\b[^>]+\blanguage\b[^\w>]+php\b),UimsS', '&lt;\1', $t);
@@ -188,10 +188,10 @@  discard block
 block discarded – undo
188 188
 
189 189
 	// Reinserer les echappements des modeles
190 190
 	if (defined('_PROTEGE_JS_MODELES')) {
191
-		$t = echappe_retour($t, 'javascript' . _PROTEGE_JS_MODELES);
191
+		$t = echappe_retour($t, 'javascript'._PROTEGE_JS_MODELES);
192 192
 	}
193 193
 	if (defined('_PROTEGE_PHP_MODELES')) {
194
-		$t = echappe_retour($t, 'php' . _PROTEGE_PHP_MODELES);
194
+		$t = echappe_retour($t, 'php'._PROTEGE_PHP_MODELES);
195 195
 	}
196 196
 
197 197
 	return $dejavu[$mode_filtre][$arg] = $t;
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 define('_TYPO_PROTEGER', "!':;?~%-");
290 290
 define('_TYPO_PROTECTEUR', "\x1\x2\x3\x4\x5\x6\x7\x8");
291 291
 
292
-define('_TYPO_BALISE', ',</?[a-z!][^<>]*[' . preg_quote(_TYPO_PROTEGER) . '][^<>]*>,imsS');
292
+define('_TYPO_BALISE', ',</?[a-z!][^<>]*['.preg_quote(_TYPO_PROTEGER).'][^<>]*>,imsS');
293 293
 
294 294
 /**
295 295
  * Corrige la typographie
Please login to merge, or discard this patch.
ecrire/inc/queue.php 2 patches
Indentation   +524 added lines, -524 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Queue
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 define('_JQ_SCHEDULED', 1);
@@ -50,103 +50,103 @@  discard block
 block discarded – undo
50 50
  *  id of job
51 51
  */
52 52
 function queue_add_job(
53
-	$function,
54
-	$description,
55
-	$arguments = [],
56
-	$file = '',
57
-	$no_duplicate = false,
58
-	$time = 0,
59
-	$priority = 0
53
+    $function,
54
+    $description,
55
+    $arguments = [],
56
+    $file = '',
57
+    $no_duplicate = false,
58
+    $time = 0,
59
+    $priority = 0
60 60
 ) {
61
-	include_spip('base/abstract_sql');
62
-
63
-	// cas pourri de ecrire/action/editer_site avec l'option reload=oui
64
-	if (defined('_GENIE_SYNDIC_NOW')) {
65
-		$arguments['id_syndic'] = _GENIE_SYNDIC_NOW;
66
-	}
67
-
68
-	// serialiser les arguments
69
-	$arguments = serialize($arguments);
70
-	$md5args = md5($arguments);
71
-
72
-	// si pas de date programee, des que possible
73
-	$duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
74
-	if (!$time) {
75
-		$time = time();
76
-		$duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
77
-	}
78
-	$date = date('Y-m-d H:i:s', $time);
79
-
80
-	$set_job = [
81
-		'fonction' => $function,
82
-		'descriptif' => $description,
83
-		'args' => $arguments,
84
-		'md5args' => $md5args,
85
-		'inclure' => $file,
86
-		'priorite' => max(-10, min(10, intval($priority))),
87
-		'date' => $date,
88
-		'status' => _JQ_SCHEDULED,
89
-	];
90
-	// si option ne pas dupliquer, regarder si la fonction existe deja
91
-	// avec les memes args et file
92
-	if (
93
-		$no_duplicate
94
-		and
95
-		$id_job = sql_getfetsel(
96
-			'id_job',
97
-			'spip_jobs',
98
-			$duplicate_where =
99
-				$duplicate_where . 'fonction=' . sql_quote($function)
100
-				. (($no_duplicate === 'function_only') ? '' :
101
-			' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
102
-		)
103
-	) {
104
-		return $id_job;
105
-	}
106
-
107
-	$id_job = sql_insertq('spip_jobs', $set_job);
108
-	// en cas de concurrence, deux process peuvent arriver jusqu'ici en parallele
109
-	// avec le meme job unique a inserer. Dans ce cas, celui qui a eu l'id le plus grand
110
-	// doit s'effacer
111
-	if (
112
-		$no_duplicate
113
-		and
114
-		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
115
-	) {
116
-		sql_delete('spip_jobs', 'id_job=' . intval($id_job));
117
-
118
-		return $id_prev;
119
-	}
120
-
121
-	// verifier la non duplication qui peut etre problematique en cas de concurence
122
-	// il faut dans ce cas que seul le dernier ajoute se supprime !
123
-
124
-	// une option de debug pour verifier que les arguments en base sont bons
125
-	// ie cas d'un char non acceptables sur certains type de champs
126
-	// qui coupe la valeur
127
-	if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
-		$args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
129
-		if ($args !== $arguments) {
130
-			spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
131
-				$arguments,
132
-				true
133
-			), 'queue');
134
-		}
135
-	}
136
-
137
-	if ($id_job) {
138
-		queue_update_next_job_time($time);
139
-	}
140
-	// si la mise en file d'attente du job echoue,
141
-	// il ne faut pas perdre l'execution de la fonction
142
-	// on la lance immediatement, c'est un fallback
143
-	// sauf en cas d'upgrade necessaire (table spip_jobs inexistante)
144
-	elseif ($GLOBALS['meta']['version_installee'] == $GLOBALS['spip_version_base']) {
145
-		$set_job['id_job'] = 0;
146
-		queue_start_job($set_job);
147
-	}
148
-
149
-	return $id_job;
61
+    include_spip('base/abstract_sql');
62
+
63
+    // cas pourri de ecrire/action/editer_site avec l'option reload=oui
64
+    if (defined('_GENIE_SYNDIC_NOW')) {
65
+        $arguments['id_syndic'] = _GENIE_SYNDIC_NOW;
66
+    }
67
+
68
+    // serialiser les arguments
69
+    $arguments = serialize($arguments);
70
+    $md5args = md5($arguments);
71
+
72
+    // si pas de date programee, des que possible
73
+    $duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
74
+    if (!$time) {
75
+        $time = time();
76
+        $duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
77
+    }
78
+    $date = date('Y-m-d H:i:s', $time);
79
+
80
+    $set_job = [
81
+        'fonction' => $function,
82
+        'descriptif' => $description,
83
+        'args' => $arguments,
84
+        'md5args' => $md5args,
85
+        'inclure' => $file,
86
+        'priorite' => max(-10, min(10, intval($priority))),
87
+        'date' => $date,
88
+        'status' => _JQ_SCHEDULED,
89
+    ];
90
+    // si option ne pas dupliquer, regarder si la fonction existe deja
91
+    // avec les memes args et file
92
+    if (
93
+        $no_duplicate
94
+        and
95
+        $id_job = sql_getfetsel(
96
+            'id_job',
97
+            'spip_jobs',
98
+            $duplicate_where =
99
+                $duplicate_where . 'fonction=' . sql_quote($function)
100
+                . (($no_duplicate === 'function_only') ? '' :
101
+            ' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
102
+        )
103
+    ) {
104
+        return $id_job;
105
+    }
106
+
107
+    $id_job = sql_insertq('spip_jobs', $set_job);
108
+    // en cas de concurrence, deux process peuvent arriver jusqu'ici en parallele
109
+    // avec le meme job unique a inserer. Dans ce cas, celui qui a eu l'id le plus grand
110
+    // doit s'effacer
111
+    if (
112
+        $no_duplicate
113
+        and
114
+        $id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
115
+    ) {
116
+        sql_delete('spip_jobs', 'id_job=' . intval($id_job));
117
+
118
+        return $id_prev;
119
+    }
120
+
121
+    // verifier la non duplication qui peut etre problematique en cas de concurence
122
+    // il faut dans ce cas que seul le dernier ajoute se supprime !
123
+
124
+    // une option de debug pour verifier que les arguments en base sont bons
125
+    // ie cas d'un char non acceptables sur certains type de champs
126
+    // qui coupe la valeur
127
+    if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
+        $args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
129
+        if ($args !== $arguments) {
130
+            spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
131
+                $arguments,
132
+                true
133
+            ), 'queue');
134
+        }
135
+    }
136
+
137
+    if ($id_job) {
138
+        queue_update_next_job_time($time);
139
+    }
140
+    // si la mise en file d'attente du job echoue,
141
+    // il ne faut pas perdre l'execution de la fonction
142
+    // on la lance immediatement, c'est un fallback
143
+    // sauf en cas d'upgrade necessaire (table spip_jobs inexistante)
144
+    elseif ($GLOBALS['meta']['version_installee'] == $GLOBALS['spip_version_base']) {
145
+        $set_job['id_job'] = 0;
146
+        queue_start_job($set_job);
147
+    }
148
+
149
+    return $id_job;
150 150
 }
151 151
 
152 152
 /**
@@ -155,11 +155,11 @@  discard block
 block discarded – undo
155 155
  * @return void
156 156
  */
157 157
 function queue_purger() {
158
-	include_spip('base/abstract_sql');
159
-	sql_delete('spip_jobs');
160
-	sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
161
-	include_spip('inc/genie');
162
-	genie_queue_watch_dist();
158
+    include_spip('base/abstract_sql');
159
+    sql_delete('spip_jobs');
160
+    sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
161
+    include_spip('inc/genie');
162
+    genie_queue_watch_dist();
163 163
 }
164 164
 
165 165
 /**
@@ -170,25 +170,25 @@  discard block
 block discarded – undo
170 170
  * @return int|bool
171 171
  */
172 172
 function queue_remove_job($id_job) {
173
-	include_spip('base/abstract_sql');
174
-
175
-	if (
176
-		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
-		and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
178
-	) {
179
-		queue_unlink_job($id_job);
180
-		// est-ce une tache cron qu'il faut relancer ?
181
-		if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
182
-			// relancer avec les nouveaux arguments de temps
183
-			include_spip('inc/genie');
184
-			// relancer avec la periode prevue
185
-			queue_genie_replan_job($row['fonction'], $periode, strtotime($row['date']));
186
-		}
187
-		queue_update_next_job_time();
188
-		return $res;
189
-	}
190
-
191
-	return false;
173
+    include_spip('base/abstract_sql');
174
+
175
+    if (
176
+        $row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
+        and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
178
+    ) {
179
+        queue_unlink_job($id_job);
180
+        // est-ce une tache cron qu'il faut relancer ?
181
+        if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
182
+            // relancer avec les nouveaux arguments de temps
183
+            include_spip('inc/genie');
184
+            // relancer avec la periode prevue
185
+            queue_genie_replan_job($row['fonction'], $periode, strtotime($row['date']));
186
+        }
187
+        queue_update_next_job_time();
188
+        return $res;
189
+    }
190
+
191
+    return false;
192 192
 }
193 193
 
194 194
 /**
@@ -201,18 +201,18 @@  discard block
 block discarded – undo
201 201
  *  ou un tableau composé de tableaux simples pour lieur plusieurs objets en une fois
202 202
  */
203 203
 function queue_link_job($id_job, $objets) {
204
-	include_spip('base/abstract_sql');
205
-
206
-	if (is_array($objets) and count($objets)) {
207
-		if (is_array(reset($objets))) {
208
-			foreach ($objets as $k => $o) {
209
-				$objets[$k]['id_job'] = $id_job;
210
-			}
211
-			sql_insertq_multi('spip_jobs_liens', $objets);
212
-		} else {
213
-			sql_insertq('spip_jobs_liens', array_merge(['id_job' => $id_job], $objets));
214
-		}
215
-	}
204
+    include_spip('base/abstract_sql');
205
+
206
+    if (is_array($objets) and count($objets)) {
207
+        if (is_array(reset($objets))) {
208
+            foreach ($objets as $k => $o) {
209
+                $objets[$k]['id_job'] = $id_job;
210
+            }
211
+            sql_insertq_multi('spip_jobs_liens', $objets);
212
+        } else {
213
+            sql_insertq('spip_jobs_liens', array_merge(['id_job' => $id_job], $objets));
214
+        }
215
+    }
216 216
 }
217 217
 
218 218
 /**
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
  *  resultat du sql_delete
225 225
  */
226 226
 function queue_unlink_job($id_job) {
227
-	return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
227
+    return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
228 228
 }
229 229
 
230 230
 /**
@@ -237,84 +237,84 @@  discard block
 block discarded – undo
237 237
  */
238 238
 function queue_start_job($row) {
239 239
 
240
-	// deserialiser les arguments
241
-	$args = unserialize($row['args']);
242
-	if ($args === false) {
243
-		spip_log('arguments job errones ' . var_export($row, true), 'queue');
244
-		$args = [];
245
-	}
246
-
247
-	$fonction = $row['fonction'];
248
-	if (strlen($inclure = trim($row['inclure']))) {
249
-		if (substr($inclure, -1) == '/') { // c'est un chemin pour charger_fonction
250
-			$f = charger_fonction($fonction, rtrim($inclure, '/'), false);
251
-			if ($f) {
252
-				$fonction = $f;
253
-			}
254
-		} else {
255
-			include_spip($inclure);
256
-		}
257
-	}
258
-
259
-	if (!function_exists($fonction)) {
260
-		spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
261
-
262
-		return false;
263
-	}
264
-
265
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
266
-	switch (is_countable($args) ? count($args) : 0) {
267
-		case 0:
268
-			$res = $fonction();
269
-			break;
270
-		case 1:
271
-			$res = $fonction($args[0]);
272
-			break;
273
-		case 2:
274
-			$res = $fonction($args[0], $args[1]);
275
-			break;
276
-		case 3:
277
-			$res = $fonction($args[0], $args[1], $args[2]);
278
-			break;
279
-		case 4:
280
-			$res = $fonction($args[0], $args[1], $args[2], $args[3]);
281
-			break;
282
-		case 5:
283
-			$res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4]);
284
-			break;
285
-		case 6:
286
-			$res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]);
287
-			break;
288
-		case 7:
289
-			$res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]);
290
-			break;
291
-		case 8:
292
-			$res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]);
293
-			break;
294
-		case 9:
295
-			$res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7], $args[8]);
296
-			break;
297
-		case 10:
298
-			$res = $fonction(
299
-				$args[0],
300
-				$args[1],
301
-				$args[2],
302
-				$args[3],
303
-				$args[4],
304
-				$args[5],
305
-				$args[6],
306
-				$args[7],
307
-				$args[8],
308
-				$args[9]
309
-			);
310
-			break;
311
-		default:
312
-			# plus lent mais completement generique
313
-			$res = call_user_func_array($fonction, $args);
314
-	}
315
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
316
-
317
-	return $res;
240
+    // deserialiser les arguments
241
+    $args = unserialize($row['args']);
242
+    if ($args === false) {
243
+        spip_log('arguments job errones ' . var_export($row, true), 'queue');
244
+        $args = [];
245
+    }
246
+
247
+    $fonction = $row['fonction'];
248
+    if (strlen($inclure = trim($row['inclure']))) {
249
+        if (substr($inclure, -1) == '/') { // c'est un chemin pour charger_fonction
250
+            $f = charger_fonction($fonction, rtrim($inclure, '/'), false);
251
+            if ($f) {
252
+                $fonction = $f;
253
+            }
254
+        } else {
255
+            include_spip($inclure);
256
+        }
257
+    }
258
+
259
+    if (!function_exists($fonction)) {
260
+        spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
261
+
262
+        return false;
263
+    }
264
+
265
+    spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
266
+    switch (is_countable($args) ? count($args) : 0) {
267
+        case 0:
268
+            $res = $fonction();
269
+            break;
270
+        case 1:
271
+            $res = $fonction($args[0]);
272
+            break;
273
+        case 2:
274
+            $res = $fonction($args[0], $args[1]);
275
+            break;
276
+        case 3:
277
+            $res = $fonction($args[0], $args[1], $args[2]);
278
+            break;
279
+        case 4:
280
+            $res = $fonction($args[0], $args[1], $args[2], $args[3]);
281
+            break;
282
+        case 5:
283
+            $res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4]);
284
+            break;
285
+        case 6:
286
+            $res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]);
287
+            break;
288
+        case 7:
289
+            $res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]);
290
+            break;
291
+        case 8:
292
+            $res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]);
293
+            break;
294
+        case 9:
295
+            $res = $fonction($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7], $args[8]);
296
+            break;
297
+        case 10:
298
+            $res = $fonction(
299
+                $args[0],
300
+                $args[1],
301
+                $args[2],
302
+                $args[3],
303
+                $args[4],
304
+                $args[5],
305
+                $args[6],
306
+                $args[7],
307
+                $args[8],
308
+                $args[9]
309
+            );
310
+            break;
311
+        default:
312
+            # plus lent mais completement generique
313
+            $res = call_user_func_array($fonction, $args);
314
+    }
315
+    spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
316
+
317
+    return $res;
318 318
 }
319 319
 
320 320
 /**
@@ -341,89 +341,89 @@  discard block
 block discarded – undo
341 341
  *     - true : une planification a été faite.
342 342
  */
343 343
 function queue_schedule($force_jobs = null) {
344
-	$time = time();
345
-	if (defined('_DEBUG_BLOCK_QUEUE')) {
346
-		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
347
-
348
-		return;
349
-	}
350
-
351
-	// rien a faire si le prochain job est encore dans le futur
352
-	if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
353
-		spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
354
-
355
-		return;
356
-	}
357
-
358
-	include_spip('base/abstract_sql');
359
-	// on ne peut rien faire si pas de connexion SQL
360
-	if (!spip_connect()) {
361
-		return false;
362
-	}
363
-
364
-	if (!defined('_JQ_MAX_JOBS_TIME_TO_EXECUTE')) {
365
-		$max_time = ini_get('max_execution_time') / 2;
366
-		// valeur conservatrice si on a pas reussi a lire le max_execution_time
367
-		if (!$max_time) {
368
-			$max_time = 5;
369
-		}
370
-		define('_JQ_MAX_JOBS_TIME_TO_EXECUTE', min($max_time, 15)); // une valeur maxi en temps.
371
-	}
372
-	$end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
373
-
374
-	spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
375
-
376
-	if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
377
-		define('_JQ_MAX_JOBS_EXECUTE', 200);
378
-	}
379
-	$nbj = 0;
380
-	// attraper les jobs
381
-	// dont la date est passee (echus en attente),
382
-	// par ordre :
383
-	//	- de priorite
384
-	//	- de date
385
-	// lorsqu'un job cron n'a pas fini, sa priorite est descendue
386
-	// pour qu'il ne bloque pas les autres jobs en attente
387
-	if (is_array($force_jobs) and count($force_jobs)) {
388
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
389
-	} else {
390
-		$now = date('Y-m-d H:i:s', $time);
391
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
392
-	}
393
-
394
-	register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
395
-	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
396
-	do {
397
-		if ($row = array_shift($res)) {
398
-			$nbj++;
399
-			// il faut un verrou, a base de sql_delete
400
-			if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
401
-				#spip_log("JQ schedule job ".$nbj." OK",'jq');
402
-				// on reinsert dans la base aussitot avec un status=_JQ_PENDING
403
-				$row['status'] = _JQ_PENDING;
404
-				$row['date'] = date('Y-m-d H:i:s', $time);
405
-				sql_insertq('spip_jobs', $row);
406
-
407
-				// on a la main sur le job :
408
-				// l'executer
409
-				$result = queue_start_job($row);
410
-
411
-				$time = time();
412
-				queue_close_job($row, $time, $result);
413
-			}
414
-		}
415
-		spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
416
-	} while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
417
-	spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
418
-
419
-	if ($row = array_shift($res)) {
420
-		queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
421
-		spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
422
-	} else {
423
-		queue_update_next_job_time();
424
-	}
425
-
426
-	return true;
344
+    $time = time();
345
+    if (defined('_DEBUG_BLOCK_QUEUE')) {
346
+        spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
347
+
348
+        return;
349
+    }
350
+
351
+    // rien a faire si le prochain job est encore dans le futur
352
+    if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
353
+        spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
354
+
355
+        return;
356
+    }
357
+
358
+    include_spip('base/abstract_sql');
359
+    // on ne peut rien faire si pas de connexion SQL
360
+    if (!spip_connect()) {
361
+        return false;
362
+    }
363
+
364
+    if (!defined('_JQ_MAX_JOBS_TIME_TO_EXECUTE')) {
365
+        $max_time = ini_get('max_execution_time') / 2;
366
+        // valeur conservatrice si on a pas reussi a lire le max_execution_time
367
+        if (!$max_time) {
368
+            $max_time = 5;
369
+        }
370
+        define('_JQ_MAX_JOBS_TIME_TO_EXECUTE', min($max_time, 15)); // une valeur maxi en temps.
371
+    }
372
+    $end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
373
+
374
+    spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
375
+
376
+    if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
377
+        define('_JQ_MAX_JOBS_EXECUTE', 200);
378
+    }
379
+    $nbj = 0;
380
+    // attraper les jobs
381
+    // dont la date est passee (echus en attente),
382
+    // par ordre :
383
+    //	- de priorite
384
+    //	- de date
385
+    // lorsqu'un job cron n'a pas fini, sa priorite est descendue
386
+    // pour qu'il ne bloque pas les autres jobs en attente
387
+    if (is_array($force_jobs) and count($force_jobs)) {
388
+        $cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
389
+    } else {
390
+        $now = date('Y-m-d H:i:s', $time);
391
+        $cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
392
+    }
393
+
394
+    register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
395
+    $res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
396
+    do {
397
+        if ($row = array_shift($res)) {
398
+            $nbj++;
399
+            // il faut un verrou, a base de sql_delete
400
+            if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
401
+                #spip_log("JQ schedule job ".$nbj." OK",'jq');
402
+                // on reinsert dans la base aussitot avec un status=_JQ_PENDING
403
+                $row['status'] = _JQ_PENDING;
404
+                $row['date'] = date('Y-m-d H:i:s', $time);
405
+                sql_insertq('spip_jobs', $row);
406
+
407
+                // on a la main sur le job :
408
+                // l'executer
409
+                $result = queue_start_job($row);
410
+
411
+                $time = time();
412
+                queue_close_job($row, $time, $result);
413
+            }
414
+        }
415
+        spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
416
+    } while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
417
+    spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
418
+
419
+    if ($row = array_shift($res)) {
420
+        queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
421
+        spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
422
+    } else {
423
+        queue_update_next_job_time();
424
+    }
425
+
426
+    return true;
427 427
 }
428 428
 
429 429
 /**
@@ -441,21 +441,21 @@  discard block
 block discarded – undo
441 441
  * @param int $result
442 442
  */
443 443
 function queue_close_job(&$row, $time, $result = 0) {
444
-	// est-ce une tache cron qu'il faut relancer ?
445
-	if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
446
-		// relancer avec les nouveaux arguments de temps
447
-		include_spip('inc/genie');
448
-		if ($result < 0) { // relancer tout de suite, mais en baissant la priorite
449
-		queue_genie_replan_job($row['fonction'], $periode, 0 - $result, null, $row['priorite'] - 1);
450
-		} else // relancer avec la periode prevue
451
-		{
452
-			queue_genie_replan_job($row['fonction'], $periode, $time);
453
-		}
454
-	}
455
-	// purger ses liens eventuels avec des objets
456
-	sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
457
-	// supprimer le job fini
458
-	sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
444
+    // est-ce une tache cron qu'il faut relancer ?
445
+    if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
446
+        // relancer avec les nouveaux arguments de temps
447
+        include_spip('inc/genie');
448
+        if ($result < 0) { // relancer tout de suite, mais en baissant la priorite
449
+        queue_genie_replan_job($row['fonction'], $periode, 0 - $result, null, $row['priorite'] - 1);
450
+        } else // relancer avec la periode prevue
451
+        {
452
+            queue_genie_replan_job($row['fonction'], $periode, $time);
453
+        }
454
+    }
455
+    // purger ses liens eventuels avec des objets
456
+    sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
457
+    // supprimer le job fini
458
+    sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
459 459
 }
460 460
 
461 461
 /**
@@ -465,10 +465,10 @@  discard block
 block discarded – undo
465 465
  * @uses queue_update_next_job_time()
466 466
  */
467 467
 function queue_error_handler() {
468
-	// se remettre dans le bon dossier, car Apache le change parfois (toujours?)
469
-	chdir(_ROOT_CWD);
468
+    // se remettre dans le bon dossier, car Apache le change parfois (toujours?)
469
+    chdir(_ROOT_CWD);
470 470
 
471
-	queue_update_next_job_time();
471
+    queue_update_next_job_time();
472 472
 }
473 473
 
474 474
 
@@ -485,18 +485,18 @@  discard block
 block discarded – undo
485 485
  *     Périodicité de la tâche en secondes, si tâche périodique, sinon false.
486 486
  */
487 487
 function queue_is_cron_job($function, $inclure) {
488
-	static $taches = null;
489
-	if (strncmp($inclure, 'genie/', 6) == 0) {
490
-		if (is_null($taches)) {
491
-			include_spip('inc/genie');
492
-			$taches = taches_generales();
493
-		}
494
-		if (isset($taches[$function])) {
495
-			return $taches[$function];
496
-		}
497
-	}
498
-
499
-	return false;
488
+    static $taches = null;
489
+    if (strncmp($inclure, 'genie/', 6) == 0) {
490
+        if (is_null($taches)) {
491
+            include_spip('inc/genie');
492
+            $taches = taches_generales();
493
+        }
494
+        if (isset($taches[$function])) {
495
+            return $taches[$function];
496
+        }
497
+    }
498
+
499
+    return false;
500 500
 }
501 501
 
502 502
 /**
@@ -510,62 +510,62 @@  discard block
 block discarded – undo
510 510
  *  temps de la tache ajoutee ou 0 pour ASAP
511 511
  */
512 512
 function queue_update_next_job_time($next_time = null) {
513
-	static $nb_jobs_scheduled = null;
514
-	static $deja_la = false;
515
-	// prendre le min des $next_time que l'on voit passer ici, en cas de reentrance
516
-	static $next = null;
517
-	// queue_close_job peut etre reentrant ici
518
-	if ($deja_la) {
519
-		return;
520
-	}
521
-	$deja_la = true;
522
-
523
-	include_spip('base/abstract_sql');
524
-	$time = time();
525
-
526
-	// traiter les jobs morts au combat (_JQ_PENDING depuis plus de 180s)
527
-	// pour cause de timeout ou autre erreur fatale
528
-	$res = sql_allfetsel(
529
-		'*',
530
-		'spip_jobs',
531
-		'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
532
-	);
533
-	if (is_array($res)) {
534
-		foreach ($res as $row) {
535
-			queue_close_job($row, $time);
536
-			spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
537
-		}
538
-	}
539
-
540
-	// chercher la date du prochain job si pas connu
541
-	if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
542
-		$date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
543
-		$next = strtotime($date);
544
-	}
545
-	if (!is_null($next_time)) {
546
-		if (is_null($next) or $next > $next_time) {
547
-			$next = $next_time;
548
-		}
549
-	}
550
-
551
-	if ($next) {
552
-		if (is_null($nb_jobs_scheduled)) {
553
-			$nb_jobs_scheduled = sql_countsel(
554
-				'spip_jobs',
555
-				'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
556
-			);
557
-		} elseif ($next <= $time) {
558
-			$nb_jobs_scheduled++;
559
-		}
560
-		// si trop de jobs en attente, on force la purge en fin de hit
561
-		// pour assurer le coup
562
-		if ($nb_jobs_scheduled > (defined('_JQ_NB_JOBS_OVERFLOW') ? _JQ_NB_JOBS_OVERFLOW : 10000)) {
563
-			define('_DIRECT_CRON_FORCE', true);
564
-		}
565
-	}
566
-
567
-	queue_set_next_job_time($next);
568
-	$deja_la = false;
513
+    static $nb_jobs_scheduled = null;
514
+    static $deja_la = false;
515
+    // prendre le min des $next_time que l'on voit passer ici, en cas de reentrance
516
+    static $next = null;
517
+    // queue_close_job peut etre reentrant ici
518
+    if ($deja_la) {
519
+        return;
520
+    }
521
+    $deja_la = true;
522
+
523
+    include_spip('base/abstract_sql');
524
+    $time = time();
525
+
526
+    // traiter les jobs morts au combat (_JQ_PENDING depuis plus de 180s)
527
+    // pour cause de timeout ou autre erreur fatale
528
+    $res = sql_allfetsel(
529
+        '*',
530
+        'spip_jobs',
531
+        'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
532
+    );
533
+    if (is_array($res)) {
534
+        foreach ($res as $row) {
535
+            queue_close_job($row, $time);
536
+            spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
537
+        }
538
+    }
539
+
540
+    // chercher la date du prochain job si pas connu
541
+    if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
542
+        $date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
543
+        $next = strtotime($date);
544
+    }
545
+    if (!is_null($next_time)) {
546
+        if (is_null($next) or $next > $next_time) {
547
+            $next = $next_time;
548
+        }
549
+    }
550
+
551
+    if ($next) {
552
+        if (is_null($nb_jobs_scheduled)) {
553
+            $nb_jobs_scheduled = sql_countsel(
554
+                'spip_jobs',
555
+                'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
556
+            );
557
+        } elseif ($next <= $time) {
558
+            $nb_jobs_scheduled++;
559
+        }
560
+        // si trop de jobs en attente, on force la purge en fin de hit
561
+        // pour assurer le coup
562
+        if ($nb_jobs_scheduled > (defined('_JQ_NB_JOBS_OVERFLOW') ? _JQ_NB_JOBS_OVERFLOW : 10000)) {
563
+            define('_DIRECT_CRON_FORCE', true);
564
+        }
565
+    }
566
+
567
+    queue_set_next_job_time($next);
568
+    $deja_la = false;
569 569
 }
570 570
 
571 571
 
@@ -576,26 +576,26 @@  discard block
 block discarded – undo
576 576
  */
577 577
 function queue_set_next_job_time($next) {
578 578
 
579
-	// utiliser le temps courant reel plutot que temps de la requete ici
580
-	$time = time();
581
-
582
-	// toujours relire la valeur pour comparer, pour tenir compte des maj concourrantes
583
-	// et ne mettre a jour que si il y a un interet a le faire
584
-	// permet ausis d'initialiser le nom de fichier a coup sur
585
-	$curr_next = $_SERVER['REQUEST_TIME'] + max(0, queue_sleep_time_to_next_job(true));
586
-	if (
587
-		($curr_next <= $time and $next > $time) // le prochain job est dans le futur mais pas la date planifiee actuelle
588
-		or $curr_next > $next // le prochain job est plus tot que la date planifiee actuelle
589
-	) {
590
-		if (function_exists('cache_set') and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
591
-			cache_set(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
592
-		} else {
593
-			ecrire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
594
-		}
595
-		queue_sleep_time_to_next_job($next);
596
-	}
597
-
598
-	return queue_sleep_time_to_next_job();
579
+    // utiliser le temps courant reel plutot que temps de la requete ici
580
+    $time = time();
581
+
582
+    // toujours relire la valeur pour comparer, pour tenir compte des maj concourrantes
583
+    // et ne mettre a jour que si il y a un interet a le faire
584
+    // permet ausis d'initialiser le nom de fichier a coup sur
585
+    $curr_next = $_SERVER['REQUEST_TIME'] + max(0, queue_sleep_time_to_next_job(true));
586
+    if (
587
+        ($curr_next <= $time and $next > $time) // le prochain job est dans le futur mais pas la date planifiee actuelle
588
+        or $curr_next > $next // le prochain job est plus tot que la date planifiee actuelle
589
+    ) {
590
+        if (function_exists('cache_set') and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
591
+            cache_set(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
592
+        } else {
593
+            ecrire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
594
+        }
595
+        queue_sleep_time_to_next_job($next);
596
+    }
597
+
598
+    return queue_sleep_time_to_next_job();
599 599
 }
600 600
 
601 601
 /**
@@ -612,60 +612,60 @@  discard block
 block discarded – undo
612 612
  * @return string
613 613
  */
614 614
 function queue_affichage_cron() {
615
-	$texte = '';
616
-
617
-	$time_to_next = queue_sleep_time_to_next_job();
618
-	// rien a faire si le prochain job est encore dans le futur
619
-	if ($time_to_next > 0 or defined('_DEBUG_BLOCK_QUEUE')) {
620
-		return $texte;
621
-	}
622
-
623
-	// ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
624
-	if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
625
-		return $texte;
626
-	}
627
-
628
-	@touch($lock);
629
-
630
-	// il y a des taches en attentes
631
-	// si depuis plus de 5min, on essaye de lancer le cron par tous les moyens pour rattraper le coup
632
-	// on est sans doute sur un site qui n'autorise pas http sortant ou avec peu de trafic
633
-	$urgent = false;
634
-	if ($time_to_next < -300) {
635
-		$urgent = true;
636
-	}
637
-
638
-	$url_cron = generer_url_action('cron', '', false, true);
639
-
640
-	if (!defined('_HTML_BG_CRON_FORCE') or !_HTML_BG_CRON_FORCE) {
641
-		if (queue_lancer_url_http_async($url_cron) and !$urgent) {
642
-			return $texte;
643
-		}
644
-	}
645
-
646
-	// si deja force, on retourne sans rien
647
-	if (defined('_DIRECT_CRON_FORCE')) {
648
-		return $texte;
649
-	}
650
-
651
-	// si c'est un bot
652
-	// inutile de faire un appel par image background,
653
-	// on force un appel direct en fin de hit
654
-	if ((defined('_IS_BOT') and _IS_BOT)) {
655
-		define('_DIRECT_CRON_FORCE', true);
656
-
657
-		return $texte;
658
-	}
659
-
660
-	if (!defined('_HTML_BG_CRON_INHIB') or !_HTML_BG_CRON_INHIB) {
661
-		// en derniere solution, on insere un appel xhr non bloquant ou une image background dans la page si pas de JS
662
-		$url_cron = generer_url_action('cron');
663
-		$texte = '<!-- SPIP-CRON -->'
664
-		  . "<script>setTimeout(function(){var xo = new XMLHttpRequest();xo.open('GET', '$url_cron', true);xo.send('');},100);</script>"
665
-		  . "<noscript><div style=\"background-image: url('$url_cron');\"></div></noscript>";
666
-	}
667
-
668
-	return $texte;
615
+    $texte = '';
616
+
617
+    $time_to_next = queue_sleep_time_to_next_job();
618
+    // rien a faire si le prochain job est encore dans le futur
619
+    if ($time_to_next > 0 or defined('_DEBUG_BLOCK_QUEUE')) {
620
+        return $texte;
621
+    }
622
+
623
+    // ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
624
+    if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
625
+        return $texte;
626
+    }
627
+
628
+    @touch($lock);
629
+
630
+    // il y a des taches en attentes
631
+    // si depuis plus de 5min, on essaye de lancer le cron par tous les moyens pour rattraper le coup
632
+    // on est sans doute sur un site qui n'autorise pas http sortant ou avec peu de trafic
633
+    $urgent = false;
634
+    if ($time_to_next < -300) {
635
+        $urgent = true;
636
+    }
637
+
638
+    $url_cron = generer_url_action('cron', '', false, true);
639
+
640
+    if (!defined('_HTML_BG_CRON_FORCE') or !_HTML_BG_CRON_FORCE) {
641
+        if (queue_lancer_url_http_async($url_cron) and !$urgent) {
642
+            return $texte;
643
+        }
644
+    }
645
+
646
+    // si deja force, on retourne sans rien
647
+    if (defined('_DIRECT_CRON_FORCE')) {
648
+        return $texte;
649
+    }
650
+
651
+    // si c'est un bot
652
+    // inutile de faire un appel par image background,
653
+    // on force un appel direct en fin de hit
654
+    if ((defined('_IS_BOT') and _IS_BOT)) {
655
+        define('_DIRECT_CRON_FORCE', true);
656
+
657
+        return $texte;
658
+    }
659
+
660
+    if (!defined('_HTML_BG_CRON_INHIB') or !_HTML_BG_CRON_INHIB) {
661
+        // en derniere solution, on insere un appel xhr non bloquant ou une image background dans la page si pas de JS
662
+        $url_cron = generer_url_action('cron');
663
+        $texte = '<!-- SPIP-CRON -->'
664
+            . "<script>setTimeout(function(){var xo = new XMLHttpRequest();xo.open('GET', '$url_cron', true);xo.send('');},100);</script>"
665
+            . "<noscript><div style=\"background-image: url('$url_cron');\"></div></noscript>";
666
+    }
667
+
668
+    return $texte;
669 669
 }
670 670
 
671 671
 /**
@@ -674,73 +674,73 @@  discard block
 block discarded – undo
674 674
  * @return bool : true si l'url a pu être appelée en asynchrone, false sinon
675 675
  */
676 676
 function queue_lancer_url_http_async($url_cron) {
677
-	// methode la plus rapide :
678
-	// Si fsockopen est possible, on lance le cron via un socket en asynchrone
679
-	// si fsockopen echoue (disponibilite serveur, firewall) on essaye pas cURL
680
-	// car on a toutes les chances d'echouer pareil mais sans moyen de le savoir
681
-	// mais on renvoie false direct
682
-	if (function_exists('fsockopen')) {
683
-		$parts = parse_url($url_cron);
684
-
685
-		switch ($parts['scheme']) {
686
-			case 'https':
687
-				$scheme = 'ssl://';
688
-				$port = 443;
689
-				break;
690
-			case 'http':
691
-			default:
692
-				$scheme = '';
693
-				$port = 80;
694
-		}
695
-		$fp = @fsockopen(
696
-			$scheme . $parts['host'],
697
-			$parts['port'] ?? $port,
698
-			$errno,
699
-			$errstr,
700
-			1
701
-		);
702
-
703
-		if ($fp) {
704
-			$host_sent = $parts['host'];
705
-			if (isset($parts['port']) and $parts['port'] !== $port) {
706
-				$host_sent .= ':' . $parts['port'];
707
-			}
708
-			$timeout = 200; // ms
709
-			stream_set_timeout($fp, 0, $timeout * 1000);
710
-			$query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
711
-			$out = 'GET ' . $query . " HTTP/1.1\r\n";
712
-			$out .= 'Host: ' . $host_sent . "\r\n";
713
-			$out .= "Connection: Close\r\n\r\n";
714
-			fwrite($fp, $out);
715
-			spip_timer('read');
716
-			$t = 0;
717
-			// on lit la reponse si possible pour fermer proprement la connexion
718
-			// avec un timeout total de 200ms pour ne pas se bloquer
719
-			while (!feof($fp) and $t < $timeout) {
720
-				@fgets($fp, 1024);
721
-				$t += spip_timer('read', true);
722
-				spip_timer('read');
723
-			}
724
-			fclose($fp);
725
-			return true;
726
-		}
727
-	}
728
-	// si fsockopen n'est pas dispo on essaye cURL :
729
-	// lancer le cron par un cURL asynchrone si cURL est present
730
-	elseif (function_exists('curl_init')) {
731
-		//setting the curl parameters.
732
-		$ch = curl_init($url_cron);
733
-		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
734
-		// cf bug : http://www.php.net/manual/en/function.curl-setopt.php#104597
735
-		curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
736
-		// valeur mini pour que la requete soit lancee
737
-		curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
738
-		// lancer
739
-		curl_exec($ch);
740
-		// fermer
741
-		curl_close($ch);
742
-		return true;
743
-	}
744
-
745
-	return false;
677
+    // methode la plus rapide :
678
+    // Si fsockopen est possible, on lance le cron via un socket en asynchrone
679
+    // si fsockopen echoue (disponibilite serveur, firewall) on essaye pas cURL
680
+    // car on a toutes les chances d'echouer pareil mais sans moyen de le savoir
681
+    // mais on renvoie false direct
682
+    if (function_exists('fsockopen')) {
683
+        $parts = parse_url($url_cron);
684
+
685
+        switch ($parts['scheme']) {
686
+            case 'https':
687
+                $scheme = 'ssl://';
688
+                $port = 443;
689
+                break;
690
+            case 'http':
691
+            default:
692
+                $scheme = '';
693
+                $port = 80;
694
+        }
695
+        $fp = @fsockopen(
696
+            $scheme . $parts['host'],
697
+            $parts['port'] ?? $port,
698
+            $errno,
699
+            $errstr,
700
+            1
701
+        );
702
+
703
+        if ($fp) {
704
+            $host_sent = $parts['host'];
705
+            if (isset($parts['port']) and $parts['port'] !== $port) {
706
+                $host_sent .= ':' . $parts['port'];
707
+            }
708
+            $timeout = 200; // ms
709
+            stream_set_timeout($fp, 0, $timeout * 1000);
710
+            $query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
711
+            $out = 'GET ' . $query . " HTTP/1.1\r\n";
712
+            $out .= 'Host: ' . $host_sent . "\r\n";
713
+            $out .= "Connection: Close\r\n\r\n";
714
+            fwrite($fp, $out);
715
+            spip_timer('read');
716
+            $t = 0;
717
+            // on lit la reponse si possible pour fermer proprement la connexion
718
+            // avec un timeout total de 200ms pour ne pas se bloquer
719
+            while (!feof($fp) and $t < $timeout) {
720
+                @fgets($fp, 1024);
721
+                $t += spip_timer('read', true);
722
+                spip_timer('read');
723
+            }
724
+            fclose($fp);
725
+            return true;
726
+        }
727
+    }
728
+    // si fsockopen n'est pas dispo on essaye cURL :
729
+    // lancer le cron par un cURL asynchrone si cURL est present
730
+    elseif (function_exists('curl_init')) {
731
+        //setting the curl parameters.
732
+        $ch = curl_init($url_cron);
733
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
734
+        // cf bug : http://www.php.net/manual/en/function.curl-setopt.php#104597
735
+        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
736
+        // valeur mini pour que la requete soit lancee
737
+        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
738
+        // lancer
739
+        curl_exec($ch);
740
+        // fermer
741
+        curl_close($ch);
742
+        return true;
743
+    }
744
+
745
+    return false;
746 746
 }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -40 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	$md5args = md5($arguments);
71 71
 
72 72
 	// si pas de date programee, des que possible
73
-	$duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
73
+	$duplicate_where = 'status='.intval(_JQ_SCHEDULED).' AND ';
74 74
 	if (!$time) {
75 75
 		$time = time();
76 76
 		$duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
@@ -96,9 +96,8 @@  discard block
 block discarded – undo
96 96
 			'id_job',
97 97
 			'spip_jobs',
98 98
 			$duplicate_where =
99
-				$duplicate_where . 'fonction=' . sql_quote($function)
100
-				. (($no_duplicate === 'function_only') ? '' :
101
-			' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
99
+				$duplicate_where.'fonction='.sql_quote($function)
100
+				. (($no_duplicate === 'function_only') ? '' : ' AND md5args='.sql_quote($md5args).' AND inclure='.sql_quote($file))
102 101
 		)
103 102
 	) {
104 103
 		return $id_job;
@@ -111,9 +110,9 @@  discard block
 block discarded – undo
111 110
 	if (
112 111
 		$no_duplicate
113 112
 		and
114
-		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
113
+		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<'.intval($id_job)." AND $duplicate_where")
115 114
 	) {
116
-		sql_delete('spip_jobs', 'id_job=' . intval($id_job));
115
+		sql_delete('spip_jobs', 'id_job='.intval($id_job));
117 116
 
118 117
 		return $id_prev;
119 118
 	}
@@ -125,9 +124,9 @@  discard block
 block discarded – undo
125 124
 	// ie cas d'un char non acceptables sur certains type de champs
126 125
 	// qui coupe la valeur
127 126
 	if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
-		$args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
127
+		$args = sql_getfetsel('args', 'spip_jobs', 'id_job='.intval($id_job));
129 128
 		if ($args !== $arguments) {
130
-			spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
129
+			spip_log('arguments job errones / longueur '.strlen($args).' vs '.strlen($arguments).' / valeur : '.var_export(
131 130
 				$arguments,
132 131
 				true
133 132
 			), 'queue');
@@ -157,7 +156,7 @@  discard block
 block discarded – undo
157 156
 function queue_purger() {
158 157
 	include_spip('base/abstract_sql');
159 158
 	sql_delete('spip_jobs');
160
-	sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
159
+	sql_delete('spip_jobs_liens', 'id_job NOT IN ('.sql_get_select('id_job', 'spip_jobs').')');
161 160
 	include_spip('inc/genie');
162 161
 	genie_queue_watch_dist();
163 162
 }
@@ -173,8 +172,8 @@  discard block
 block discarded – undo
173 172
 	include_spip('base/abstract_sql');
174 173
 
175 174
 	if (
176
-		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
-		and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
175
+		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job='.intval($id_job))
176
+		and $res = sql_delete('spip_jobs', 'id_job='.intval($id_job))
178 177
 	) {
179 178
 		queue_unlink_job($id_job);
180 179
 		// est-ce une tache cron qu'il faut relancer ?
@@ -224,7 +223,7 @@  discard block
 block discarded – undo
224 223
  *  resultat du sql_delete
225 224
  */
226 225
 function queue_unlink_job($id_job) {
227
-	return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
226
+	return sql_delete('spip_jobs_liens', 'id_job='.intval($id_job));
228 227
 }
229 228
 
230 229
 /**
@@ -240,7 +239,7 @@  discard block
 block discarded – undo
240 239
 	// deserialiser les arguments
241 240
 	$args = unserialize($row['args']);
242 241
 	if ($args === false) {
243
-		spip_log('arguments job errones ' . var_export($row, true), 'queue');
242
+		spip_log('arguments job errones '.var_export($row, true), 'queue');
244 243
 		$args = [];
245 244
 	}
246 245
 
@@ -257,15 +256,14 @@  discard block
 block discarded – undo
257 256
 	}
258 257
 
259 258
 	if (!function_exists($fonction)) {
260
-		spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
259
+		spip_log("fonction $fonction ($inclure) inexistante ".var_export($row, true), 'queue');
261 260
 
262 261
 		return false;
263 262
 	}
264 263
 
265
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
264
+	spip_log('queue ['.$row['id_job']."]: $fonction() start", 'queue');
266 265
 	switch (is_countable($args) ? count($args) : 0) {
267
-		case 0:
268
-			$res = $fonction();
266
+		case 0 : $res = $fonction();
269 267
 			break;
270 268
 		case 1:
271 269
 			$res = $fonction($args[0]);
@@ -312,7 +310,7 @@  discard block
 block discarded – undo
312 310
 			# plus lent mais completement generique
313 311
 			$res = call_user_func_array($fonction, $args);
314 312
 	}
315
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
313
+	spip_log('queue ['.$row['id_job']."]: $fonction() end", 'queue');
316 314
 
317 315
 	return $res;
318 316
 }
@@ -343,14 +341,14 @@  discard block
 block discarded – undo
343 341
 function queue_schedule($force_jobs = null) {
344 342
 	$time = time();
345 343
 	if (defined('_DEBUG_BLOCK_QUEUE')) {
346
-		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
344
+		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq'._LOG_DEBUG);
347 345
 
348 346
 		return;
349 347
 	}
350 348
 
351 349
 	// rien a faire si le prochain job est encore dans le futur
352 350
 	if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
353
-		spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
351
+		spip_log('queue_sleep_time_to_next_job', 'jq'._LOG_DEBUG);
354 352
 
355 353
 		return;
356 354
 	}
@@ -371,7 +369,7 @@  discard block
 block discarded – undo
371 369
 	}
372 370
 	$end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
373 371
 
374
-	spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
372
+	spip_log("JQ schedule $time / $end_time", 'jq'._LOG_DEBUG);
375 373
 
376 374
 	if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
377 375
 		define('_JQ_MAX_JOBS_EXECUTE', 200);
@@ -385,19 +383,19 @@  discard block
 block discarded – undo
385 383
 	// lorsqu'un job cron n'a pas fini, sa priorite est descendue
386 384
 	// pour qu'il ne bloque pas les autres jobs en attente
387 385
 	if (is_array($force_jobs) and count($force_jobs)) {
388
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
386
+		$cond = 'status='.intval(_JQ_SCHEDULED).' AND '.sql_in('id_job', $force_jobs);
389 387
 	} else {
390 388
 		$now = date('Y-m-d H:i:s', $time);
391
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
389
+		$cond = 'status='.intval(_JQ_SCHEDULED).' AND date<='.sql_quote($now);
392 390
 	}
393 391
 
394 392
 	register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
395
-	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
393
+	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,'.(_JQ_MAX_JOBS_EXECUTE + 1));
396 394
 	do {
397 395
 		if ($row = array_shift($res)) {
398 396
 			$nbj++;
399 397
 			// il faut un verrou, a base de sql_delete
400
-			if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
398
+			if (sql_delete('spip_jobs', 'id_job='.intval($row['id_job']).' AND status='.intval(_JQ_SCHEDULED))) {
401 399
 				#spip_log("JQ schedule job ".$nbj." OK",'jq');
402 400
 				// on reinsert dans la base aussitot avec un status=_JQ_PENDING
403 401
 				$row['status'] = _JQ_PENDING;
@@ -412,13 +410,13 @@  discard block
 block discarded – undo
412 410
 				queue_close_job($row, $time, $result);
413 411
 			}
414 412
 		}
415
-		spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
413
+		spip_log('JQ schedule job end time '.$time, 'jq'._LOG_DEBUG);
416 414
 	} while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
417
-	spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
415
+	spip_log('JQ schedule end time '.time(), 'jq'._LOG_DEBUG);
418 416
 
419 417
 	if ($row = array_shift($res)) {
420 418
 		queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
421
-		spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
419
+		spip_log('JQ encore !', 'jq'._LOG_DEBUG);
422 420
 	} else {
423 421
 		queue_update_next_job_time();
424 422
 	}
@@ -453,9 +451,9 @@  discard block
 block discarded – undo
453 451
 		}
454 452
 	}
455 453
 	// purger ses liens eventuels avec des objets
456
-	sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
454
+	sql_delete('spip_jobs_liens', 'id_job='.intval($row['id_job']));
457 455
 	// supprimer le job fini
458
-	sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
456
+	sql_delete('spip_jobs', 'id_job='.intval($row['id_job']));
459 457
 }
460 458
 
461 459
 /**
@@ -528,18 +526,18 @@  discard block
 block discarded – undo
528 526
 	$res = sql_allfetsel(
529 527
 		'*',
530 528
 		'spip_jobs',
531
-		'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
529
+		'status='.intval(_JQ_PENDING).' AND date<'.sql_quote(date('Y-m-d H:i:s', $time - 180))
532 530
 	);
533 531
 	if (is_array($res)) {
534 532
 		foreach ($res as $row) {
535 533
 			queue_close_job($row, $time);
536
-			spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
534
+			spip_log('queue_close_job car _JQ_PENDING depuis +180s : '.print_r($row, 1), 'job_mort'._LOG_ERREUR);
537 535
 		}
538 536
 	}
539 537
 
540 538
 	// chercher la date du prochain job si pas connu
541 539
 	if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
542
-		$date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
540
+		$date = sql_getfetsel('date', 'spip_jobs', 'status='.intval(_JQ_SCHEDULED), '', 'date', '0,1');
543 541
 		$next = strtotime($date);
544 542
 	}
545 543
 	if (!is_null($next_time)) {
@@ -552,7 +550,7 @@  discard block
 block discarded – undo
552 550
 		if (is_null($nb_jobs_scheduled)) {
553 551
 			$nb_jobs_scheduled = sql_countsel(
554 552
 				'spip_jobs',
555
-				'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
553
+				'status='.intval(_JQ_SCHEDULED).' AND date<'.sql_quote(date('Y-m-d H:i:s', $time))
556 554
 			);
557 555
 		} elseif ($next <= $time) {
558 556
 			$nb_jobs_scheduled++;
@@ -621,7 +619,7 @@  discard block
 block discarded – undo
621 619
 	}
622 620
 
623 621
 	// ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
624
-	if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
622
+	if (file_exists($lock = _DIR_TMP.'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
625 623
 		return $texte;
626 624
 	}
627 625
 
@@ -693,7 +691,7 @@  discard block
 block discarded – undo
693 691
 				$port = 80;
694 692
 		}
695 693
 		$fp = @fsockopen(
696
-			$scheme . $parts['host'],
694
+			$scheme.$parts['host'],
697 695
 			$parts['port'] ?? $port,
698 696
 			$errno,
699 697
 			$errstr,
@@ -703,13 +701,13 @@  discard block
 block discarded – undo
703 701
 		if ($fp) {
704 702
 			$host_sent = $parts['host'];
705 703
 			if (isset($parts['port']) and $parts['port'] !== $port) {
706
-				$host_sent .= ':' . $parts['port'];
704
+				$host_sent .= ':'.$parts['port'];
707 705
 			}
708 706
 			$timeout = 200; // ms
709 707
 			stream_set_timeout($fp, 0, $timeout * 1000);
710
-			$query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
711
-			$out = 'GET ' . $query . " HTTP/1.1\r\n";
712
-			$out .= 'Host: ' . $host_sent . "\r\n";
708
+			$query = $parts['path'].($parts['query'] ? '?'.$parts['query'] : '');
709
+			$out = 'GET '.$query." HTTP/1.1\r\n";
710
+			$out .= 'Host: '.$host_sent."\r\n";
713 711
 			$out .= "Connection: Close\r\n\r\n";
714 712
 			fwrite($fp, $out);
715 713
 			spip_timer('read');
Please login to merge, or discard this patch.
ecrire/inc/filtres_alertes.php 2 patches
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  **/
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
  *     Pile complétée par le code à générer
44 44
  */
45 45
 function balise_ALERTE_MESSAGE_dist($p) {
46
-	$_texte = interprete_argument_balise(1, $p);
47
-	$_titre = interprete_argument_balise(2, $p);
48
-	$_class = interprete_argument_balise(3, $p);
49
-	$_role  = interprete_argument_balise(4, $p);
50
-	$_id    = interprete_argument_balise(5, $p);
51
-	$_texte = ($_texte ?: "''");
52
-	$_titre = ($_titre ? ", $_titre" : ', null');
53
-	$_class = ($_class ? ", $_class" : ', null');
54
-	$_role  = ($_role  ? ", $_role"  : ', null');
55
-	$_id    = ($_id    ? ", $_id"    : ', null');
46
+    $_texte = interprete_argument_balise(1, $p);
47
+    $_titre = interprete_argument_balise(2, $p);
48
+    $_class = interprete_argument_balise(3, $p);
49
+    $_role  = interprete_argument_balise(4, $p);
50
+    $_id    = interprete_argument_balise(5, $p);
51
+    $_texte = ($_texte ?: "''");
52
+    $_titre = ($_titre ? ", $_titre" : ', null');
53
+    $_class = ($_class ? ", $_class" : ', null');
54
+    $_role  = ($_role  ? ", $_role"  : ', null');
55
+    $_id    = ($_id    ? ", $_id"    : ', null');
56 56
 
57
-	$f = chercher_filtre('message_alerte');
58
-	$p->code = "$f($_texte$_titre$_class$_role$_id)";
59
-	$p->interdire_scripts = false;
57
+    $f = chercher_filtre('message_alerte');
58
+    $p->code = "$f($_texte$_titre$_class$_role$_id)";
59
+    $p->interdire_scripts = false;
60 60
 
61
-	return $p;
61
+    return $p;
62 62
 }
63 63
 
64 64
 /**
@@ -86,20 +86,20 @@  discard block
 block discarded – undo
86 86
  *     Pile complétée par le code à générer
87 87
  */
88 88
 function balise_ALERTE_OUVRIR_dist($p) {
89
-	$_titre = interprete_argument_balise(1, $p);
90
-	$_class = interprete_argument_balise(2, $p);
91
-	$_role  = interprete_argument_balise(3, $p);
92
-	$_id    = interprete_argument_balise(4, $p);
93
-	$_titre = ($_titre ? "$_titre"   : 'null');
94
-	$_class = ($_class ? ", $_class" : ', null');
95
-	$_role  = ($_role  ? ", $_role"  : ', null');
96
-	$_id    = ($_id    ? ", $_id"    : ', null');
89
+    $_titre = interprete_argument_balise(1, $p);
90
+    $_class = interprete_argument_balise(2, $p);
91
+    $_role  = interprete_argument_balise(3, $p);
92
+    $_id    = interprete_argument_balise(4, $p);
93
+    $_titre = ($_titre ? "$_titre"   : 'null');
94
+    $_class = ($_class ? ", $_class" : ', null');
95
+    $_role  = ($_role  ? ", $_role"  : ', null');
96
+    $_id    = ($_id    ? ", $_id"    : ', null');
97 97
 
98
-	$f = chercher_filtre('message_alerte_ouvrir');
99
-	$p->code = "$f($_titre$_class$_role$_id)";
100
-	$p->interdire_scripts = false;
98
+    $f = chercher_filtre('message_alerte_ouvrir');
99
+    $p->code = "$f($_titre$_class$_role$_id)";
100
+    $p->interdire_scripts = false;
101 101
 
102
-	return $p;
102
+    return $p;
103 103
 }
104 104
 
105 105
 /**
@@ -121,11 +121,11 @@  discard block
 block discarded – undo
121 121
  *     Pile complétée par le code à générer
122 122
  */
123 123
 function balise_ALERTE_FERMER_dist($p) {
124
-	$f = chercher_filtre('message_alerte_fermer');
125
-	$p->code = "$f()";
126
-	$p->interdire_scripts = false;
124
+    $f = chercher_filtre('message_alerte_fermer');
125
+    $p->code = "$f()";
126
+    $p->interdire_scripts = false;
127 127
 
128
-	return $p;
128
+    return $p;
129 129
 }
130 130
 
131 131
 /**
@@ -160,14 +160,14 @@  discard block
 block discarded – undo
160 160
  */
161 161
 function message_alerte(string $texte, ?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
162 162
 
163
-	$message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
-	$message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
-	$message =
166
-		$message_alerte_ouvrir($titre, $class, $role, $id) .
167
-		$texte .
168
-		$message_alerte_fermer();
163
+    $message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
+    $message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
+    $message =
166
+        $message_alerte_ouvrir($titre, $class, $role, $id) .
167
+        $texte .
168
+        $message_alerte_fermer();
169 169
 
170
-	return $message;
170
+    return $message;
171 171
 }
172 172
 
173 173
 /**
@@ -198,55 +198,55 @@  discard block
 block discarded – undo
198 198
  */
199 199
 function message_alerte_ouvrir(?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
200 200
 
201
-	$prive = test_espace_prive();
201
+    $prive = test_espace_prive();
202 202
 
203
-	// Valeurs par défaut
204
-	$role ??= 'alert'; // fallback uniquement si null
205
-	$class ??= 'notice'; // fallback uniquement si null
203
+    // Valeurs par défaut
204
+    $role ??= 'alert'; // fallback uniquement si null
205
+    $class ??= 'notice'; // fallback uniquement si null
206 206
 
207
-	// Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
208
-	$types = [
209
-		'notice',
210
-		'error',
211
-		'success',
212
-		'info',
213
-	];
214
-	$type  = array_intersect(explode(' ', $class), $types);
215
-	$type  = reset($type);
216
-	$class = trim(str_replace($types, '', $class) . " $type");
207
+    // Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
208
+    $types = [
209
+        'notice',
210
+        'error',
211
+        'success',
212
+        'info',
213
+    ];
214
+    $type  = array_intersect(explode(' ', $class), $types);
215
+    $type  = reset($type);
216
+    $class = trim(str_replace($types, '', $class) . " $type");
217 217
 
218
-	// Classes
219
-	$class_racine = 'msg-alert';
220
-	$clearfix     = ($prive ? 'clearfix' : '');
221
-	$class_alerte = "$class_racine $class";
222
-	$class_texte  = "${class_racine}__text $clearfix";
223
-	$class_titre  = "${class_racine}__heading";
218
+    // Classes
219
+    $class_racine = 'msg-alert';
220
+    $clearfix     = ($prive ? 'clearfix' : '');
221
+    $class_alerte = "$class_racine $class";
222
+    $class_texte  = "${class_racine}__text $clearfix";
223
+    $class_titre  = "${class_racine}__heading";
224 224
 
225
-	// Titre : markup
226
-	$titre = trim($titre);
227
-	if (strlen($titre)) {
228
-		include_spip('inc/filtres');
229
-		// Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
230
-		$cherche_tag = ($prive ? '<h' : '<');
231
-		$wrap_tag    = ($prive ? '<h3>' : '<div>');
232
-		if (strpos($titre, $cherche_tag) !== 0) {
233
-			$titre = wrap($titre, $wrap_tag);
234
-		}
235
-		// puis on ajoute la classe
236
-		$titre = ajouter_class($titre, $class_titre);
237
-	}
225
+    // Titre : markup
226
+    $titre = trim($titre);
227
+    if (strlen($titre)) {
228
+        include_spip('inc/filtres');
229
+        // Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
230
+        $cherche_tag = ($prive ? '<h' : '<');
231
+        $wrap_tag    = ($prive ? '<h3>' : '<div>');
232
+        if (strpos($titre, $cherche_tag) !== 0) {
233
+            $titre = wrap($titre, $wrap_tag);
234
+        }
235
+        // puis on ajoute la classe
236
+        $titre = ajouter_class($titre, $class_titre);
237
+    }
238 238
 
239
-	// Attributs
240
-	$attr_role = ($role ? "role=\"$role\"" : '');
241
-	$attr_id   = ($id   ? "id=\"$id\"" : '');
242
-	$attr_data = ($type ? "data-alert=\"$type\"" : '');
239
+    // Attributs
240
+    $attr_role = ($role ? "role=\"$role\"" : '');
241
+    $attr_id   = ($id   ? "id=\"$id\"" : '');
242
+    $attr_data = ($type ? "data-alert=\"$type\"" : '');
243 243
 
244
-	$message =
245
-		"<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
246
-			. $titre
247
-			. "<div class=\"$class_texte\">";
244
+    $message =
245
+        "<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
246
+            . $titre
247
+            . "<div class=\"$class_texte\">";
248 248
 
249
-	return $message;
249
+    return $message;
250 250
 }
251 251
 
252 252
 /**
@@ -260,5 +260,5 @@  discard block
 block discarded – undo
260 260
  *     HTML de fin de l'alerte
261 261
  */
262 262
 function message_alerte_fermer(): string {
263
-	return '</div></div>';
263
+    return '</div></div>';
264 264
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -51,8 +51,8 @@  discard block
 block discarded – undo
51 51
 	$_texte = ($_texte ?: "''");
52 52
 	$_titre = ($_titre ? ", $_titre" : ', null');
53 53
 	$_class = ($_class ? ", $_class" : ', null');
54
-	$_role  = ($_role  ? ", $_role"  : ', null');
55
-	$_id    = ($_id    ? ", $_id"    : ', null');
54
+	$_role  = ($_role ? ", $_role" : ', null');
55
+	$_id    = ($_id ? ", $_id" : ', null');
56 56
 
57 57
 	$f = chercher_filtre('message_alerte');
58 58
 	$p->code = "$f($_texte$_titre$_class$_role$_id)";
@@ -90,10 +90,10 @@  discard block
 block discarded – undo
90 90
 	$_class = interprete_argument_balise(2, $p);
91 91
 	$_role  = interprete_argument_balise(3, $p);
92 92
 	$_id    = interprete_argument_balise(4, $p);
93
-	$_titre = ($_titre ? "$_titre"   : 'null');
93
+	$_titre = ($_titre ? "$_titre" : 'null');
94 94
 	$_class = ($_class ? ", $_class" : ', null');
95
-	$_role  = ($_role  ? ", $_role"  : ', null');
96
-	$_id    = ($_id    ? ", $_id"    : ', null');
95
+	$_role  = ($_role ? ", $_role" : ', null');
96
+	$_id    = ($_id ? ", $_id" : ', null');
97 97
 
98 98
 	$f = chercher_filtre('message_alerte_ouvrir');
99 99
 	$p->code = "$f($_titre$_class$_role$_id)";
@@ -163,8 +163,8 @@  discard block
 block discarded – undo
163 163
 	$message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164 164
 	$message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165 165
 	$message =
166
-		$message_alerte_ouvrir($titre, $class, $role, $id) .
167
-		$texte .
166
+		$message_alerte_ouvrir($titre, $class, $role, $id).
167
+		$texte.
168 168
 		$message_alerte_fermer();
169 169
 
170 170
 	return $message;
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 	];
214 214
 	$type  = array_intersect(explode(' ', $class), $types);
215 215
 	$type  = reset($type);
216
-	$class = trim(str_replace($types, '', $class) . " $type");
216
+	$class = trim(str_replace($types, '', $class)." $type");
217 217
 
218 218
 	// Classes
219 219
 	$class_racine = 'msg-alert';
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 
239 239
 	// Attributs
240 240
 	$attr_role = ($role ? "role=\"$role\"" : '');
241
-	$attr_id   = ($id   ? "id=\"$id\"" : '');
241
+	$attr_id   = ($id ? "id=\"$id\"" : '');
242 242
 	$attr_data = ($type ? "data-alert=\"$type\"" : '');
243 243
 
244 244
 	$message =
Please login to merge, or discard this patch.
ecrire/inc/cvt_configurer.php 2 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
  */
21 21
 
22 22
 if (!defined('_ECRIRE_INC_VERSION')) {
23
-	return;
23
+    return;
24 24
 }
25 25
 
26 26
 include_spip('inc/config');
@@ -32,31 +32,31 @@  discard block
 block discarded – undo
32 32
  * @return array
33 33
  */
34 34
 function cvtconf_formulaire_charger($flux) {
35
-	if (
36
-		$form = $flux['args']['form']
37
-		and strncmp($form, 'configurer_', 11) == 0 // un #FORMULAIRE_CONFIGURER_XXX
38
-	) {
39
-		// Pour tous les formulaires CONFIGURER, ayant une fonction charger ou pas, on teste si autorisé
40
-		include_spip('inc/autoriser');
41
-		if (!autoriser('configurer', '_' . substr($form, 11))) {
42
-			return false;
43
-		}
35
+    if (
36
+        $form = $flux['args']['form']
37
+        and strncmp($form, 'configurer_', 11) == 0 // un #FORMULAIRE_CONFIGURER_XXX
38
+    ) {
39
+        // Pour tous les formulaires CONFIGURER, ayant une fonction charger ou pas, on teste si autorisé
40
+        include_spip('inc/autoriser');
41
+        if (!autoriser('configurer', '_' . substr($form, 11))) {
42
+            return false;
43
+        }
44 44
 
45
-		// S'il n'y a pas de fonction charger(), on génère un contexte automatiquement
46
-		if (!charger_fonction('charger', "formulaires/$form/", true)) {
47
-			$flux['data'] = cvtconf_formulaires_configurer_recense($form);
48
-			$flux['data']['editable'] = true;
49
-			if (_request('var_mode') == 'configurer' and autoriser('webmestre')) {
50
-				if (!_AJAX) {
51
-					var_dump($flux['data']);
52
-				}
53
-				// reinjecter pour la trace au traitement
54
-				$flux['data']['_hidden'] = "<input type='hidden' name='var_mode' value='configurer' />";
55
-			}
56
-		}
57
-	}
45
+        // S'il n'y a pas de fonction charger(), on génère un contexte automatiquement
46
+        if (!charger_fonction('charger', "formulaires/$form/", true)) {
47
+            $flux['data'] = cvtconf_formulaires_configurer_recense($form);
48
+            $flux['data']['editable'] = true;
49
+            if (_request('var_mode') == 'configurer' and autoriser('webmestre')) {
50
+                if (!_AJAX) {
51
+                    var_dump($flux['data']);
52
+                }
53
+                // reinjecter pour la trace au traitement
54
+                $flux['data']['_hidden'] = "<input type='hidden' name='var_mode' value='configurer' />";
55
+            }
56
+        }
57
+    }
58 58
 
59
-	return $flux;
59
+    return $flux;
60 60
 }
61 61
 
62 62
 /**
@@ -66,16 +66,16 @@  discard block
 block discarded – undo
66 66
  * @return array
67 67
  */
68 68
 function cvtconf_formulaire_traiter($flux) {
69
-	if (
70
-		$form = $flux['args']['form']
71
-		and strncmp($form, 'configurer_', 11) == 0 // un #FORMULAIRE_CONFIGURER_XXX
72
-		and !charger_fonction('traiter', "formulaires/$form/", true) // sans fonction traiter()
73
-	) {
74
-		$trace = cvtconf_formulaires_configurer_enregistre($form, $flux['args']['args']);
75
-		$flux['data'] = ['message_ok' => _T('config_info_enregistree') . $trace, 'editable' => true];
76
-	}
69
+    if (
70
+        $form = $flux['args']['form']
71
+        and strncmp($form, 'configurer_', 11) == 0 // un #FORMULAIRE_CONFIGURER_XXX
72
+        and !charger_fonction('traiter', "formulaires/$form/", true) // sans fonction traiter()
73
+    ) {
74
+        $trace = cvtconf_formulaires_configurer_enregistre($form, $flux['args']['args']);
75
+        $flux['data'] = ['message_ok' => _T('config_info_enregistree') . $trace, 'editable' => true];
76
+    }
77 77
 
78
-	return $flux;
78
+    return $flux;
79 79
 }
80 80
 
81 81
 /**
@@ -91,32 +91,32 @@  discard block
 block discarded – undo
91 91
  * @return string
92 92
  */
93 93
 function cvtconf_formulaires_configurer_enregistre($form, $args) {
94
-	$valeurs = [];
95
-	// charger les valeurs
96
-	// ce qui permet de prendre en charge une fonction charger() existante
97
-	// qui prend alors la main sur l'auto detection
98
-	if ($charger_valeurs = charger_fonction('charger', "formulaires/$form/", true)) {
99
-		$valeurs = call_user_func_array($charger_valeurs, $args);
100
-	}
101
-	$valeurs = pipeline(
102
-		'formulaire_charger',
103
-		[
104
-			'args' => ['form' => $form, 'args' => $args, 'je_suis_poste' => false],
105
-			'data' => $valeurs
106
-		]
107
-	);
108
-	// ne pas stocker editable !
109
-	unset($valeurs['editable']);
94
+    $valeurs = [];
95
+    // charger les valeurs
96
+    // ce qui permet de prendre en charge une fonction charger() existante
97
+    // qui prend alors la main sur l'auto detection
98
+    if ($charger_valeurs = charger_fonction('charger', "formulaires/$form/", true)) {
99
+        $valeurs = call_user_func_array($charger_valeurs, $args);
100
+    }
101
+    $valeurs = pipeline(
102
+        'formulaire_charger',
103
+        [
104
+            'args' => ['form' => $form, 'args' => $args, 'je_suis_poste' => false],
105
+            'data' => $valeurs
106
+        ]
107
+    );
108
+    // ne pas stocker editable !
109
+    unset($valeurs['editable']);
110 110
 
111
-	// recuperer les valeurs postees
112
-	$store = [];
113
-	foreach ($valeurs as $k => $v) {
114
-		if (substr($k, 0, 1) !== '_') {
115
-			$store[$k] = _request($k);
116
-		}
117
-	}
111
+    // recuperer les valeurs postees
112
+    $store = [];
113
+    foreach ($valeurs as $k => $v) {
114
+        if (substr($k, 0, 1) !== '_') {
115
+            $store[$k] = _request($k);
116
+        }
117
+    }
118 118
 
119
-	return cvtconf_configurer_stocker($form, $valeurs, $store);
119
+    return cvtconf_configurer_stocker($form, $valeurs, $store);
120 120
 }
121 121
 
122 122
 /**
@@ -132,31 +132,31 @@  discard block
 block discarded – undo
132 132
  * @return array
133 133
  */
134 134
 function cvtconf_definir_configurer_conteneur($form, $valeurs) {
135
-	// stocker en base
136
-	// par defaut, dans un casier serialize dans spip_meta (idem CFG)
137
-	$casier = substr($form, 11);
138
-	$table = 'meta';
139
-	$prefixe = '';
140
-	$stockage = '';
135
+    // stocker en base
136
+    // par defaut, dans un casier serialize dans spip_meta (idem CFG)
137
+    $casier = substr($form, 11);
138
+    $table = 'meta';
139
+    $prefixe = '';
140
+    $stockage = '';
141 141
 
142
-	if (isset($valeurs['_meta_casier'])) {
143
-		$casier = $valeurs['_meta_casier'];
144
-	}
145
-	if (isset($valeurs['_meta_prefixe'])) {
146
-		$prefixe = $valeurs['_meta_prefixe'];
147
-	}
148
-	if (isset($valeurs['_meta_stockage'])) {
149
-		$stockage = $valeurs['_meta_stockage'] . '::';
150
-	}
142
+    if (isset($valeurs['_meta_casier'])) {
143
+        $casier = $valeurs['_meta_casier'];
144
+    }
145
+    if (isset($valeurs['_meta_prefixe'])) {
146
+        $prefixe = $valeurs['_meta_prefixe'];
147
+    }
148
+    if (isset($valeurs['_meta_stockage'])) {
149
+        $stockage = $valeurs['_meta_stockage'] . '::';
150
+    }
151 151
 
152
-	// si on indique juste une table, il faut vider les autres proprietes
153
-	// car par defaut on utilise ni casier ni prefixe dans ce cas
154
-	if (isset($valeurs['_meta_table'])) {
155
-		$table = $valeurs['_meta_table'];
156
-		$casier = ($valeurs['_meta_casier'] ?? '');
157
-	}
152
+    // si on indique juste une table, il faut vider les autres proprietes
153
+    // car par defaut on utilise ni casier ni prefixe dans ce cas
154
+    if (isset($valeurs['_meta_table'])) {
155
+        $table = $valeurs['_meta_table'];
156
+        $casier = ($valeurs['_meta_casier'] ?? '');
157
+    }
158 158
 
159
-	return [$table, $casier, $prefixe, $stockage];
159
+    return [$table, $casier, $prefixe, $stockage];
160 160
 }
161 161
 
162 162
 /**
@@ -167,48 +167,48 @@  discard block
 block discarded – undo
167 167
  * @return array
168 168
  */
169 169
 function cvtconf_formulaires_configurer_recense($form) {
170
-	$valeurs = ['editable' => ' '];
170
+    $valeurs = ['editable' => ' '];
171 171
 
172
-	// sinon cas analyse du squelette
173
-	if (
174
-		$f = find_in_path($form . '.' . _EXTENSION_SQUELETTES, 'formulaires/')
175
-		and lire_fichier($f, $contenu)
176
-	) {
177
-		for ($i = 0; $i < 2; $i++) {
178
-			// a la seconde iteration, evaluer le fond avec les valeurs deja trouvees
179
-			// permet de trouver aussi les name="#GET{truc}"
180
-			if ($i == 1) {
181
-				$contenu = recuperer_fond("formulaires/$form", $valeurs);
182
-			}
172
+    // sinon cas analyse du squelette
173
+    if (
174
+        $f = find_in_path($form . '.' . _EXTENSION_SQUELETTES, 'formulaires/')
175
+        and lire_fichier($f, $contenu)
176
+    ) {
177
+        for ($i = 0; $i < 2; $i++) {
178
+            // a la seconde iteration, evaluer le fond avec les valeurs deja trouvees
179
+            // permet de trouver aussi les name="#GET{truc}"
180
+            if ($i == 1) {
181
+                $contenu = recuperer_fond("formulaires/$form", $valeurs);
182
+            }
183 183
 
184
-			$balises = array_merge(
185
-				extraire_balises($contenu, 'input'),
186
-				extraire_balises($contenu, 'textarea'),
187
-				extraire_balises($contenu, 'select')
188
-			);
184
+            $balises = array_merge(
185
+                extraire_balises($contenu, 'input'),
186
+                extraire_balises($contenu, 'textarea'),
187
+                extraire_balises($contenu, 'select')
188
+            );
189 189
 
190
-			foreach ($balises as $b) {
191
-				if (
192
-					$n = extraire_attribut($b, 'name')
193
-					and preg_match(',^([\w\-]+)(\[\w*\])?$,', $n, $r)
194
-					and !in_array($n, ['formulaire_action', 'formulaire_action_args', 'formulaire_action_sign'])
195
-					and extraire_attribut($b, 'type') !== 'submit'
196
-				) {
197
-					$valeurs[$r[1]] = '';
198
-					// recuperer les valeurs _meta_xx qui peuvent etre fournies
199
-					// en input hidden dans le squelette
200
-					if (strncmp($r[1], '_meta_', 6) == 0) {
201
-						$valeurs[$r[1]] = extraire_attribut($b, 'value');
202
-					}
203
-				}
204
-			}
205
-		}
206
-	}
190
+            foreach ($balises as $b) {
191
+                if (
192
+                    $n = extraire_attribut($b, 'name')
193
+                    and preg_match(',^([\w\-]+)(\[\w*\])?$,', $n, $r)
194
+                    and !in_array($n, ['formulaire_action', 'formulaire_action_args', 'formulaire_action_sign'])
195
+                    and extraire_attribut($b, 'type') !== 'submit'
196
+                ) {
197
+                    $valeurs[$r[1]] = '';
198
+                    // recuperer les valeurs _meta_xx qui peuvent etre fournies
199
+                    // en input hidden dans le squelette
200
+                    if (strncmp($r[1], '_meta_', 6) == 0) {
201
+                        $valeurs[$r[1]] = extraire_attribut($b, 'value');
202
+                    }
203
+                }
204
+            }
205
+        }
206
+    }
207 207
 
208 208
 
209
-	cvtconf_configurer_lire_meta($form, $valeurs);
209
+    cvtconf_configurer_lire_meta($form, $valeurs);
210 210
 
211
-	return $valeurs;
211
+    return $valeurs;
212 212
 }
213 213
 
214 214
 /**
@@ -220,26 +220,26 @@  discard block
 block discarded – undo
220 220
  * @return string
221 221
  */
222 222
 function cvtconf_configurer_stocker($form, $valeurs, $store) {
223
-	$trace = '';
224
-	[$table, $casier, $prefixe, $stockage] = cvtconf_definir_configurer_conteneur($form, $valeurs);
225
-	// stocker en base
226
-	// par defaut, dans un casier serialize dans spip_meta (idem CFG)
227
-	if (!isset($GLOBALS[$table])) {
228
-		lire_metas($table);
229
-	}
223
+    $trace = '';
224
+    [$table, $casier, $prefixe, $stockage] = cvtconf_definir_configurer_conteneur($form, $valeurs);
225
+    // stocker en base
226
+    // par defaut, dans un casier serialize dans spip_meta (idem CFG)
227
+    if (!isset($GLOBALS[$table])) {
228
+        lire_metas($table);
229
+    }
230 230
 
231
-	$prefixe = ($prefixe ? $prefixe . '_' : '');
232
-	$table = ($table) ? "/$table/" : '';
233
-	$casier = ($casier) ? rtrim($casier, '/') . '/' : ''; // slash final, sinon rien
231
+    $prefixe = ($prefixe ? $prefixe . '_' : '');
232
+    $table = ($table) ? "/$table/" : '';
233
+    $casier = ($casier) ? rtrim($casier, '/') . '/' : ''; // slash final, sinon rien
234 234
 
235
-	foreach ($store as $k => $v) {
236
-		ecrire_config("$stockage$table$prefixe$casier$k", $v);
237
-		if (_request('var_mode') == 'configurer' and autoriser('webmestre')) {
238
-			$trace .= "<br />table $table : " . $prefixe . $k . " = $v;";
239
-		}
240
-	}
235
+    foreach ($store as $k => $v) {
236
+        ecrire_config("$stockage$table$prefixe$casier$k", $v);
237
+        if (_request('var_mode') == 'configurer' and autoriser('webmestre')) {
238
+            $trace .= "<br />table $table : " . $prefixe . $k . " = $v;";
239
+        }
240
+    }
241 241
 
242
-	return $trace;
242
+    return $trace;
243 243
 }
244 244
 
245 245
 /**
@@ -249,21 +249,21 @@  discard block
 block discarded – undo
249 249
  * @param array $valeurs
250 250
  */
251 251
 function cvtconf_configurer_lire_meta($form, &$valeurs) {
252
-	[$table, $casier, $prefixe, $stockage] = cvtconf_definir_configurer_conteneur($form, $valeurs);
252
+    [$table, $casier, $prefixe, $stockage] = cvtconf_definir_configurer_conteneur($form, $valeurs);
253 253
 
254
-	$table = ($table) ? "/$table/" : '';
255
-	$prefixe = ($prefixe ? $prefixe . '_' : '');
256
-	if ($casier) {
257
-		$meta = lire_config("$stockage$table$prefixe$casier");
258
-		$prefixe = '';
259
-	} else {
260
-		$table = rtrim($table, '/');
261
-		$meta = lire_config("$stockage$table");
262
-	}
254
+    $table = ($table) ? "/$table/" : '';
255
+    $prefixe = ($prefixe ? $prefixe . '_' : '');
256
+    if ($casier) {
257
+        $meta = lire_config("$stockage$table$prefixe$casier");
258
+        $prefixe = '';
259
+    } else {
260
+        $table = rtrim($table, '/');
261
+        $meta = lire_config("$stockage$table");
262
+    }
263 263
 
264
-	foreach ($valeurs as $k => $v) {
265
-		if (substr($k, 0, 1) !== '_') {
266
-			$valeurs[$k] = ($meta[$prefixe . $k] ?? null);
267
-		}
268
-	}
264
+    foreach ($valeurs as $k => $v) {
265
+        if (substr($k, 0, 1) !== '_') {
266
+            $valeurs[$k] = ($meta[$prefixe . $k] ?? null);
267
+        }
268
+    }
269 269
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	) {
39 39
 		// Pour tous les formulaires CONFIGURER, ayant une fonction charger ou pas, on teste si autorisé
40 40
 		include_spip('inc/autoriser');
41
-		if (!autoriser('configurer', '_' . substr($form, 11))) {
41
+		if (!autoriser('configurer', '_'.substr($form, 11))) {
42 42
 			return false;
43 43
 		}
44 44
 
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 		and !charger_fonction('traiter', "formulaires/$form/", true) // sans fonction traiter()
73 73
 	) {
74 74
 		$trace = cvtconf_formulaires_configurer_enregistre($form, $flux['args']['args']);
75
-		$flux['data'] = ['message_ok' => _T('config_info_enregistree') . $trace, 'editable' => true];
75
+		$flux['data'] = ['message_ok' => _T('config_info_enregistree').$trace, 'editable' => true];
76 76
 	}
77 77
 
78 78
 	return $flux;
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 		$prefixe = $valeurs['_meta_prefixe'];
147 147
 	}
148 148
 	if (isset($valeurs['_meta_stockage'])) {
149
-		$stockage = $valeurs['_meta_stockage'] . '::';
149
+		$stockage = $valeurs['_meta_stockage'].'::';
150 150
 	}
151 151
 
152 152
 	// si on indique juste une table, il faut vider les autres proprietes
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 
172 172
 	// sinon cas analyse du squelette
173 173
 	if (
174
-		$f = find_in_path($form . '.' . _EXTENSION_SQUELETTES, 'formulaires/')
174
+		$f = find_in_path($form.'.'._EXTENSION_SQUELETTES, 'formulaires/')
175 175
 		and lire_fichier($f, $contenu)
176 176
 	) {
177 177
 		for ($i = 0; $i < 2; $i++) {
@@ -228,14 +228,14 @@  discard block
 block discarded – undo
228 228
 		lire_metas($table);
229 229
 	}
230 230
 
231
-	$prefixe = ($prefixe ? $prefixe . '_' : '');
231
+	$prefixe = ($prefixe ? $prefixe.'_' : '');
232 232
 	$table = ($table) ? "/$table/" : '';
233
-	$casier = ($casier) ? rtrim($casier, '/') . '/' : ''; // slash final, sinon rien
233
+	$casier = ($casier) ? rtrim($casier, '/').'/' : ''; // slash final, sinon rien
234 234
 
235 235
 	foreach ($store as $k => $v) {
236 236
 		ecrire_config("$stockage$table$prefixe$casier$k", $v);
237 237
 		if (_request('var_mode') == 'configurer' and autoriser('webmestre')) {
238
-			$trace .= "<br />table $table : " . $prefixe . $k . " = $v;";
238
+			$trace .= "<br />table $table : ".$prefixe.$k." = $v;";
239 239
 		}
240 240
 	}
241 241
 
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	[$table, $casier, $prefixe, $stockage] = cvtconf_definir_configurer_conteneur($form, $valeurs);
253 253
 
254 254
 	$table = ($table) ? "/$table/" : '';
255
-	$prefixe = ($prefixe ? $prefixe . '_' : '');
255
+	$prefixe = ($prefixe ? $prefixe.'_' : '');
256 256
 	if ($casier) {
257 257
 		$meta = lire_config("$stockage$table$prefixe$casier");
258 258
 		$prefixe = '';
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 
264 264
 	foreach ($valeurs as $k => $v) {
265 265
 		if (substr($k, 0, 1) !== '_') {
266
-			$valeurs[$k] = ($meta[$prefixe . $k] ?? null);
266
+			$valeurs[$k] = ($meta[$prefixe.$k] ?? null);
267 267
 		}
268 268
 	}
269 269
 }
Please login to merge, or discard this patch.
ecrire/inc/idna_convert.class.php 1 patch
Spacing   +43 added lines, -46 removed lines patch added patch discarded remove patch
@@ -73,16 +73,16 @@  discard block
 block discarded – undo
73 73
     protected $_lcount = 19;
74 74
     protected $_vcount = 21;
75 75
     protected $_tcount = 28;
76
-    protected $_ncount = 588;   // _vcount * _tcount
76
+    protected $_ncount = 588; // _vcount * _tcount
77 77
     protected $_scount = 11172; // _lcount * _tcount * _vcount
78 78
     protected $_error = false;
79 79
     protected static $_mb_string_overload = null;
80 80
     // See {@link set_paramter()} for details of how to change the following
81 81
     // settings from within your script / application
82
-    protected $_api_encoding = 'utf8';   // Default input charset is UTF-8
83
-    protected $_allow_overlong = false;  // Overlong UTF-8 encodings are forbidden
84
-    protected $_strict_mode = false;     // Behave strict or not
85
-    protected $_idn_version = 2003;      // Can be either 2003 (old, default) or 2008
82
+    protected $_api_encoding = 'utf8'; // Default input charset is UTF-8
83
+    protected $_allow_overlong = false; // Overlong UTF-8 encodings are forbidden
84
+    protected $_strict_mode = false; // Behave strict or not
85
+    protected $_idn_version = 2003; // Can be either 2003 (old, default) or 2008
86 86
 
87 87
     /**
88 88
      * the constructor
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
                             $this->_api_encoding = $v;
141 141
                             break;
142 142
                         default:
143
-                            $this->_error('Set Parameter: Unknown parameter ' . $v . ' for option ' . $k);
143
+                            $this->_error('Set Parameter: Unknown parameter '.$v.' for option '.$k);
144 144
                             return false;
145 145
                     }
146 146
                     break;
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
                     if (in_array($v, array('2003', '2008'))) {
155 155
                         $this->_idn_version = $v;
156 156
                     } else {
157
-                        $this->_error('Set Parameter: Unknown parameter ' . $v . ' for option ' . $k);
157
+                        $this->_error('Set Parameter: Unknown parameter '.$v.' for option '.$k);
158 158
                     }
159 159
                     break;
160 160
                 case 'encode_german_sz': // Deprecated
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
                     }
166 166
                     break;
167 167
                 default:
168
-                    $this->_error('Set Parameter: Unknown option ' . $k);
168
+                    $this->_error('Set Parameter: Unknown option '.$k);
169 169
                     return false;
170 170
             }
171 171
         }
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
                 case 'ucs4_array':
189 189
                     break;
190 190
                 default:
191
-                    $this->_error('Unknown encoding ' . $one_time_encoding);
191
+                    $this->_error('Unknown encoding '.$one_time_encoding);
192 192
                     return false;
193 193
             }
194 194
         }
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
             [$email_pref, $input] = explode('@', $input, 2);
207 207
             $arr = explode('.', $input);
208 208
             foreach ($arr as $k => $v) {
209
-                if (preg_match('!^' . preg_quote($this->_punycode_prefix, '!') . '!', $v)) {
209
+                if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
210 210
                     $conv = $this->_decode($v);
211 211
                     if ($conv) {
212 212
                         $arr[$k] = $conv;
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
             $input = join('.', $arr);
217 217
             $arr = explode('.', $email_pref);
218 218
             foreach ($arr as $k => $v) {
219
-                if (preg_match('!^' . preg_quote($this->_punycode_prefix, '!') . '!', $v)) {
219
+                if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
220 220
                     $conv = $this->_decode($v);
221 221
                     if ($conv) {
222 222
                         $arr[$k] = $conv;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
                 }
225 225
             }
226 226
             $email_pref = join('.', $arr);
227
-            $return = $email_pref . '@' . $input;
227
+            $return = $email_pref.'@'.$input;
228 228
         } elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters)
229 229
             // No no in strict mode
230 230
             if ($this->_strict_mode) {
@@ -241,13 +241,13 @@  discard block
 block discarded – undo
241 241
                     }
242 242
                 }
243 243
                 $parsed['host'] = join('.', $arr);
244
-                $return = (empty($parsed['scheme']) ? '' : $parsed['scheme'] . (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://')).
245
-                        (empty($parsed['user']) ? '' : $parsed['user'] . (empty($parsed['pass']) ? '' : ':' . $parsed['pass']) . '@').
244
+                $return = (empty($parsed['scheme']) ? '' : $parsed['scheme'].(strtolower($parsed['scheme']) == 'mailto' ? ':' : '://')).
245
+                        (empty($parsed['user']) ? '' : $parsed['user'].(empty($parsed['pass']) ? '' : ':'.$parsed['pass']).'@').
246 246
                         $parsed['host'].
247
-                        (empty($parsed['port']) ? '' : ':' . $parsed['port']).
247
+                        (empty($parsed['port']) ? '' : ':'.$parsed['port']).
248 248
                         (empty($parsed['path']) ? '' : $parsed['path']).
249
-                        (empty($parsed['query']) ? '' : '?' . $parsed['query']).
250
-                        (empty($parsed['fragment']) ? '' : '#' . $parsed['fragment']);
249
+                        (empty($parsed['query']) ? '' : '?'.$parsed['query']).
250
+                        (empty($parsed['fragment']) ? '' : '#'.$parsed['fragment']);
251 251
             } else { // parse_url seems to have failed, try without it
252 252
                 $arr = explode('.', $input);
253 253
                 foreach ($arr as $k => $v) {
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
         // The output is UTF-8 by default, other output formats need conversion here
266 266
         // If one time encoding is given, use this, else the objects property
267 267
         switch ($one_time_encoding ?: $this->_api_encoding) {
268
-            case 'utf8':        return $return; // break;
269
-            case 'ucs4_string': return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return));  // break;
268
+            case 'utf8' : return $return; // break;
269
+            case 'ucs4_string': return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return)); // break;
270 270
             case 'ucs4_array':  return $this->_utf8_to_ucs4($return); // break;
271 271
             default:            $this->_error('Unsupported output format'); return false;
272 272
         }
@@ -283,15 +283,14 @@  discard block
 block discarded – undo
283 283
         // Forcing conversion of input to UCS4 array
284 284
         // If one time encoding is given, use this, else the objects property
285 285
         switch ($one_time_encoding ?: $this->_api_encoding) {
286
-            case 'utf8':
287
-                $decoded = $this->_utf8_to_ucs4($decoded);
286
+            case 'utf8' : $decoded = $this->_utf8_to_ucs4($decoded);
288 287
                 break;
289 288
             case 'ucs4_string':
290 289
                 $decoded = $this->_ucs4_string_to_ucs4($decoded);
291 290
             case 'ucs4_array':
292 291
                 break;
293 292
             default:
294
-                $this->_error('Unsupported input format: ' . ($one_time_encoding ?: $this->_api_encoding));
293
+                $this->_error('Unsupported input format: '.($one_time_encoding ?: $this->_api_encoding));
295 294
                 return false;
296 295
         }
297 296
 
@@ -380,13 +379,13 @@  discard block
 block discarded – undo
380 379
             }
381 380
         }
382 381
         $parsed['host'] = join('.', $arr);
383
-        $return = (empty($parsed['scheme']) ? '' : $parsed['scheme'] . (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://')).
384
-                (empty($parsed['user']) ? '' : $parsed['user'] . (empty($parsed['pass']) ? '' : ':' . $parsed['pass']) . '@').
382
+        $return = (empty($parsed['scheme']) ? '' : $parsed['scheme'].(strtolower($parsed['scheme']) == 'mailto' ? ':' : '://')).
383
+                (empty($parsed['user']) ? '' : $parsed['user'].(empty($parsed['pass']) ? '' : ':'.$parsed['pass']).'@').
385 384
                 $parsed['host'].
386
-                (empty($parsed['port']) ? '' : ':' . $parsed['port']).
385
+                (empty($parsed['port']) ? '' : ':'.$parsed['port']).
387 386
                 (empty($parsed['path']) ? '' : $parsed['path']).
388
-                (empty($parsed['query']) ? '' : '?' . $parsed['query']).
389
-                (empty($parsed['fragment']) ? '' : '#' . $parsed['fragment']);
387
+                (empty($parsed['query']) ? '' : '?'.$parsed['query']).
388
+                (empty($parsed['fragment']) ? '' : '#'.$parsed['fragment']);
390 389
         return $return;
391 390
     }
392 391
 
@@ -409,11 +408,11 @@  discard block
 block discarded – undo
409 408
     {
410 409
         $decoded = array();
411 410
         // find the Punycode prefix
412
-        if (!preg_match('!^' . preg_quote($this->_punycode_prefix, '!') . '!', $encoded)) {
411
+        if (!preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $encoded)) {
413 412
             $this->_error('This is not a punycode string');
414 413
             return false;
415 414
         }
416
-        $encode_test = preg_replace('!^' . preg_quote($this->_punycode_prefix, '!') . '!', '', $encoded);
415
+        $encode_test = preg_replace('!^'.preg_quote($this->_punycode_prefix, '!').'!', '', $encoded);
417 416
         // If nothing left after removing the prefix, it is hopeless
418 417
         if (!$encode_test) {
419 418
             $this->_error('The given encoded string was empty');
@@ -439,8 +438,7 @@  discard block
 block discarded – undo
439 438
             for ($old_idx = $idx, $w = 1, $k = $this->_base; 1; $k += $this->_base) {
440 439
                 $digit = $this->_decode_digit($encoded[$enco_idx++]);
441 440
                 $idx += $digit * $w;
442
-                $t = ($k <= $bias) ? $this->_tmin :
443
-                        (($k >= $bias + $this->_tmax) ? $this->_tmax : ($k - $bias));
441
+                $t = ($k <= $bias) ? $this->_tmin : (($k >= $bias + $this->_tmax) ? $this->_tmax : ($k - $bias));
444 442
                 if ($digit < $t) {
445 443
                     break;
446 444
                 }
@@ -513,7 +511,7 @@  discard block
 block discarded – undo
513 511
             return $encoded; // All codepoints were basic ones
514 512
         }
515 513
         // Start with the prefix; copy it to output
516
-        $encoded = $this->_punycode_prefix . $encoded;
514
+        $encoded = $this->_punycode_prefix.$encoded;
517 515
         // If we have basic code points in output, add an hyphen to the end
518 516
         if ($codecount) {
519 517
             $encoded .= '-';
@@ -540,8 +538,7 @@  discard block
 block discarded – undo
540 538
                     $delta++;
541 539
                 } elseif ($decoded[$i] == $cur_code) {
542 540
                     for ($q = $delta, $k = $this->_base; 1; $k += $this->_base) {
543
-                        $t = ($k <= $bias) ? $this->_tmin :
544
-                                (($k >= $bias + $this->_tmax) ? $this->_tmax : $k - $bias);
541
+                        $t = ($k <= $bias) ? $this->_tmin : (($k >= $bias + $this->_tmax) ? $this->_tmax : $k - $bias);
545 542
                         if ($q < $t) {
546 543
                             break;
547 544
                         }
@@ -628,12 +625,12 @@  discard block
 block discarded – undo
628 625
             }
629 626
             // Try to find prohibited input
630 627
             if (in_array($v, self::$NP['prohibit']) || in_array($v, self::$NP['general_prohibited'])) {
631
-                $this->_error('NAMEPREP: Prohibited input U+' . sprintf('%08X', $v));
628
+                $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
632 629
                 return false;
633 630
             }
634 631
             foreach (self::$NP['prohibit_ranges'] as $range) {
635 632
                 if ($range[0] <= $v && $v <= $range[1]) {
636
-                    $this->_error('NAMEPREP: Prohibited input U+' . sprintf('%08X', $v));
633
+                    $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
637 634
                     return false;
638 635
                 }
639 636
             }
@@ -871,7 +868,7 @@  discard block
 block discarded – undo
871 868
                 $output[$out_len] = $v;
872 869
                 ++$out_len;
873 870
                 if ('add' == $mode) {
874
-                    $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte ' . $k);
871
+                    $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k);
875 872
                     return false;
876 873
                 }
877 874
                 continue;
@@ -896,7 +893,7 @@  discard block
 block discarded – undo
896 893
                     $next_byte = 4;
897 894
                     $v = ($v - 252) << 30;
898 895
                 } else {
899
-                    $this->_error('This might be UTF-8, but I don\'t understand it at byte ' . $k);
896
+                    $this->_error('This might be UTF-8, but I don\'t understand it at byte '.$k);
900 897
                     return false;
901 898
                 }
902 899
                 if ('add' == $mode) {
@@ -909,7 +906,7 @@  discard block
 block discarded – undo
909 906
                 if (!$this->_allow_overlong && $test == 'range') {
910 907
                     $test = 'none';
911 908
                     if (($v < 0xA0 && $start_byte == 0xE0) || ($v < 0x90 && $start_byte == 0xF0) || ($v > 0x8F && $start_byte == 0xF4)) {
912
-                        $this->_error('Bogus UTF-8 character detected (out of legal range) at byte ' . $k);
909
+                        $this->_error('Bogus UTF-8 character detected (out of legal range) at byte '.$k);
913 910
                         return false;
914 911
                     }
915 912
                 }
@@ -918,7 +915,7 @@  discard block
 block discarded – undo
918 915
                     $output[($out_len - 1)] += $v;
919 916
                     --$next_byte;
920 917
                 } else {
921
-                    $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte ' . $k);
918
+                    $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k);
922 919
                     return false;
923 920
                 }
924 921
                 if ($next_byte < 0) {
@@ -942,13 +939,13 @@  discard block
 block discarded – undo
942 939
             if ($v < 128) { // 7bit are transferred literally
943 940
                 $output .= chr($v);
944 941
             } elseif ($v < (1 << 11)) { // 2 bytes
945
-                $output .= chr(192 + ($v >> 6)) . chr(128 + ($v & 63));
942
+                $output .= chr(192 + ($v >> 6)).chr(128 + ($v & 63));
946 943
             } elseif ($v < (1 << 16)) { // 3 bytes
947
-                $output .= chr(224 + ($v >> 12)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
944
+                $output .= chr(224 + ($v >> 12)).chr(128 + (($v >> 6) & 63)).chr(128 + ($v & 63));
948 945
             } elseif ($v < (1 << 21)) { // 4 bytes
949
-                $output .= chr(240 + ($v >> 18)) . chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
946
+                $output .= chr(240 + ($v >> 18)).chr(128 + (($v >> 12) & 63)).chr(128 + (($v >> 6) & 63)).chr(128 + ($v & 63));
950 947
             } else {
951
-                $this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte ' . $k);
948
+                $this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte '.$k);
952 949
                 return false;
953 950
             }
954 951
         }
@@ -967,7 +964,7 @@  discard block
 block discarded – undo
967 964
         // Take array values and split output to 4 bytes per value
968 965
         // The bit mask is 255, which reads &11111111
969 966
         foreach ($input as $v) {
970
-            $output .= chr(($v >> 24) & 255) . chr(($v >> 16) & 255) . chr(($v >> 8) & 255) . chr($v & 255);
967
+            $output .= chr(($v >> 24) & 255).chr(($v >> 16) & 255).chr(($v >> 8) & 255).chr($v & 255);
971 968
         }
972 969
         return $output;
973 970
     }
@@ -997,7 +994,7 @@  discard block
 block discarded – undo
997 994
                 $out_len++;
998 995
                 $output[$out_len] = 0;
999 996
             }
1000
-            $output[$out_len] += ord($input[$i]) << (8 * (3 - ($i % 4) ) );
997
+            $output[$out_len] += ord($input[$i]) << (8 * (3 - ($i % 4)));
1001 998
         }
1002 999
         return $output;
1003 1000
     }
Please login to merge, or discard this patch.