Completed
Push — master ( 72d0e2...cf43de )
by cam
01:25
created
ecrire/public/evaluer_page.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 /**
@@ -29,50 +29,50 @@  discard block
 block discarded – undo
29 29
  * @return void
30 30
  */
31 31
 
32
- /** @var bool Évaluation réussie ? */
32
+    /** @var bool Évaluation réussie ? */
33 33
 $res = true;
34 34
 
35 35
 // Cas d'une page contenant du PHP :
36 36
 if (empty($page['process_ins']) or $page['process_ins'] != 'html') {
37
-	include_spip('inc/lang');
37
+    include_spip('inc/lang');
38 38
 
39
-	// restaurer l'etat des notes avant calcul
40
-	if (
41
-		isset($page['notes'])
42
-		and $page['notes']
43
-		and $notes = charger_fonction('notes', 'inc', true)
44
-	) {
45
-		$notes($page['notes'], 'restaurer_etat');
46
-	}
47
-	ob_start();
48
-	if (strpos($page['texte'], '?xml') !== false) {
49
-		$page['texte'] = str_replace('<' . '?xml', "<\1?xml", $page['texte']);
50
-	}
39
+    // restaurer l'etat des notes avant calcul
40
+    if (
41
+        isset($page['notes'])
42
+        and $page['notes']
43
+        and $notes = charger_fonction('notes', 'inc', true)
44
+    ) {
45
+        $notes($page['notes'], 'restaurer_etat');
46
+    }
47
+    ob_start();
48
+    if (strpos($page['texte'], '?xml') !== false) {
49
+        $page['texte'] = str_replace('<' . '?xml', "<\1?xml", $page['texte']);
50
+    }
51 51
 
52
-	try {
53
-		$res = eval('?' . '>' . $page['texte']);
54
-		$page['texte'] = ob_get_contents();
55
-	} catch (\Throwable $e) {
56
-		$code = $page['texte'];
57
-		$GLOBALS['numero_ligne_php'] = 1;
58
-		if (!function_exists('numerote_ligne_php')) {
59
-			function numerote_ligne_php($match) {
60
-				$GLOBALS['numero_ligne_php']++;
61
-				return "\n/*" . str_pad($GLOBALS['numero_ligne_php'], 3, '0', STR_PAD_LEFT) . '*/';
62
-			}
63
-		}
64
-		$code = '/*001*/' . preg_replace_callback(",\n,", 'numerote_ligne_php', $code);
65
-		$code = trim(highlight_string($code, true));
66
-		erreur_squelette('L' . $e->getLine() . ': ' . $e->getMessage() . '<br />' . $code, [$page['source'],'',$e->getFile(),'',$GLOBALS['spip_lang']]);
67
-		$page['texte'] = '<!-- Erreur -->';
68
-	}
69
-	ob_end_clean();
52
+    try {
53
+        $res = eval('?' . '>' . $page['texte']);
54
+        $page['texte'] = ob_get_contents();
55
+    } catch (\Throwable $e) {
56
+        $code = $page['texte'];
57
+        $GLOBALS['numero_ligne_php'] = 1;
58
+        if (!function_exists('numerote_ligne_php')) {
59
+            function numerote_ligne_php($match) {
60
+                $GLOBALS['numero_ligne_php']++;
61
+                return "\n/*" . str_pad($GLOBALS['numero_ligne_php'], 3, '0', STR_PAD_LEFT) . '*/';
62
+            }
63
+        }
64
+        $code = '/*001*/' . preg_replace_callback(",\n,", 'numerote_ligne_php', $code);
65
+        $code = trim(highlight_string($code, true));
66
+        erreur_squelette('L' . $e->getLine() . ': ' . $e->getMessage() . '<br />' . $code, [$page['source'],'',$e->getFile(),'',$GLOBALS['spip_lang']]);
67
+        $page['texte'] = '<!-- Erreur -->';
68
+    }
69
+    ob_end_clean();
70 70
 
71
-	$page['process_ins'] = 'html';
71
+    $page['process_ins'] = 'html';
72 72
 
73
-	if (strpos($page['texte'], '?xml') !== false) {
74
-		$page['texte'] = str_replace("<\1?xml", '<' . '?xml', $page['texte']);
75
-	}
73
+    if (strpos($page['texte'], '?xml') !== false) {
74
+        $page['texte'] = str_replace("<\1?xml", '<' . '?xml', $page['texte']);
75
+    }
76 76
 }
77 77
 
78 78
 // le résultat de calcul d'un squelette est toujours de type string
Please login to merge, or discard this patch.
ecrire/inc/urls.php 1 patch
Indentation   +205 added lines, -205 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
 include_spip('base/objets');
23 23
 
@@ -57,106 +57,106 @@  discard block
 block discarded – undo
57 57
  *
58 58
  */
59 59
 function urls_decoder_url($url, $fond = '', $contexte = [], $assembler = false) {
60
-	static $current_base = null;
60
+    static $current_base = null;
61 61
 
62
-	// les anciennes fonctions modifient directement les globales
63
-	// on les sauve avant l'appel, et on les retablit apres !
64
-	$save = [
65
-		$GLOBALS['fond'] ?? null,
66
-		$GLOBALS['contexte'] ?? null,
67
-		$_SERVER['REDIRECT_url_propre'] ?? null,
68
-		$_ENV['url_propre'] ?? null,
69
-		$GLOBALS['profondeur_url']
70
-	];
62
+    // les anciennes fonctions modifient directement les globales
63
+    // on les sauve avant l'appel, et on les retablit apres !
64
+    $save = [
65
+        $GLOBALS['fond'] ?? null,
66
+        $GLOBALS['contexte'] ?? null,
67
+        $_SERVER['REDIRECT_url_propre'] ?? null,
68
+        $_ENV['url_propre'] ?? null,
69
+        $GLOBALS['profondeur_url']
70
+    ];
71 71
 
72
-	if (is_null($current_base)) {
73
-		include_spip('inc/filtres_mini');
74
-		// le decodage des urls se fait toujours par rapport au site public
75
-		$current_base = url_absolue(_DIR_RACINE ?: './');
76
-	}
77
-	if (strncmp($url, $current_base, strlen($current_base)) == 0) {
78
-		$url = substr($url, strlen($current_base));
79
-	}
72
+    if (is_null($current_base)) {
73
+        include_spip('inc/filtres_mini');
74
+        // le decodage des urls se fait toujours par rapport au site public
75
+        $current_base = url_absolue(_DIR_RACINE ?: './');
76
+    }
77
+    if (strncmp($url, $current_base, strlen($current_base)) == 0) {
78
+        $url = substr($url, strlen($current_base));
79
+    }
80 80
 
81
-	// si on est en train d'assembler la page principale,
82
-	// recuperer l'url depuis les globales url propres si fournies
83
-	// sinon extraire la bonne portion d'url
84
-	if ($assembler) {
85
-		if (isset($_SERVER['REDIRECT_url_propre'])) {
86
-			$url = $_SERVER['REDIRECT_url_propre'];
87
-		} elseif (isset($_ENV['url_propre'])) {
88
-			$url = $_ENV['url_propre'];
89
-		} else {
90
-			$qs = explode('?', $url);
91
-			// ne prendre que le segment d'url qui correspond, en fonction de la profondeur calculee
92
-			$url = ltrim($qs[0], '/');
93
-			$url = explode('/', $url);
94
-			while (count($url) > $GLOBALS['profondeur_url'] + 1) {
95
-				array_shift($url);
96
-			}
97
-			$qs[0] = implode('/', $url);
98
-			$url = implode('?', $qs);
99
-		}
100
-	}
81
+    // si on est en train d'assembler la page principale,
82
+    // recuperer l'url depuis les globales url propres si fournies
83
+    // sinon extraire la bonne portion d'url
84
+    if ($assembler) {
85
+        if (isset($_SERVER['REDIRECT_url_propre'])) {
86
+            $url = $_SERVER['REDIRECT_url_propre'];
87
+        } elseif (isset($_ENV['url_propre'])) {
88
+            $url = $_ENV['url_propre'];
89
+        } else {
90
+            $qs = explode('?', $url);
91
+            // ne prendre que le segment d'url qui correspond, en fonction de la profondeur calculee
92
+            $url = ltrim($qs[0], '/');
93
+            $url = explode('/', $url);
94
+            while (count($url) > $GLOBALS['profondeur_url'] + 1) {
95
+                array_shift($url);
96
+            }
97
+            $qs[0] = implode('/', $url);
98
+            $url = implode('?', $qs);
99
+        }
100
+    }
101 101
 
102
-	unset($_SERVER['REDIRECT_url_propre']);
103
-	unset($_ENV['url_propre']);
104
-	include_spip('inc/filtres_mini');
105
-	if (strpos($url, '://') === false) {
106
-		$GLOBALS['profondeur_url'] = substr_count(ltrim(resolve_path("/$url"), '/'), '/');
107
-	} else {
108
-		$GLOBALS['profondeur_url'] = max(0, substr_count($url, '/') - substr_count($current_base, '/'));
109
-	}
102
+    unset($_SERVER['REDIRECT_url_propre']);
103
+    unset($_ENV['url_propre']);
104
+    include_spip('inc/filtres_mini');
105
+    if (strpos($url, '://') === false) {
106
+        $GLOBALS['profondeur_url'] = substr_count(ltrim(resolve_path("/$url"), '/'), '/');
107
+    } else {
108
+        $GLOBALS['profondeur_url'] = max(0, substr_count($url, '/') - substr_count($current_base, '/'));
109
+    }
110 110
 
111
-	$url_redirect = '';
112
-	$decoder = charger_fonction_url('decoder');
113
-	if ($decoder) {
114
-		$a = $decoder($url, $fond, $contexte);
115
-		if (is_array($a)) {
116
-			[$ncontexte, $type, $url_redirect, $nfond] = array_pad($a, 4, null);
117
-			$url_redirect ??= '';
118
-			if ($url_redirect === $url) {
119
-				$url_redirect = '';
120
-			} // securite pour eviter une redirection infinie
121
-			if ($assembler and strlen($url_redirect)) {
122
-				spip_log("Redirige $url vers $url_redirect");
123
-				include_spip('inc/headers');
124
-				redirige_par_entete($url_redirect, '', 301);
125
-			}
126
-			if (isset($nfond)) {
127
-				$fond = $nfond;
128
-			} else {
129
-				if (
130
-					$fond == ''
131
-					or $fond == 'type_urls' /* compat avec htaccess 2.0.0 */
132
-				) {
133
-					$fond = $type;
134
-				}
135
-			}
136
-			if (isset($ncontexte)) {
137
-				$contexte = $ncontexte;
138
-			}
139
-			if (defined('_DEFINIR_CONTEXTE_TYPE') and _DEFINIR_CONTEXTE_TYPE) {
140
-				$contexte['type'] = $type;
141
-			}
142
-			if (!defined('_DEFINIR_CONTEXTE_TYPE_PAGE') or _DEFINIR_CONTEXTE_TYPE_PAGE) {
143
-				$contexte['type-page'] = $type;
144
-			}
145
-		}
146
-	}
111
+    $url_redirect = '';
112
+    $decoder = charger_fonction_url('decoder');
113
+    if ($decoder) {
114
+        $a = $decoder($url, $fond, $contexte);
115
+        if (is_array($a)) {
116
+            [$ncontexte, $type, $url_redirect, $nfond] = array_pad($a, 4, null);
117
+            $url_redirect ??= '';
118
+            if ($url_redirect === $url) {
119
+                $url_redirect = '';
120
+            } // securite pour eviter une redirection infinie
121
+            if ($assembler and strlen($url_redirect)) {
122
+                spip_log("Redirige $url vers $url_redirect");
123
+                include_spip('inc/headers');
124
+                redirige_par_entete($url_redirect, '', 301);
125
+            }
126
+            if (isset($nfond)) {
127
+                $fond = $nfond;
128
+            } else {
129
+                if (
130
+                    $fond == ''
131
+                    or $fond == 'type_urls' /* compat avec htaccess 2.0.0 */
132
+                ) {
133
+                    $fond = $type;
134
+                }
135
+            }
136
+            if (isset($ncontexte)) {
137
+                $contexte = $ncontexte;
138
+            }
139
+            if (defined('_DEFINIR_CONTEXTE_TYPE') and _DEFINIR_CONTEXTE_TYPE) {
140
+                $contexte['type'] = $type;
141
+            }
142
+            if (!defined('_DEFINIR_CONTEXTE_TYPE_PAGE') or _DEFINIR_CONTEXTE_TYPE_PAGE) {
143
+                $contexte['type-page'] = $type;
144
+            }
145
+        }
146
+    }
147 147
 
148
-	// retablir les globales
149
-	[$GLOBALS['fond'], $GLOBALS['contexte'], $_SERVER['REDIRECT_url_propre'], $_ENV['url_propre'], $GLOBALS['profondeur_url']] = $save;
148
+    // retablir les globales
149
+    [$GLOBALS['fond'], $GLOBALS['contexte'], $_SERVER['REDIRECT_url_propre'], $_ENV['url_propre'], $GLOBALS['profondeur_url']] = $save;
150 150
 
151
-	// vider les globales url propres qui ne doivent plus etre utilisees en cas
152
-	// d'inversion url => objet
153
-	// maintenir pour compat ?
154
-	#if ($assembler) {
155
-	#	unset($_SERVER['REDIRECT_url_propre']);
156
-	#	unset($_ENV['url_propre']);
157
-	#}
151
+    // vider les globales url propres qui ne doivent plus etre utilisees en cas
152
+    // d'inversion url => objet
153
+    // maintenir pour compat ?
154
+    #if ($assembler) {
155
+    #	unset($_SERVER['REDIRECT_url_propre']);
156
+    #	unset($_ENV['url_propre']);
157
+    #}
158 158
 
159
-	return [$fond, $contexte, $url_redirect];
159
+    return [$fond, $contexte, $url_redirect];
160 160
 }
161 161
 
162 162
 /**
@@ -169,20 +169,20 @@  discard block
 block discarded – undo
169 169
  * @return array|false|string
170 170
  */
171 171
 function urls_transition_retrouver_anciennes_url_propres(string $url_propre, string $entite, array $contexte = []): array {
172
-	if ($url_propre) {
173
-		if ($GLOBALS['profondeur_url'] <= 0) {
174
-			$urls_anciennes = charger_fonction_url('decoder', 'propres');
175
-		} else {
176
-			$urls_anciennes = charger_fonction_url('decoder', 'arbo');
177
-		}
172
+    if ($url_propre) {
173
+        if ($GLOBALS['profondeur_url'] <= 0) {
174
+            $urls_anciennes = charger_fonction_url('decoder', 'propres');
175
+        } else {
176
+            $urls_anciennes = charger_fonction_url('decoder', 'arbo');
177
+        }
178 178
 
179
-		if ($urls_anciennes) {
180
-			$urls_anciennes = $urls_anciennes($url_propre, $entite, $contexte);
181
-		}
182
-		return $urls_anciennes ?: [];
183
-	}
179
+        if ($urls_anciennes) {
180
+            $urls_anciennes = $urls_anciennes($url_propre, $entite, $contexte);
181
+        }
182
+        return $urls_anciennes ?: [];
183
+    }
184 184
 
185
-	return [];
185
+    return [];
186 186
 }
187 187
 
188 188
 /**
@@ -195,41 +195,41 @@  discard block
 block discarded – undo
195 195
  * @return array|false|string
196 196
  */
197 197
 function urls_transition_retrouver_anciennes_url_html(string $url, string $entite, array $contexte = []): array {
198
-	// Migration depuis anciennes URLs ?
199
-	// traiter les injections domain.tld/spip.php/n/importe/quoi/rubrique23
200
-	if (
201
-		$url
202
-		and $GLOBALS['profondeur_url'] <= 0
203
-	) {
204
-		$r = nettoyer_url_page($url, $contexte);
205
-		if ($r) {
206
-			[$contexte, $type, , , $suite] = $r;
207
-			$_id = id_table_objet($type);
208
-			$id_objet = $contexte[$_id];
209
-			$url_propre = generer_objet_url($id_objet, $type);
210
-			if (
211
-				strlen($url_propre)
212
-				and !strstr($url, (string) $url_propre)
213
-				and (
214
-					objet_test_si_publie($type, $id_objet)
215
-					or (defined('_VAR_PREVIEW') and _VAR_PREVIEW and autoriser('voir', $type, $id_objet))
216
-				)
217
-			) {
218
-				[, $hash] = array_pad(explode('#', $url_propre), 2, '');
219
-				$args = [];
220
-				foreach (array_filter(explode('&', $suite ?? '')) as $fragment) {
221
-					if ($fragment != "$_id=$id_objet") {
222
-						$args[] = $fragment;
223
-					}
224
-				}
225
-				$url_redirect = generer_objet_url($id_objet, $type, join('&', array_filter($args)), $hash);
198
+    // Migration depuis anciennes URLs ?
199
+    // traiter les injections domain.tld/spip.php/n/importe/quoi/rubrique23
200
+    if (
201
+        $url
202
+        and $GLOBALS['profondeur_url'] <= 0
203
+    ) {
204
+        $r = nettoyer_url_page($url, $contexte);
205
+        if ($r) {
206
+            [$contexte, $type, , , $suite] = $r;
207
+            $_id = id_table_objet($type);
208
+            $id_objet = $contexte[$_id];
209
+            $url_propre = generer_objet_url($id_objet, $type);
210
+            if (
211
+                strlen($url_propre)
212
+                and !strstr($url, (string) $url_propre)
213
+                and (
214
+                    objet_test_si_publie($type, $id_objet)
215
+                    or (defined('_VAR_PREVIEW') and _VAR_PREVIEW and autoriser('voir', $type, $id_objet))
216
+                )
217
+            ) {
218
+                [, $hash] = array_pad(explode('#', $url_propre), 2, '');
219
+                $args = [];
220
+                foreach (array_filter(explode('&', $suite ?? '')) as $fragment) {
221
+                    if ($fragment != "$_id=$id_objet") {
222
+                        $args[] = $fragment;
223
+                    }
224
+                }
225
+                $url_redirect = generer_objet_url($id_objet, $type, join('&', array_filter($args)), $hash);
226 226
 
227
-				return [$contexte, $type, $url_redirect, $type];
228
-			}
229
-		}
230
-	}
231
-	/* Fin compatibilite anciennes urls */
232
-	return [];
227
+                return [$contexte, $type, $url_redirect, $type];
228
+            }
229
+        }
230
+    }
231
+    /* Fin compatibilite anciennes urls */
232
+    return [];
233 233
 }
234 234
 
235 235
 /**
@@ -242,24 +242,24 @@  discard block
 block discarded – undo
242 242
  * @return string|array
243 243
  */
244 244
 function urls_liste_objets($preg = true) {
245
-	static $url_objets = null;
246
-	if (is_null($url_objets)) {
247
-		$url_objets = [];
248
-		// recuperer les tables_objets_sql declarees
249
-		$tables_objets = lister_tables_objets_sql();
250
-		foreach ($tables_objets as $t => $infos) {
251
-			if ($infos['page']) {
252
-				$url_objets[] = $infos['type'];
253
-				$url_objets = array_merge($url_objets, $infos['type_surnoms']);
254
-			}
255
-		}
256
-		$url_objets = pipeline('declarer_url_objets', $url_objets);
257
-	}
258
-	if (!$preg) {
259
-		return $url_objets;
260
-	}
245
+    static $url_objets = null;
246
+    if (is_null($url_objets)) {
247
+        $url_objets = [];
248
+        // recuperer les tables_objets_sql declarees
249
+        $tables_objets = lister_tables_objets_sql();
250
+        foreach ($tables_objets as $t => $infos) {
251
+            if ($infos['page']) {
252
+                $url_objets[] = $infos['type'];
253
+                $url_objets = array_merge($url_objets, $infos['type_surnoms']);
254
+            }
255
+        }
256
+        $url_objets = pipeline('declarer_url_objets', $url_objets);
257
+    }
258
+    if (!$preg) {
259
+        return $url_objets;
260
+    }
261 261
 
262
-	return implode('|', array_map('preg_quote', $url_objets));
262
+    return implode('|', array_map('preg_quote', $url_objets));
263 263
 }
264 264
 
265 265
 /**
@@ -273,26 +273,26 @@  discard block
 block discarded – undo
273 273
  * @return array
274 274
  */
275 275
 function nettoyer_url_page($url, $contexte = []) {
276
-	$url_objets = urls_liste_objets();
277
-	$raccourci_url_page_html = ',^(?:[^?]*/)?(' . $url_objets . ')([0-9]+)(?:\.html)?([?&].*)?$,';
278
-	$raccourci_url_page_id = ',^(?:[^?]*/)?(' . $url_objets . ')\.php3?[?]id_\1=([0-9]+)([?&].*)?$,';
279
-	$raccourci_url_page_spip = ',^(?:[^?]*/)?(?:spip[.]php)?[?](' . $url_objets . ')([0-9]+)=?(&.*)?$,';
276
+    $url_objets = urls_liste_objets();
277
+    $raccourci_url_page_html = ',^(?:[^?]*/)?(' . $url_objets . ')([0-9]+)(?:\.html)?([?&].*)?$,';
278
+    $raccourci_url_page_id = ',^(?:[^?]*/)?(' . $url_objets . ')\.php3?[?]id_\1=([0-9]+)([?&].*)?$,';
279
+    $raccourci_url_page_spip = ',^(?:[^?]*/)?(?:spip[.]php)?[?](' . $url_objets . ')([0-9]+)=?(&.*)?$,';
280 280
 
281
-	if (
282
-		preg_match($raccourci_url_page_html, $url, $regs)
283
-		or preg_match($raccourci_url_page_id, $url, $regs)
284
-		or preg_match($raccourci_url_page_spip, $url, $regs)
285
-	) {
286
-		$regs = array_pad($regs, 4, null);
287
-		$type = objet_type($regs[1]);
288
-		$_id = id_table_objet($type);
289
-		$contexte[$_id] = $regs[2];
290
-		$suite = $regs[3];
281
+    if (
282
+        preg_match($raccourci_url_page_html, $url, $regs)
283
+        or preg_match($raccourci_url_page_id, $url, $regs)
284
+        or preg_match($raccourci_url_page_spip, $url, $regs)
285
+    ) {
286
+        $regs = array_pad($regs, 4, null);
287
+        $type = objet_type($regs[1]);
288
+        $_id = id_table_objet($type);
289
+        $contexte[$_id] = $regs[2];
290
+        $suite = $regs[3];
291 291
 
292
-		return [$contexte, $type, null, $type, $suite];
293
-	}
292
+        return [$contexte, $type, null, $type, $suite];
293
+    }
294 294
 
295
-	return [];
295
+    return [];
296 296
 }
297 297
 
298 298
 /**
@@ -310,38 +310,38 @@  discard block
 block discarded – undo
310 310
  * @return string
311 311
  */
312 312
 function generer_objet_url_ecrire($id, string $objet, string $args = '', string $ancre = '', ?bool $public = null, string $connect = ''): string {
313
-	static $furls = [];
314
-	$id = intval($id);
315
-	if (!isset($furls[$objet])) {
316
-		if (
317
-			function_exists($f = 'generer_' . $objet . '_url_ecrire')
318
-			// ou definie par un plugin
319
-			or $f = charger_fonction($f, 'urls', true)
320
-			// deprecated
321
-			or function_exists($f = 'generer_url_ecrire_' . $objet) or $f = charger_fonction($f, 'urls', true)
322
-		) {
323
-			$furls[$objet] = $f;
324
-		} else {
325
-			$furls[$objet] = '';
326
-		}
327
-	}
328
-	if ($furls[$objet]) {
329
-		return $furls[$objet]($id, $args, $ancre, $public, $connect);
330
-	}
331
-	// si pas de flag public fourni
332
-	// le calculer en fonction de la declaration de statut
333
-	if (is_null($public) and !$connect) {
334
-		$public = objet_test_si_publie($objet, $id, $connect);
335
-	}
336
-	if ($public or $connect) {
337
-		return generer_objet_url_absolue($id, $objet, $args, $ancre, $public, '', $connect);
338
-	}
339
-	$a = id_table_objet($objet) . '=' . intval($id);
340
-	if (!function_exists('objet_info')) {
341
-		include_spip('inc/filtres');
342
-	}
313
+    static $furls = [];
314
+    $id = intval($id);
315
+    if (!isset($furls[$objet])) {
316
+        if (
317
+            function_exists($f = 'generer_' . $objet . '_url_ecrire')
318
+            // ou definie par un plugin
319
+            or $f = charger_fonction($f, 'urls', true)
320
+            // deprecated
321
+            or function_exists($f = 'generer_url_ecrire_' . $objet) or $f = charger_fonction($f, 'urls', true)
322
+        ) {
323
+            $furls[$objet] = $f;
324
+        } else {
325
+            $furls[$objet] = '';
326
+        }
327
+    }
328
+    if ($furls[$objet]) {
329
+        return $furls[$objet]($id, $args, $ancre, $public, $connect);
330
+    }
331
+    // si pas de flag public fourni
332
+    // le calculer en fonction de la declaration de statut
333
+    if (is_null($public) and !$connect) {
334
+        $public = objet_test_si_publie($objet, $id, $connect);
335
+    }
336
+    if ($public or $connect) {
337
+        return generer_objet_url_absolue($id, $objet, $args, $ancre, $public, '', $connect);
338
+    }
339
+    $a = id_table_objet($objet) . '=' . intval($id);
340
+    if (!function_exists('objet_info')) {
341
+        include_spip('inc/filtres');
342
+    }
343 343
 
344
-	return generer_url_ecrire(objet_info($objet, 'url_voir'), $a . ($args ? "&$args" : '')) . ($ancre ? "#$ancre" : '');
344
+    return generer_url_ecrire(objet_info($objet, 'url_voir'), $a . ($args ? "&$args" : '')) . ($ancre ? "#$ancre" : '');
345 345
 }
346 346
 
347 347
 /**
@@ -349,5 +349,5 @@  discard block
 block discarded – undo
349 349
  * @see generer_objet_url_ecrire
350 350
  */
351 351
 function generer_url_ecrire_objet($objet, $id, $args = '', $ancre = '', $public = null, string $connect = '') {
352
-	return generer_objet_url_ecrire($id, $objet, $args, $ancre, $public, $connect);
352
+    return generer_objet_url_ecrire($id, $objet, $args, $ancre, $public, $connect);
353 353
 }
Please login to merge, or discard this patch.
ecrire/inc/lien.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('base/abstract_sql');
@@ -37,42 +37,42 @@  discard block
 block discarded – undo
37 37
  * @return string
38 38
  */
39 39
 function inc_lien_dist(
40
-	$lien,
41
-	$texte = '',
42
-	$class = '',
43
-	$title = '',
44
-	$hlang = '',
45
-	$rel = '',
46
-	string $connect = '',
47
-	$env = []
40
+    $lien,
41
+    $texte = '',
42
+    $class = '',
43
+    $title = '',
44
+    $hlang = '',
45
+    $rel = '',
46
+    string $connect = '',
47
+    $env = []
48 48
 ) {
49
-	return $lien;
49
+    return $lien;
50 50
 }
51 51
 
52 52
 function expanser_liens($t, string $connect = '', $env = []) {
53 53
 
54
-	$t = pipeline('pre_liens', $t);
54
+    $t = pipeline('pre_liens', $t);
55 55
 
56
-	// on passe a traiter_modeles la liste des liens reperes pour lui permettre
57
-	// de remettre le texte d'origine dans les parametres du modele
58
-	$t = traiter_modeles($t, false, false, $connect);
56
+    // on passe a traiter_modeles la liste des liens reperes pour lui permettre
57
+    // de remettre le texte d'origine dans les parametres du modele
58
+    $t = traiter_modeles($t, false, false, $connect);
59 59
 
60
-	return $t;
60
+    return $t;
61 61
 }
62 62
 
63 63
 // Meme analyse mais pour eliminer les liens
64 64
 // et ne laisser que leur titre, a expliciter si ce n'est fait
65 65
 function nettoyer_raccourcis_typo($texte, string $connect = '') {
66
-	return $texte;
66
+    return $texte;
67 67
 }
68 68
 
69 69
 // Repere dans la partie texte d'un raccourci [texte->...]
70 70
 // la langue et la bulle eventuelles
71 71
 function traiter_raccourci_lien_atts($texte) {
72
-	$bulle = '';
73
-	$hlang = '';
72
+    $bulle = '';
73
+    $hlang = '';
74 74
 
75
-	return [trim($texte), $bulle, $hlang];
75
+    return [trim($texte), $bulle, $hlang];
76 76
 }
77 77
 
78 78
 define('_RACCOURCI_CHAPO', '/^(\W*)(\W*)(\w*\d+([?#].*)?)$/');
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
  * @return string
89 89
  */
90 90
 function virtuel_redirige($virtuel, $url = false) {
91
-	return $virtuel;
91
+    return $virtuel;
92 92
 }
93 93
 
94 94
 // Cherche un lien du type [->raccourci 123]
@@ -101,62 +101,62 @@  discard block
 block discarded – undo
101 101
 // 'url':   seulement U  (i.e. generer_url_RACCOURCI)
102 102
 
103 103
 function calculer_url($ref, $texte = '', $pour = 'url', string $connect = '', $echappe_typo = true) {
104
-	$r = traiter_lien_implicite($ref, $texte, $pour, $connect);
104
+    $r = traiter_lien_implicite($ref, $texte, $pour, $connect);
105 105
 
106
-	return $r ?: traiter_lien_explicite($ref, $texte, $pour, $connect, $echappe_typo);
106
+    return $r ?: traiter_lien_explicite($ref, $texte, $pour, $connect, $echappe_typo);
107 107
 }
108 108
 
109 109
 define('_EXTRAIRE_LIEN', ',^\s*(?:' . _PROTOCOLES_STD . '):?/?/?\s*$,iS');
110 110
 
111 111
 function traiter_lien_explicite($ref, $texte = '', $pour = 'url', string $connect = '', $echappe_typo = true) {
112
-	if (preg_match(_EXTRAIRE_LIEN, $ref)) {
113
-		return ($pour != 'tout') ? '' : ['', '', '', ''];
114
-	}
115
-
116
-	$lien = entites_html(trim($ref));
117
-
118
-	// Liens explicites
119
-	if (!$texte) {
120
-		$texte = str_replace('"', '', $lien);
121
-		// evite l'affichage de trops longues urls.
122
-		$lien_court = charger_fonction('lien_court', 'inc');
123
-		$texte = $lien_court($texte);
124
-		if ($echappe_typo) {
125
-			$texte = '<html>' . quote_amp($texte) . '</html>';
126
-		}
127
-	}
128
-
129
-	// petites corrections d'URL
130
-	if (preg_match('/^www\.[^@]+$/S', $lien)) {
131
-		$lien = 'http://' . $lien;
132
-	} else {
133
-		if (strpos($lien, '@') && email_valide($lien)) {
134
-			if (!$texte) {
135
-				$texte = $lien;
136
-			}
137
-			$lien = 'mailto:' . $lien;
138
-		}
139
-	}
140
-
141
-	if ($pour == 'url') {
142
-		return $lien;
143
-	}
144
-
145
-	if ($pour == 'titre') {
146
-		return $texte;
147
-	}
148
-
149
-	return ['url' => $lien, 'titre' => $texte];
112
+    if (preg_match(_EXTRAIRE_LIEN, $ref)) {
113
+        return ($pour != 'tout') ? '' : ['', '', '', ''];
114
+    }
115
+
116
+    $lien = entites_html(trim($ref));
117
+
118
+    // Liens explicites
119
+    if (!$texte) {
120
+        $texte = str_replace('"', '', $lien);
121
+        // evite l'affichage de trops longues urls.
122
+        $lien_court = charger_fonction('lien_court', 'inc');
123
+        $texte = $lien_court($texte);
124
+        if ($echappe_typo) {
125
+            $texte = '<html>' . quote_amp($texte) . '</html>';
126
+        }
127
+    }
128
+
129
+    // petites corrections d'URL
130
+    if (preg_match('/^www\.[^@]+$/S', $lien)) {
131
+        $lien = 'http://' . $lien;
132
+    } else {
133
+        if (strpos($lien, '@') && email_valide($lien)) {
134
+            if (!$texte) {
135
+                $texte = $lien;
136
+            }
137
+            $lien = 'mailto:' . $lien;
138
+        }
139
+    }
140
+
141
+    if ($pour == 'url') {
142
+        return $lien;
143
+    }
144
+
145
+    if ($pour == 'titre') {
146
+        return $texte;
147
+    }
148
+
149
+    return ['url' => $lien, 'titre' => $texte];
150 150
 }
151 151
 
152 152
 function liens_implicite_glose_dist($texte, $id, $type, $args, $ancre, string $connect = '') {
153
-	if (function_exists($f = 'glossaire_' . $ancre)) {
154
-		$url = $f($texte, $id);
155
-	} else {
156
-		$url = glossaire_std($texte);
157
-	}
153
+    if (function_exists($f = 'glossaire_' . $ancre)) {
154
+        $url = $f($texte, $id);
155
+    } else {
156
+        $url = glossaire_std($texte);
157
+    }
158 158
 
159
-	return $url;
159
+    return $url;
160 160
 }
161 161
 
162 162
 /**
@@ -178,74 +178,74 @@  discard block
 block discarded – undo
178 178
  * @return array|bool|string
179 179
  */
180 180
 function traiter_lien_implicite($ref, $texte = '', $pour = 'url', $connect = '') {
181
-	$cible = $GLOBALS['lien_implicite_cible_public'] ?? null;
182
-	if (!($match = typer_raccourci($ref))) {
183
-		return false;
184
-	}
185
-
186
-	[$type, , $id, , $args, , $ancre] = array_pad($match, 7, null);
187
-
188
-	# attention dans le cas des sites le lien doit pointer non pas sur
189
-	# la page locale du site, mais directement sur le site lui-meme
190
-	$url = '';
191
-	if ($f = charger_fonction("implicite_$type", 'liens', true)) {
192
-		$url = $f($texte, $id, $type, $args, $ancre, $connect);
193
-	}
194
-
195
-	if (!$url) {
196
-		$url = generer_objet_url($id, $type, $args ?? '', $ancre ?? '', $cible, '', $connect ?? '');
197
-	}
198
-
199
-	if (!$url) {
200
-		return false;
201
-	}
202
-
203
-	if (is_array($url)) {
204
-		[$type, $id] = array_pad($url, 2, null);
205
-		$url = generer_objet_url($id, $type, $args ?? '', $ancre ?? '', $cible, '', $connect ?? '');
206
-	}
207
-
208
-	if ($pour === 'url') {
209
-		return $url;
210
-	}
211
-
212
-	$r = traiter_raccourci_titre($id, $type, $connect);
213
-	if ($r) {
214
-		$r['class'] = ($type == 'site') ? 'spip_out' : 'spip_in';
215
-	}
216
-
217
-	if ($texte = trim($texte)) {
218
-		$r['titre'] = $texte;
219
-	}
220
-
221
-	if (!@$r['titre']) {
222
-		$r['titre'] = _T($type) . " $id";
223
-	}
224
-
225
-	if ($pour == 'titre') {
226
-		return $r['titre'];
227
-	}
228
-
229
-	$r['url'] = $url;
230
-
231
-	// dans le cas d'un lien vers un doc, ajouter le type='mime/type'
232
-	if (
233
-		$type == 'document'
234
-		and $mime = sql_getfetsel(
235
-			'mime_type',
236
-			'spip_types_documents',
237
-			'extension IN (' . sql_get_select('extension', 'spip_documents', 'id_document=' . sql_quote($id)) . ')',
238
-			'',
239
-			'',
240
-			'',
241
-			'',
242
-			$connect
243
-		)
244
-	) {
245
-		$r['mime'] = $mime;
246
-	}
247
-
248
-	return $r;
181
+    $cible = $GLOBALS['lien_implicite_cible_public'] ?? null;
182
+    if (!($match = typer_raccourci($ref))) {
183
+        return false;
184
+    }
185
+
186
+    [$type, , $id, , $args, , $ancre] = array_pad($match, 7, null);
187
+
188
+    # attention dans le cas des sites le lien doit pointer non pas sur
189
+    # la page locale du site, mais directement sur le site lui-meme
190
+    $url = '';
191
+    if ($f = charger_fonction("implicite_$type", 'liens', true)) {
192
+        $url = $f($texte, $id, $type, $args, $ancre, $connect);
193
+    }
194
+
195
+    if (!$url) {
196
+        $url = generer_objet_url($id, $type, $args ?? '', $ancre ?? '', $cible, '', $connect ?? '');
197
+    }
198
+
199
+    if (!$url) {
200
+        return false;
201
+    }
202
+
203
+    if (is_array($url)) {
204
+        [$type, $id] = array_pad($url, 2, null);
205
+        $url = generer_objet_url($id, $type, $args ?? '', $ancre ?? '', $cible, '', $connect ?? '');
206
+    }
207
+
208
+    if ($pour === 'url') {
209
+        return $url;
210
+    }
211
+
212
+    $r = traiter_raccourci_titre($id, $type, $connect);
213
+    if ($r) {
214
+        $r['class'] = ($type == 'site') ? 'spip_out' : 'spip_in';
215
+    }
216
+
217
+    if ($texte = trim($texte)) {
218
+        $r['titre'] = $texte;
219
+    }
220
+
221
+    if (!@$r['titre']) {
222
+        $r['titre'] = _T($type) . " $id";
223
+    }
224
+
225
+    if ($pour == 'titre') {
226
+        return $r['titre'];
227
+    }
228
+
229
+    $r['url'] = $url;
230
+
231
+    // dans le cas d'un lien vers un doc, ajouter le type='mime/type'
232
+    if (
233
+        $type == 'document'
234
+        and $mime = sql_getfetsel(
235
+            'mime_type',
236
+            'spip_types_documents',
237
+            'extension IN (' . sql_get_select('extension', 'spip_documents', 'id_document=' . sql_quote($id)) . ')',
238
+            '',
239
+            '',
240
+            '',
241
+            '',
242
+            $connect
243
+        )
244
+    ) {
245
+        $r['mime'] = $mime;
246
+    }
247
+
248
+    return $r;
249 249
 }
250 250
 
251 251
 // analyse des raccourcis issus de [TITRE->RACCOURCInnn] et connexes
@@ -253,43 +253,43 @@  discard block
 block discarded – undo
253 253
 define('_RACCOURCI_URL', '/^\s*(\w*?)\s*(\d+)(\?(.*?))?(#([^\s]*))?\s*$/S');
254 254
 
255 255
 function typer_raccourci($lien) {
256
-	if (!preg_match(_RACCOURCI_URL, $lien, $match)) {
257
-		return [];
258
-	}
259
-
260
-	$f = $match[1];
261
-	// valeur par defaut et alias historiques
262
-	if (!$f) {
263
-		$f = 'article';
264
-	} else {
265
-		if ($f == 'art') {
266
-			$f = 'article';
267
-		} else {
268
-			if ($f == 'br') {
269
-				$f = 'breve';
270
-			} else {
271
-				if ($f == 'rub') {
272
-					$f = 'rubrique';
273
-				} else {
274
-					if ($f == 'aut') {
275
-						$f = 'auteur';
276
-					} else {
277
-						if ($f == 'doc' or $f == 'im' or $f == 'img' or $f == 'image' or $f == 'emb') {
278
-							$f = 'document';
279
-						} else {
280
-							if (preg_match('/^br..?ve$/S', $f)) {
281
-								$f = 'breve'; # accents :(
282
-							}
283
-						}
284
-					}
285
-				}
286
-			}
287
-		}
288
-	}
289
-
290
-	$match[0] = $f;
291
-
292
-	return $match;
256
+    if (!preg_match(_RACCOURCI_URL, $lien, $match)) {
257
+        return [];
258
+    }
259
+
260
+    $f = $match[1];
261
+    // valeur par defaut et alias historiques
262
+    if (!$f) {
263
+        $f = 'article';
264
+    } else {
265
+        if ($f == 'art') {
266
+            $f = 'article';
267
+        } else {
268
+            if ($f == 'br') {
269
+                $f = 'breve';
270
+            } else {
271
+                if ($f == 'rub') {
272
+                    $f = 'rubrique';
273
+                } else {
274
+                    if ($f == 'aut') {
275
+                        $f = 'auteur';
276
+                    } else {
277
+                        if ($f == 'doc' or $f == 'im' or $f == 'img' or $f == 'image' or $f == 'emb') {
278
+                            $f = 'document';
279
+                        } else {
280
+                            if (preg_match('/^br..?ve$/S', $f)) {
281
+                                $f = 'breve'; # accents :(
282
+                            }
283
+                        }
284
+                    }
285
+                }
286
+            }
287
+        }
288
+    }
289
+
290
+    $match[0] = $f;
291
+
292
+    return $match;
293 293
 }
294 294
 
295 295
 /**
@@ -304,44 +304,44 @@  discard block
 block discarded – undo
304 304
  * }
305 305
  **/
306 306
 function traiter_raccourci_titre($id, $type, $connect = null) {
307
-	$trouver_table = charger_fonction('trouver_table', 'base');
308
-	$desc = $trouver_table(table_objet($type));
307
+    $trouver_table = charger_fonction('trouver_table', 'base');
308
+    $desc = $trouver_table(table_objet($type));
309 309
 
310
-	if (!($desc and $s = $desc['titre'])) {
311
-		return [];
312
-	}
310
+    if (!($desc and $s = $desc['titre'])) {
311
+        return [];
312
+    }
313 313
 
314
-	$_id = $desc['key']['PRIMARY KEY'];
315
-	$r = sql_fetsel($s, $desc['table'], "$_id=$id", '', '', '', '', $connect);
314
+    $_id = $desc['key']['PRIMARY KEY'];
315
+    $r = sql_fetsel($s, $desc['table'], "$_id=$id", '', '', '', '', $connect);
316 316
 
317
-	if (!$r) {
318
-		return [];
319
-	}
317
+    if (!$r) {
318
+        return [];
319
+    }
320 320
 
321
-	$r['titre'] = supprimer_numero($r['titre']);
321
+    $r['titre'] = supprimer_numero($r['titre']);
322 322
 
323
-	if (!$r['titre'] and !empty($r['surnom'])) {
324
-		$r['titre'] = $r['surnom'];
325
-	}
323
+    if (!$r['titre'] and !empty($r['surnom'])) {
324
+        $r['titre'] = $r['surnom'];
325
+    }
326 326
 
327
-	if (!isset($r['lang'])) {
328
-		$r['lang'] = '';
329
-	}
327
+    if (!isset($r['lang'])) {
328
+        $r['lang'] = '';
329
+    }
330 330
 
331
-	return $r;
331
+    return $r;
332 332
 }
333 333
 
334 334
 //
335 335
 // Raccourcis ancre [#ancre<-]
336 336
 //
337 337
 function traiter_raccourci_ancre($letexte) {
338
-	return $letexte;
338
+    return $letexte;
339 339
 }
340 340
 
341 341
 function traiter_raccourci_glossaire($texte) {
342
-	return $texte;
342
+    return $texte;
343 343
 }
344 344
 
345 345
 function glossaire_std($terme) {
346
-	return $terme;
346
+    return $terme;
347 347
 }
Please login to merge, or discard this patch.
prive/formulaires/editer_liens.php 1 patch
Indentation   +438 added lines, -438 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Formulaires
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 
@@ -36,25 +36,25 @@  discard block
 block discarded – undo
36 36
  *   ($table_source,$objet,$id_objet,$objet_lien)
37 37
  */
38 38
 function determine_source_lien_objet($a, $b, $c) {
39
-	$table_source = $objet_lien = $objet = $id_objet = null;
40
-	// auteurs, article, 23 :
41
-	// associer des auteurs à l'article 23, sur la table pivot spip_auteurs_liens
42
-	if (is_numeric($c) and !is_numeric($b)) {
43
-		$table_source = table_objet($a);
44
-		$objet_lien = objet_type($a);
45
-		$objet = objet_type($b);
46
-		$id_objet = $c;
47
-	}
48
-	// article, 23, auteurs
49
-	// associer des auteurs à l'article 23, sur la table pivot spip_articles_liens
50
-	if (is_numeric($b) and !is_numeric($c)) {
51
-		$table_source = table_objet($c);
52
-		$objet_lien = objet_type($a);
53
-		$objet = objet_type($a);
54
-		$id_objet = $b;
55
-	}
56
-
57
-	return [$table_source, $objet, $id_objet, $objet_lien];
39
+    $table_source = $objet_lien = $objet = $id_objet = null;
40
+    // auteurs, article, 23 :
41
+    // associer des auteurs à l'article 23, sur la table pivot spip_auteurs_liens
42
+    if (is_numeric($c) and !is_numeric($b)) {
43
+        $table_source = table_objet($a);
44
+        $objet_lien = objet_type($a);
45
+        $objet = objet_type($b);
46
+        $id_objet = $c;
47
+    }
48
+    // article, 23, auteurs
49
+    // associer des auteurs à l'article 23, sur la table pivot spip_articles_liens
50
+    if (is_numeric($b) and !is_numeric($c)) {
51
+        $table_source = table_objet($c);
52
+        $objet_lien = objet_type($a);
53
+        $objet = objet_type($a);
54
+        $id_objet = $b;
55
+    }
56
+
57
+    return [$table_source, $objet, $id_objet, $objet_lien];
58 58
 }
59 59
 
60 60
 /**
@@ -80,86 +80,86 @@  discard block
 block discarded – undo
80 80
  */
81 81
 function formulaires_editer_liens_charger_dist($a, $b, $c, $options = []) {
82 82
 
83
-	// compat avec ancienne signature ou le 4eme argument est $editable
84
-	if (!is_array($options)) {
85
-		$options = ['editable' => $options];
86
-	} elseif (!isset($options['editable'])) {
87
-		$options['editable'] = true;
88
-	}
89
-
90
-	$editable = $options['editable'];
91
-
92
-	[$table_source, $objet, $id_objet, $objet_lien] = determine_source_lien_objet($a, $b, $c);
93
-	if (!$table_source or !$objet or !$objet_lien or !$id_objet) {
94
-		return false;
95
-	}
96
-
97
-	$objet_source = objet_type($table_source);
98
-	$table_sql_source = table_objet_sql($objet_source);
99
-
100
-	// verifier existence de la table xxx_liens
101
-	include_spip('action/editer_liens');
102
-	if (!objet_associable($objet_lien)) {
103
-		return false;
104
-	}
105
-
106
-	// L'éditabilité :) est définie par un test permanent (par exemple "associermots") ET le 4ème argument
107
-	include_spip('inc/autoriser');
108
-	$editable = ($editable and autoriser('associer' . $table_source, $objet, $id_objet)
109
-		and autoriser('modifier', $objet, $id_objet));
110
-
111
-	if (
112
-		!$editable and !count(objet_trouver_liens(
113
-			[$objet_lien => '*'],
114
-			[($objet_lien == $objet_source ? $objet : $objet_source) => $id_objet]
115
-		))
116
-	) {
117
-		return false;
118
-	}
119
-
120
-	// squelettes de vue et de d'association
121
-	// ils sont différents si des rôles sont définis.
122
-	$skel_vue = $table_source . '_lies';
123
-	$skel_ajout = $table_source . '_associer';
124
-
125
-	// description des roles
126
-	include_spip('inc/roles');
127
-	if ($roles = roles_presents($objet_source, $objet)) {
128
-		// on demande de nouveaux squelettes en conséquence
129
-		$skel_vue = $table_source . '_roles_lies';
130
-		$skel_ajout = $table_source . '_roles_associer';
131
-	}
132
-
133
-	$oups = '';
134
-	if ($editable) {
135
-		$oups = lien_gerer__oups('editer_liens', 'hash');
136
-	}
137
-	$valeurs = [
138
-		'id' => "$table_source-$objet-$id_objet-$objet_lien", // identifiant unique pour les id du form
139
-		'_vue_liee' => $skel_vue,
140
-		'_vue_ajout' => $skel_ajout,
141
-		'_objet_lien' => $objet_lien,
142
-		'id_lien_ajoute' => _request('id_lien_ajoute'),
143
-		'objet' => $objet,
144
-		'id_objet' => $id_objet,
145
-		'objet_source' => $objet_source,
146
-		'table_source' => $table_source,
147
-		'recherche' => '',
148
-		'visible' => 0,
149
-		'ajouter_lien' => '',
150
-		'supprimer_lien' => '',
151
-		'qualifier_lien' => '',
152
-		'ordonner_lien' => '',
153
-		'desordonner_liens' => '',
154
-		'_roles' => $roles, # description des roles
155
-		'_oups' => entites_html($oups),
156
-		'editable' => $editable,
157
-	];
158
-
159
-	// les options non definies dans $valeurs sont passees telles quelles au formulaire html
160
-	$valeurs = array_merge($options, $valeurs);
161
-
162
-	return $valeurs;
83
+    // compat avec ancienne signature ou le 4eme argument est $editable
84
+    if (!is_array($options)) {
85
+        $options = ['editable' => $options];
86
+    } elseif (!isset($options['editable'])) {
87
+        $options['editable'] = true;
88
+    }
89
+
90
+    $editable = $options['editable'];
91
+
92
+    [$table_source, $objet, $id_objet, $objet_lien] = determine_source_lien_objet($a, $b, $c);
93
+    if (!$table_source or !$objet or !$objet_lien or !$id_objet) {
94
+        return false;
95
+    }
96
+
97
+    $objet_source = objet_type($table_source);
98
+    $table_sql_source = table_objet_sql($objet_source);
99
+
100
+    // verifier existence de la table xxx_liens
101
+    include_spip('action/editer_liens');
102
+    if (!objet_associable($objet_lien)) {
103
+        return false;
104
+    }
105
+
106
+    // L'éditabilité :) est définie par un test permanent (par exemple "associermots") ET le 4ème argument
107
+    include_spip('inc/autoriser');
108
+    $editable = ($editable and autoriser('associer' . $table_source, $objet, $id_objet)
109
+        and autoriser('modifier', $objet, $id_objet));
110
+
111
+    if (
112
+        !$editable and !count(objet_trouver_liens(
113
+            [$objet_lien => '*'],
114
+            [($objet_lien == $objet_source ? $objet : $objet_source) => $id_objet]
115
+        ))
116
+    ) {
117
+        return false;
118
+    }
119
+
120
+    // squelettes de vue et de d'association
121
+    // ils sont différents si des rôles sont définis.
122
+    $skel_vue = $table_source . '_lies';
123
+    $skel_ajout = $table_source . '_associer';
124
+
125
+    // description des roles
126
+    include_spip('inc/roles');
127
+    if ($roles = roles_presents($objet_source, $objet)) {
128
+        // on demande de nouveaux squelettes en conséquence
129
+        $skel_vue = $table_source . '_roles_lies';
130
+        $skel_ajout = $table_source . '_roles_associer';
131
+    }
132
+
133
+    $oups = '';
134
+    if ($editable) {
135
+        $oups = lien_gerer__oups('editer_liens', 'hash');
136
+    }
137
+    $valeurs = [
138
+        'id' => "$table_source-$objet-$id_objet-$objet_lien", // identifiant unique pour les id du form
139
+        '_vue_liee' => $skel_vue,
140
+        '_vue_ajout' => $skel_ajout,
141
+        '_objet_lien' => $objet_lien,
142
+        'id_lien_ajoute' => _request('id_lien_ajoute'),
143
+        'objet' => $objet,
144
+        'id_objet' => $id_objet,
145
+        'objet_source' => $objet_source,
146
+        'table_source' => $table_source,
147
+        'recherche' => '',
148
+        'visible' => 0,
149
+        'ajouter_lien' => '',
150
+        'supprimer_lien' => '',
151
+        'qualifier_lien' => '',
152
+        'ordonner_lien' => '',
153
+        'desordonner_liens' => '',
154
+        '_roles' => $roles, # description des roles
155
+        '_oups' => entites_html($oups),
156
+        'editable' => $editable,
157
+    ];
158
+
159
+    // les options non definies dans $valeurs sont passees telles quelles au formulaire html
160
+    $valeurs = array_merge($options, $valeurs);
161
+
162
+    return $valeurs;
163 163
 }
164 164
 
165 165
 /**
@@ -203,170 +203,170 @@  discard block
 block discarded – undo
203 203
  * @return array
204 204
  */
205 205
 function formulaires_editer_liens_traiter_dist($a, $b, $c, $options = []) {
206
-	// compat avec ancienne signature ou le 4eme argument est $editable
207
-	if (!is_array($options)) {
208
-		$options = ['editable' => $options];
209
-	} elseif (!isset($options['editable'])) {
210
-		$options['editable'] = true;
211
-	}
212
-
213
-	$editable = $options['editable'];
214
-
215
-	$res = ['editable' => $editable ? true : false];
216
-	[$table_source, $objet, $id_objet, $objet_lien] = determine_source_lien_objet($a, $b, $c);
217
-	if (!$table_source or !$objet or !$objet_lien) {
218
-		return $res;
219
-	}
220
-
221
-
222
-	if (_request('tout_voir')) {
223
-		set_request('recherche', '');
224
-	}
225
-
226
-	include_spip('inc/autoriser');
227
-	if (autoriser('modifier', $objet, $id_objet)) {
228
-		// recuperer le oups du coup d'avant pour le propager à charger() si on ne fait rien par exemple
229
-		lien_gerer__oups('editer_liens','request');
230
-
231
-		// annuler les suppressions du coup d'avant ?
232
-		if (
233
-			_request('annuler_oups')
234
-			and $oups = lien_gerer__oups('editer_liens','get')
235
-		) {
236
-			if ($oups_objets = charger_fonction("editer_liens_oups_{$table_source}_{$objet}_{$objet_lien}", 'action', true)) {
237
-				$oups_objets($oups);
238
-			} else {
239
-				$objet_source = objet_type($table_source);
240
-				include_spip('action/editer_liens');
241
-				foreach ($oups as $oup) {
242
-					if ($objet_lien == $objet_source) {
243
-						objet_associer([$objet_source => $oup[$objet_source]], [$objet => $oup[$objet]], $oup);
244
-					} else {
245
-						objet_associer([$objet => $oup[$objet]], [$objet_source => $oup[$objet_source]], $oup);
246
-					}
247
-				}
248
-			}
249
-			# oups ne persiste que pour la derniere action, si suppression
250
-			lien_gerer__oups('editer_liens','reset');
251
-		}
252
-
253
-		$supprimer = _request('supprimer_lien');
254
-		$ajouter = _request('ajouter_lien');
255
-		$ordonner = _request('ordonner_lien');
256
-
257
-		if (_request('desordonner_liens')) {
258
-			include_spip('action/editer_liens');
259
-			objet_qualifier_liens([$objet_lien => '*'], [$objet => $id_objet], ['rang_lien' => 0]);
260
-		}
261
-
262
-		// il est possible de preciser dans une seule variable un remplacement :
263
-		// remplacer_lien[old][new]
264
-		if ($remplacer = _request('remplacer_lien')) {
265
-			foreach ($remplacer as $k => $v) {
266
-				if ($old = lien_verifier_action($k, '')) {
267
-					foreach (is_array($v) ? $v : [$v] as $kn => $vn) {
268
-						if ($new = lien_verifier_action($kn, $vn)) {
269
-							$supprimer[$old] = 'x';
270
-							$ajouter[$new] = '+';
271
-						}
272
-					}
273
-				}
274
-			}
275
-		}
276
-
277
-		if ($supprimer) {
278
-			if (
279
-				$supprimer_objets = charger_fonction(
280
-					"editer_liens_supprimer_{$table_source}_{$objet}_{$objet_lien}",
281
-					'action',
282
-					true
283
-				)
284
-			) {
285
-				$oups = $supprimer_objets($supprimer);
286
-			} else {
287
-				include_spip('action/editer_liens');
288
-				$oups = [];
289
-
290
-				foreach ($supprimer as $k => $v) {
291
-					if ($lien = lien_verifier_action($k, $v)) {
292
-						$lien = explode('-', $lien);
293
-						[$objet_source, $ids, $objet_lie, $idl, $role] = array_pad($lien, 5, null);
294
-						// appliquer une condition sur le rôle si défini ('*' pour tous les roles)
295
-						$cond = (!is_null($role) ? ['role' => $role] : []);
296
-						if ($objet_lien == $objet_source) {
297
-							$oups = array_merge(
298
-								$oups,
299
-								objet_trouver_liens([$objet_source => $ids], [$objet_lie => $idl], $cond)
300
-							);
301
-							objet_dissocier([$objet_source => $ids], [$objet_lie => $idl], $cond);
302
-						} else {
303
-							$oups = array_merge(
304
-								$oups,
305
-								objet_trouver_liens([$objet_lie => $idl], [$objet_source => $ids], $cond)
306
-							);
307
-							objet_dissocier([$objet_lie => $idl], [$objet_source => $ids], $cond);
308
-						}
309
-					}
310
-				}
311
-			}
312
-			if (!empty($oups)) {
313
-				lien_gerer__oups('editer_liens','set', $oups);
314
-			} else {
315
-				lien_gerer__oups('editer_liens','reset');
316
-			}
317
-		}
318
-
319
-		if ($ajouter) {
320
-			if (
321
-				$ajouter_objets = charger_fonction("editer_liens_ajouter_{$table_source}_{$objet}_{$objet_lien}", 'action', true)
322
-			) {
323
-				$ajout_ok = $ajouter_objets($ajouter);
324
-			} else {
325
-				$ajout_ok = false;
326
-				include_spip('action/editer_liens');
327
-				foreach ($ajouter as $k => $v) {
328
-					if ($lien = lien_verifier_action($k, $v)) {
329
-						$ajout_ok = true;
330
-						[$objet1, $ids, $objet2, $idl] = explode('-', $lien);
331
-						$qualifs = lien_retrouver_qualif($objet_lien, $lien);
332
-						if ($objet_lien == $objet1) {
333
-							lien_ajouter_liaisons($objet1, $ids, $objet2, $idl, $qualifs);
334
-						} else {
335
-							lien_ajouter_liaisons($objet2, $idl, $objet1, $ids, $qualifs);
336
-						}
337
-						set_request('id_lien_ajoute', $ids);
338
-					}
339
-				}
340
-			}
341
-			# oups ne persiste que pour la derniere action, si suppression
342
-			# une suppression suivie d'un ajout dans le meme hit est un remplacement
343
-			# non annulable !
344
-			if ($ajout_ok) {
345
-				lien_gerer__oups('editer_liens','reset');
346
-			}
347
-		}
348
-
349
-		if ($ordonner) {
350
-			include_spip('action/editer_liens');
351
-			foreach ($ordonner as $k => $rang_lien) {
352
-				if ($lien = lien_verifier_action($k, '')) {
353
-					[$objet1, $ids, $objet2, $idl] = explode('-', $lien);
354
-					$qualif = ['rang_lien' => $rang_lien];
355
-
356
-					if ($objet_lien == $objet1) {
357
-						objet_qualifier_liens([$objet1 => $ids], [$objet2 => $idl], $qualif);
358
-					} else {
359
-						objet_qualifier_liens([$objet2 => $idl], [$objet1 => $ids], $qualif);
360
-					}
361
-					set_request('id_lien_ajoute', $ids);
362
-					lien_gerer__oups('editer_liens','reset');
363
-				}
364
-			}
365
-		}
366
-	}
367
-
368
-
369
-	return $res;
206
+    // compat avec ancienne signature ou le 4eme argument est $editable
207
+    if (!is_array($options)) {
208
+        $options = ['editable' => $options];
209
+    } elseif (!isset($options['editable'])) {
210
+        $options['editable'] = true;
211
+    }
212
+
213
+    $editable = $options['editable'];
214
+
215
+    $res = ['editable' => $editable ? true : false];
216
+    [$table_source, $objet, $id_objet, $objet_lien] = determine_source_lien_objet($a, $b, $c);
217
+    if (!$table_source or !$objet or !$objet_lien) {
218
+        return $res;
219
+    }
220
+
221
+
222
+    if (_request('tout_voir')) {
223
+        set_request('recherche', '');
224
+    }
225
+
226
+    include_spip('inc/autoriser');
227
+    if (autoriser('modifier', $objet, $id_objet)) {
228
+        // recuperer le oups du coup d'avant pour le propager à charger() si on ne fait rien par exemple
229
+        lien_gerer__oups('editer_liens','request');
230
+
231
+        // annuler les suppressions du coup d'avant ?
232
+        if (
233
+            _request('annuler_oups')
234
+            and $oups = lien_gerer__oups('editer_liens','get')
235
+        ) {
236
+            if ($oups_objets = charger_fonction("editer_liens_oups_{$table_source}_{$objet}_{$objet_lien}", 'action', true)) {
237
+                $oups_objets($oups);
238
+            } else {
239
+                $objet_source = objet_type($table_source);
240
+                include_spip('action/editer_liens');
241
+                foreach ($oups as $oup) {
242
+                    if ($objet_lien == $objet_source) {
243
+                        objet_associer([$objet_source => $oup[$objet_source]], [$objet => $oup[$objet]], $oup);
244
+                    } else {
245
+                        objet_associer([$objet => $oup[$objet]], [$objet_source => $oup[$objet_source]], $oup);
246
+                    }
247
+                }
248
+            }
249
+            # oups ne persiste que pour la derniere action, si suppression
250
+            lien_gerer__oups('editer_liens','reset');
251
+        }
252
+
253
+        $supprimer = _request('supprimer_lien');
254
+        $ajouter = _request('ajouter_lien');
255
+        $ordonner = _request('ordonner_lien');
256
+
257
+        if (_request('desordonner_liens')) {
258
+            include_spip('action/editer_liens');
259
+            objet_qualifier_liens([$objet_lien => '*'], [$objet => $id_objet], ['rang_lien' => 0]);
260
+        }
261
+
262
+        // il est possible de preciser dans une seule variable un remplacement :
263
+        // remplacer_lien[old][new]
264
+        if ($remplacer = _request('remplacer_lien')) {
265
+            foreach ($remplacer as $k => $v) {
266
+                if ($old = lien_verifier_action($k, '')) {
267
+                    foreach (is_array($v) ? $v : [$v] as $kn => $vn) {
268
+                        if ($new = lien_verifier_action($kn, $vn)) {
269
+                            $supprimer[$old] = 'x';
270
+                            $ajouter[$new] = '+';
271
+                        }
272
+                    }
273
+                }
274
+            }
275
+        }
276
+
277
+        if ($supprimer) {
278
+            if (
279
+                $supprimer_objets = charger_fonction(
280
+                    "editer_liens_supprimer_{$table_source}_{$objet}_{$objet_lien}",
281
+                    'action',
282
+                    true
283
+                )
284
+            ) {
285
+                $oups = $supprimer_objets($supprimer);
286
+            } else {
287
+                include_spip('action/editer_liens');
288
+                $oups = [];
289
+
290
+                foreach ($supprimer as $k => $v) {
291
+                    if ($lien = lien_verifier_action($k, $v)) {
292
+                        $lien = explode('-', $lien);
293
+                        [$objet_source, $ids, $objet_lie, $idl, $role] = array_pad($lien, 5, null);
294
+                        // appliquer une condition sur le rôle si défini ('*' pour tous les roles)
295
+                        $cond = (!is_null($role) ? ['role' => $role] : []);
296
+                        if ($objet_lien == $objet_source) {
297
+                            $oups = array_merge(
298
+                                $oups,
299
+                                objet_trouver_liens([$objet_source => $ids], [$objet_lie => $idl], $cond)
300
+                            );
301
+                            objet_dissocier([$objet_source => $ids], [$objet_lie => $idl], $cond);
302
+                        } else {
303
+                            $oups = array_merge(
304
+                                $oups,
305
+                                objet_trouver_liens([$objet_lie => $idl], [$objet_source => $ids], $cond)
306
+                            );
307
+                            objet_dissocier([$objet_lie => $idl], [$objet_source => $ids], $cond);
308
+                        }
309
+                    }
310
+                }
311
+            }
312
+            if (!empty($oups)) {
313
+                lien_gerer__oups('editer_liens','set', $oups);
314
+            } else {
315
+                lien_gerer__oups('editer_liens','reset');
316
+            }
317
+        }
318
+
319
+        if ($ajouter) {
320
+            if (
321
+                $ajouter_objets = charger_fonction("editer_liens_ajouter_{$table_source}_{$objet}_{$objet_lien}", 'action', true)
322
+            ) {
323
+                $ajout_ok = $ajouter_objets($ajouter);
324
+            } else {
325
+                $ajout_ok = false;
326
+                include_spip('action/editer_liens');
327
+                foreach ($ajouter as $k => $v) {
328
+                    if ($lien = lien_verifier_action($k, $v)) {
329
+                        $ajout_ok = true;
330
+                        [$objet1, $ids, $objet2, $idl] = explode('-', $lien);
331
+                        $qualifs = lien_retrouver_qualif($objet_lien, $lien);
332
+                        if ($objet_lien == $objet1) {
333
+                            lien_ajouter_liaisons($objet1, $ids, $objet2, $idl, $qualifs);
334
+                        } else {
335
+                            lien_ajouter_liaisons($objet2, $idl, $objet1, $ids, $qualifs);
336
+                        }
337
+                        set_request('id_lien_ajoute', $ids);
338
+                    }
339
+                }
340
+            }
341
+            # oups ne persiste que pour la derniere action, si suppression
342
+            # une suppression suivie d'un ajout dans le meme hit est un remplacement
343
+            # non annulable !
344
+            if ($ajout_ok) {
345
+                lien_gerer__oups('editer_liens','reset');
346
+            }
347
+        }
348
+
349
+        if ($ordonner) {
350
+            include_spip('action/editer_liens');
351
+            foreach ($ordonner as $k => $rang_lien) {
352
+                if ($lien = lien_verifier_action($k, '')) {
353
+                    [$objet1, $ids, $objet2, $idl] = explode('-', $lien);
354
+                    $qualif = ['rang_lien' => $rang_lien];
355
+
356
+                    if ($objet_lien == $objet1) {
357
+                        objet_qualifier_liens([$objet1 => $ids], [$objet2 => $idl], $qualif);
358
+                    } else {
359
+                        objet_qualifier_liens([$objet2 => $idl], [$objet1 => $ids], $qualif);
360
+                    }
361
+                    set_request('id_lien_ajoute', $ids);
362
+                    lien_gerer__oups('editer_liens','reset');
363
+                }
364
+            }
365
+        }
366
+    }
367
+
368
+
369
+    return $res;
370 370
 }
371 371
 
372 372
 
@@ -389,24 +389,24 @@  discard block
 block discarded – undo
389 389
  * @return string Action demandée si trouvée, sinon ''
390 390
  */
391 391
 function lien_verifier_action($k, $v) {
392
-	$action = '';
393
-	if (preg_match(',^\w+-[\w*]+-[\w*]+-[\w*]+(-[\w*])?,', $k)) {
394
-		$action = $k;
395
-	}
396
-	if (preg_match(',^\w+-[\w*]+-[\w*]+-[\w*]+(-[\w*])?,', $v)) {
397
-		if (is_numeric($k)) {
398
-			$action = $v;
399
-		}
400
-		if (_request($k)) {
401
-			$action = $v;
402
-		}
403
-	}
404
-	// ajout un role null fictif (plus pratique) si pas défini
405
-	if ($action and count(explode('-', $action)) == 4) {
406
-		$action .= '-';
407
-	}
408
-
409
-	return $action;
392
+    $action = '';
393
+    if (preg_match(',^\w+-[\w*]+-[\w*]+-[\w*]+(-[\w*])?,', $k)) {
394
+        $action = $k;
395
+    }
396
+    if (preg_match(',^\w+-[\w*]+-[\w*]+-[\w*]+(-[\w*])?,', $v)) {
397
+        if (is_numeric($k)) {
398
+            $action = $v;
399
+        }
400
+        if (_request($k)) {
401
+            $action = $v;
402
+        }
403
+    }
404
+    // ajout un role null fictif (plus pratique) si pas défini
405
+    if ($action and count(explode('-', $action)) == 4) {
406
+        $action .= '-';
407
+    }
408
+
409
+    return $action;
410 410
 }
411 411
 
412 412
 
@@ -422,66 +422,66 @@  discard block
 block discarded – undo
422 422
  *   Liste des qualifs pour chaque lien. Tableau vide s'il n'y en a pas.
423 423
  **/
424 424
 function lien_retrouver_qualif($objet_lien, $lien) {
425
-	// un role est défini dans la liaison
426
-	$defs = explode('-', $lien);
427
-	[$objet1, , $objet2, , $role] = array_pad($defs, 5, null);
428
-	if ($objet_lien == $objet1) {
429
-		$colonne_role = roles_colonne($objet1, $objet2);
430
-	} else {
431
-		$colonne_role = roles_colonne($objet2, $objet1);
432
-	}
433
-
434
-	// cas ou le role est defini en 5e argument de l'action sur le lien (suppression, ajout rapide sans autre attribut)
435
-	if ($role) {
436
-		return [
437
-			// un seul lien avec ce role
438
-			[$colonne_role => $role]
439
-		];
440
-	}
441
-
442
-	// retrouver les rôles postés pour cette liaison, s'il y en a.
443
-	$qualifier_lien = _request('qualifier_lien');
444
-	if (!$qualifier_lien or !is_array($qualifier_lien)) {
445
-		return [];
446
-	}
447
-
448
-	// pas avec l'action complete (incluant le role)
449
-	$qualif = [];
450
-	if (
451
-		(!isset($qualifier_lien[$lien]) or !$qualif = $qualifier_lien[$lien])
452
-		and count($defs) == 5
453
-	) {
454
-		// on tente avec l'action sans le role
455
-		array_pop($defs);
456
-		$lien = implode('-', $defs);
457
-		if (!isset($qualifier_lien[$lien]) or !$qualif = $qualifier_lien[$lien]) {
458
-			$qualif = [];
459
-		}
460
-	}
461
-
462
-	// $qualif de la forme array(role=>array(...),valeur=>array(...),....)
463
-	// on le reforme en array(array(role=>..,valeur=>..,..),array(role=>..,valeur=>..,..),...)
464
-	$qualifs = [];
465
-	while (is_countable($qualif) ? count($qualif) : 0) {
466
-		$q = [];
467
-		foreach ($qualif as $att => $values) {
468
-			if (is_array($values)) {
469
-				$q[$att] = array_shift($qualif[$att]);
470
-				if (!(is_countable($qualif[$att]) ? count($qualif[$att]) : 0)) {
471
-					unset($qualif[$att]);
472
-				}
473
-			} else {
474
-				$q[$att] = $values;
475
-				unset($qualif[$att]);
476
-			}
477
-		}
478
-		// pas de rôle vide
479
-		if (!$colonne_role or !isset($q[$colonne_role]) or $q[$colonne_role]) {
480
-			$qualifs[] = $q;
481
-		}
482
-	}
483
-
484
-	return $qualifs;
425
+    // un role est défini dans la liaison
426
+    $defs = explode('-', $lien);
427
+    [$objet1, , $objet2, , $role] = array_pad($defs, 5, null);
428
+    if ($objet_lien == $objet1) {
429
+        $colonne_role = roles_colonne($objet1, $objet2);
430
+    } else {
431
+        $colonne_role = roles_colonne($objet2, $objet1);
432
+    }
433
+
434
+    // cas ou le role est defini en 5e argument de l'action sur le lien (suppression, ajout rapide sans autre attribut)
435
+    if ($role) {
436
+        return [
437
+            // un seul lien avec ce role
438
+            [$colonne_role => $role]
439
+        ];
440
+    }
441
+
442
+    // retrouver les rôles postés pour cette liaison, s'il y en a.
443
+    $qualifier_lien = _request('qualifier_lien');
444
+    if (!$qualifier_lien or !is_array($qualifier_lien)) {
445
+        return [];
446
+    }
447
+
448
+    // pas avec l'action complete (incluant le role)
449
+    $qualif = [];
450
+    if (
451
+        (!isset($qualifier_lien[$lien]) or !$qualif = $qualifier_lien[$lien])
452
+        and count($defs) == 5
453
+    ) {
454
+        // on tente avec l'action sans le role
455
+        array_pop($defs);
456
+        $lien = implode('-', $defs);
457
+        if (!isset($qualifier_lien[$lien]) or !$qualif = $qualifier_lien[$lien]) {
458
+            $qualif = [];
459
+        }
460
+    }
461
+
462
+    // $qualif de la forme array(role=>array(...),valeur=>array(...),....)
463
+    // on le reforme en array(array(role=>..,valeur=>..,..),array(role=>..,valeur=>..,..),...)
464
+    $qualifs = [];
465
+    while (is_countable($qualif) ? count($qualif) : 0) {
466
+        $q = [];
467
+        foreach ($qualif as $att => $values) {
468
+            if (is_array($values)) {
469
+                $q[$att] = array_shift($qualif[$att]);
470
+                if (!(is_countable($qualif[$att]) ? count($qualif[$att]) : 0)) {
471
+                    unset($qualif[$att]);
472
+                }
473
+            } else {
474
+                $q[$att] = $values;
475
+                unset($qualif[$att]);
476
+            }
477
+        }
478
+        // pas de rôle vide
479
+        if (!$colonne_role or !isset($q[$colonne_role]) or $q[$colonne_role]) {
480
+            $qualifs[] = $q;
481
+        }
482
+    }
483
+
484
+    return $qualifs;
485 485
 }
486 486
 
487 487
 /**
@@ -500,14 +500,14 @@  discard block
 block discarded – undo
500 500
  **/
501 501
 function lien_ajouter_liaisons($objet_source, $ids, $objet_lien, $idl, $qualifs) {
502 502
 
503
-	// retrouver la colonne de roles s'il y en a a lier
504
-	if (is_array($qualifs) and count($qualifs)) {
505
-		foreach ($qualifs as $qualif) {
506
-			objet_associer([$objet_source => $ids], [$objet_lien => $idl], $qualif);
507
-		}
508
-	} else {
509
-		objet_associer([$objet_source => $ids], [$objet_lien => $idl]);
510
-	}
503
+    // retrouver la colonne de roles s'il y en a a lier
504
+    if (is_array($qualifs) and count($qualifs)) {
505
+        foreach ($qualifs as $qualif) {
506
+            objet_associer([$objet_source => $ids], [$objet_lien => $idl], $qualif);
507
+        }
508
+    } else {
509
+        objet_associer([$objet_source => $ids], [$objet_lien => $idl]);
510
+    }
511 511
 }
512 512
 
513 513
 
@@ -519,79 +519,79 @@  discard block
 block discarded – undo
519 519
  * @return array|string|null
520 520
  */
521 521
 function lien_gerer__oups(string $form, string $action, ?array $valeur = null) {
522
-	static $_oups_value;
523
-
524
-	switch ($action) {
525
-		case 'reset':
526
-			$res = (empty($_oups_value) ? false : true);
527
-			$_oups_value = null;
528
-			return $res;
529
-
530
-		case 'get':
531
-			return $_oups_value ?: null;
532
-
533
-		case 'set':
534
-			$_oups_value = $valeur;
535
-			return true;
536
-
537
-		case 'request':
538
-			$_oups_value = null;
539
-			if ($oups = _request('_oups')) {
540
-				include_spip('inc/filtres');
541
-				// on accepte uniquement une valeur signée
542
-				if ($oups = decoder_contexte_ajax($oups, $form)) {
543
-					if (!is_array($oups)
544
-						or empty($oups['id_auteur'])
545
-						or $oups['id_auteur'] !== $GLOBALS['visiteur_session']['id_auteur']
546
-						or empty($oups['time'])
547
-						or $oups['time'] < $_SERVER['REQUEST_TIME'] - 86400
548
-						or empty($oups['args'])
549
-						or $oups['args'] !== lien_gerer__oups_collecter_args($form, debug_backtrace(null, 5))
550
-						or empty($oups['oups_value'])) {
551
-						$oups = null;
552
-					}
553
-					else {
554
-						$oups = $oups['oups_value'];
555
-						// controler le contenu
556
-						foreach ($oups as $k => $oup) {
557
-							if (!is_array($oup)) {
558
-								unset($oups[$k]);
559
-							}
560
-							else {
561
-								foreach ($oup as $champ => $valeur) {
562
-									if (!is_scalar($champ)
563
-										or !is_scalar($valeur)
564
-										or preg_match(',\W,', $champ)
565
-									) {
566
-										unset($oups[$k][$champ]);
567
-									}
568
-								}
569
-								if (empty($oups[$k])) {
570
-									unset($oups[$k]);
571
-								}
572
-							}
573
-						}
574
-					}
575
-					$_oups_value = $oups;
576
-					return $_oups_value;
577
-				}
578
-			}
579
-			break;
580
-
581
-		case 'hash':
582
-			if (!$_oups_value) {
583
-				return '';
584
-			}
585
-
586
-			include_spip('inc/filtres');
587
-			$oups = [
588
-				'id_auteur' => $GLOBALS['visiteur_session']['id_auteur'] ?? 0,
589
-				'time' => strtotime(date('Y-m-d H:00:00')),
590
-				'args' => lien_gerer__oups_collecter_args($form, debug_backtrace(null, 5)),
591
-				'oups_value' => $_oups_value,
592
-			];
593
-			return encoder_contexte_ajax($oups, $form);
594
-	}
522
+    static $_oups_value;
523
+
524
+    switch ($action) {
525
+        case 'reset':
526
+            $res = (empty($_oups_value) ? false : true);
527
+            $_oups_value = null;
528
+            return $res;
529
+
530
+        case 'get':
531
+            return $_oups_value ?: null;
532
+
533
+        case 'set':
534
+            $_oups_value = $valeur;
535
+            return true;
536
+
537
+        case 'request':
538
+            $_oups_value = null;
539
+            if ($oups = _request('_oups')) {
540
+                include_spip('inc/filtres');
541
+                // on accepte uniquement une valeur signée
542
+                if ($oups = decoder_contexte_ajax($oups, $form)) {
543
+                    if (!is_array($oups)
544
+                        or empty($oups['id_auteur'])
545
+                        or $oups['id_auteur'] !== $GLOBALS['visiteur_session']['id_auteur']
546
+                        or empty($oups['time'])
547
+                        or $oups['time'] < $_SERVER['REQUEST_TIME'] - 86400
548
+                        or empty($oups['args'])
549
+                        or $oups['args'] !== lien_gerer__oups_collecter_args($form, debug_backtrace(null, 5))
550
+                        or empty($oups['oups_value'])) {
551
+                        $oups = null;
552
+                    }
553
+                    else {
554
+                        $oups = $oups['oups_value'];
555
+                        // controler le contenu
556
+                        foreach ($oups as $k => $oup) {
557
+                            if (!is_array($oup)) {
558
+                                unset($oups[$k]);
559
+                            }
560
+                            else {
561
+                                foreach ($oup as $champ => $valeur) {
562
+                                    if (!is_scalar($champ)
563
+                                        or !is_scalar($valeur)
564
+                                        or preg_match(',\W,', $champ)
565
+                                    ) {
566
+                                        unset($oups[$k][$champ]);
567
+                                    }
568
+                                }
569
+                                if (empty($oups[$k])) {
570
+                                    unset($oups[$k]);
571
+                                }
572
+                            }
573
+                        }
574
+                    }
575
+                    $_oups_value = $oups;
576
+                    return $_oups_value;
577
+                }
578
+            }
579
+            break;
580
+
581
+        case 'hash':
582
+            if (!$_oups_value) {
583
+                return '';
584
+            }
585
+
586
+            include_spip('inc/filtres');
587
+            $oups = [
588
+                'id_auteur' => $GLOBALS['visiteur_session']['id_auteur'] ?? 0,
589
+                'time' => strtotime(date('Y-m-d H:00:00')),
590
+                'args' => lien_gerer__oups_collecter_args($form, debug_backtrace(null, 5)),
591
+                'oups_value' => $_oups_value,
592
+            ];
593
+            return encoder_contexte_ajax($oups, $form);
594
+    }
595 595
 }
596 596
 
597 597
 /**
@@ -600,19 +600,19 @@  discard block
 block discarded – undo
600 600
  * @return false|float|int|mixed|Services_JSON_Error|string
601 601
  */
602 602
 function lien_gerer__oups_collecter_args($form, $trace) {
603
-	$args = '';
604
-	if (!empty($trace)) {
605
-		do {
606
-			$t = array_shift($trace);
607
-			$function = $t['function'] ?? '';
608
-			if (strpos($function, 'formulaires_'. $form) === 0) {
609
-				if (isset($t['args'])) {
610
-					$args = json_encode($t['args']);
611
-				}
612
-				break;
613
-			}
614
-		}
615
-		while (count($trace));
616
-	}
617
-	return $args;
603
+    $args = '';
604
+    if (!empty($trace)) {
605
+        do {
606
+            $t = array_shift($trace);
607
+            $function = $t['function'] ?? '';
608
+            if (strpos($function, 'formulaires_'. $form) === 0) {
609
+                if (isset($t['args'])) {
610
+                    $args = json_encode($t['args']);
611
+                }
612
+                break;
613
+            }
614
+        }
615
+        while (count($trace));
616
+    }
617
+    return $args;
618 618
 }
Please login to merge, or discard this patch.
ecrire/maj/2021.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -19,21 +19,21 @@  discard block
 block discarded – undo
19 19
  * @package SPIP\Core\SQL\Upgrade
20 20
  **/
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	return;
22
+    return;
23 23
 }
24 24
 
25 25
 $GLOBALS['maj'][2021_02_18_00] = [
26
-	['sql_alter', "TABLE spip_auteurs CHANGE imessage imessage VARCHAR(3) DEFAULT '' NOT NULL" ],
27
-	['sql_updateq', 'spip_auteurs', ['imessage' => 'oui'], "imessage != 'non' OR imessage IS NULL" ],
26
+    ['sql_alter', "TABLE spip_auteurs CHANGE imessage imessage VARCHAR(3) DEFAULT '' NOT NULL" ],
27
+    ['sql_updateq', 'spip_auteurs', ['imessage' => 'oui'], "imessage != 'non' OR imessage IS NULL" ],
28 28
 ];
29 29
 
30 30
 $GLOBALS['maj'][2022_02_23_02] = [
31
-	['sql_alter', "TABLE spip_auteurs ADD backup_cles mediumtext DEFAULT '' NOT NULL" ],
32
-	['sql_delete', 'spip_meta', "nom='secret_du_site'" ],
31
+    ['sql_alter', "TABLE spip_auteurs ADD backup_cles mediumtext DEFAULT '' NOT NULL" ],
32
+    ['sql_delete', 'spip_meta', "nom='secret_du_site'" ],
33 33
 ];
34 34
 
35 35
 $GLOBALS['maj'][2022_02_23_03] = [
36
-	['maj2021_supprimer_toutes_sessions_si_aucun_backup_cles'],
36
+    ['maj2021_supprimer_toutes_sessions_si_aucun_backup_cles'],
37 37
 ];
38 38
 
39 39
 /**
@@ -44,15 +44,15 @@  discard block
 block discarded – undo
44 44
  * - les autres auteurs vont tous regénérer un mot de passe plus sécure au premier login
45 45
  **/
46 46
 function maj2021_supprimer_toutes_sessions_si_aucun_backup_cles() {
47
-	if (!sql_countsel('spip_auteurs', "webmestre='oui' AND backup_cles!=''")) {
48
-		spip_log('supprimer sessions auteur', 'maj');
49
-		if ($dir = opendir(_DIR_SESSIONS)) {
50
-			while (($f = readdir($dir)) !== false) {
51
-				spip_unlink(_DIR_SESSIONS . $f);
52
-				if (time() >= _TIME_OUT) {
53
-					return;
54
-				}
55
-			}
56
-		}
57
-	}
47
+    if (!sql_countsel('spip_auteurs', "webmestre='oui' AND backup_cles!=''")) {
48
+        spip_log('supprimer sessions auteur', 'maj');
49
+        if ($dir = opendir(_DIR_SESSIONS)) {
50
+            while (($f = readdir($dir)) !== false) {
51
+                spip_unlink(_DIR_SESSIONS . $f);
52
+                if (time() >= _TIME_OUT) {
53
+                    return;
54
+                }
55
+            }
56
+        }
57
+    }
58 58
 }
Please login to merge, or discard this patch.
ecrire/action/api_transmettre.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -17,92 +17,92 @@
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
24 24
 function action_api_transmettre_dist($arg = null) {
25 25
 
26
-	// Obtenir l'argument 'id_auteur/cle/format/fond'
27
-	if (is_null($arg)) {
28
-		$arg = _request('arg');
29
-	}
30
-
31
-	$args = explode('/', $arg);
32
-
33
-	if (count($args) !== 4) {
34
-		action_api_transmettre_fail($arg);
35
-	}
36
-
37
-	[$id_auteur, $cle, $format, $fond] = $args;
38
-	$id_auteur = intval($id_auteur);
39
-
40
-	if (preg_match(',[^\w\\.-],', $format)) {
41
-		action_api_transmettre_fail("format $format ??");
42
-	}
43
-	if (preg_match(',[^\w\\.-],', $fond)) {
44
-		action_api_transmettre_fail("fond $fond ??");
45
-	}
46
-
47
-	// verifier la cle
48
-	//[(#ENV{id,0}|securiser_acces{#ENV{cle}, voirstats, #ENV{op}, #ENV{args}}|?{1,0})]
49
-	//[(#ENV{id,0}|securiser_acces{#ENV{cle}, voirstats, #ENV{op}, #ENV{args}}|?{1,0})]
50
-
51
-	$qs = $_SERVER['QUERY_STRING'];
52
-	// retirer action et arg de la qs
53
-	$contexte = [];
54
-	parse_str($qs, $contexte);
55
-	foreach ($contexte as $k => $v) {
56
-		if (in_array($k, ['action', 'arg', 'var_mode'])) {
57
-			unset($contexte[$k]);
58
-		}
59
-	}
60
-	$qs = http_build_query($contexte);
61
-	include_spip('inc/acces');
62
-	if (!securiser_acces_low_sec(intval($id_auteur), $cle, "transmettre/$format", $fond, $qs)) {
63
-		// si le autoriser low_sec n'est pas bon, on peut valider l'appel si l'auteur est identifie
64
-		include_spip('inc/autoriser');
65
-		$autoriser_type = preg_replace(',\W+,', '', "_{$format}{$fond}");
66
-		if (
67
-			!$id_auteur
68
-			or empty($GLOBALS['visiteur_session']['id_auteur'])
69
-			or $GLOBALS['visiteur_session']['id_auteur'] != $id_auteur
70
-			or !autoriser('transmettre', $autoriser_type, $id_auteur)
71
-		) {
72
-			action_api_transmettre_fail("auth QS $qs ??");
73
-		}
74
-	}
75
-
76
-	$contexte['id_auteur'] = $id_auteur;
77
-
78
-	$fond = "transmettre/$format/$fond";
79
-
80
-	if (!trouver_fond($fond)) {
81
-		$fond = "prive/$fond";
82
-	}
83
-
84
-	if (!trouver_fond($fond)) {
85
-		action_api_transmettre_fail("fond $fond ??");
86
-	}
87
-
88
-	$res = recuperer_fond($fond, $contexte, ['raw' => true]);
89
-	if (!empty($res['entetes'])) {
90
-		foreach ($res['entetes'] as $h => $v) {
91
-			header("$h: $v");
92
-		}
93
-	}
94
-
95
-	$res = ltrim($res['texte']);
96
-	if (empty($res)) {
97
-		spip_log("$arg $qs resultat vide", 'transmettre' . _LOG_INFO_IMPORTANTE);
98
-	}
99
-
100
-	echo $res;
101
-	exit();
26
+    // Obtenir l'argument 'id_auteur/cle/format/fond'
27
+    if (is_null($arg)) {
28
+        $arg = _request('arg');
29
+    }
30
+
31
+    $args = explode('/', $arg);
32
+
33
+    if (count($args) !== 4) {
34
+        action_api_transmettre_fail($arg);
35
+    }
36
+
37
+    [$id_auteur, $cle, $format, $fond] = $args;
38
+    $id_auteur = intval($id_auteur);
39
+
40
+    if (preg_match(',[^\w\\.-],', $format)) {
41
+        action_api_transmettre_fail("format $format ??");
42
+    }
43
+    if (preg_match(',[^\w\\.-],', $fond)) {
44
+        action_api_transmettre_fail("fond $fond ??");
45
+    }
46
+
47
+    // verifier la cle
48
+    //[(#ENV{id,0}|securiser_acces{#ENV{cle}, voirstats, #ENV{op}, #ENV{args}}|?{1,0})]
49
+    //[(#ENV{id,0}|securiser_acces{#ENV{cle}, voirstats, #ENV{op}, #ENV{args}}|?{1,0})]
50
+
51
+    $qs = $_SERVER['QUERY_STRING'];
52
+    // retirer action et arg de la qs
53
+    $contexte = [];
54
+    parse_str($qs, $contexte);
55
+    foreach ($contexte as $k => $v) {
56
+        if (in_array($k, ['action', 'arg', 'var_mode'])) {
57
+            unset($contexte[$k]);
58
+        }
59
+    }
60
+    $qs = http_build_query($contexte);
61
+    include_spip('inc/acces');
62
+    if (!securiser_acces_low_sec(intval($id_auteur), $cle, "transmettre/$format", $fond, $qs)) {
63
+        // si le autoriser low_sec n'est pas bon, on peut valider l'appel si l'auteur est identifie
64
+        include_spip('inc/autoriser');
65
+        $autoriser_type = preg_replace(',\W+,', '', "_{$format}{$fond}");
66
+        if (
67
+            !$id_auteur
68
+            or empty($GLOBALS['visiteur_session']['id_auteur'])
69
+            or $GLOBALS['visiteur_session']['id_auteur'] != $id_auteur
70
+            or !autoriser('transmettre', $autoriser_type, $id_auteur)
71
+        ) {
72
+            action_api_transmettre_fail("auth QS $qs ??");
73
+        }
74
+    }
75
+
76
+    $contexte['id_auteur'] = $id_auteur;
77
+
78
+    $fond = "transmettre/$format/$fond";
79
+
80
+    if (!trouver_fond($fond)) {
81
+        $fond = "prive/$fond";
82
+    }
83
+
84
+    if (!trouver_fond($fond)) {
85
+        action_api_transmettre_fail("fond $fond ??");
86
+    }
87
+
88
+    $res = recuperer_fond($fond, $contexte, ['raw' => true]);
89
+    if (!empty($res['entetes'])) {
90
+        foreach ($res['entetes'] as $h => $v) {
91
+            header("$h: $v");
92
+        }
93
+    }
94
+
95
+    $res = ltrim($res['texte']);
96
+    if (empty($res)) {
97
+        spip_log("$arg $qs resultat vide", 'transmettre' . _LOG_INFO_IMPORTANTE);
98
+    }
99
+
100
+    echo $res;
101
+    exit();
102 102
 }
103 103
 
104 104
 function action_api_transmettre_fail($arg) {
105
-	include_spip('inc/minipres');
106
-	echo minipres(_T('info_acces_interdit'), $arg);
107
-	exit;
105
+    include_spip('inc/minipres');
106
+    echo minipres(_T('info_acces_interdit'), $arg);
107
+    exit;
108 108
 }
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/AbstractCollecteur.php 1 patch
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -14,154 +14,154 @@
 block discarded – undo
14 14
 
15 15
 abstract class AbstractCollecteur {
16 16
 
17
-	protected static string $markPrefix = 'COLLECT';
18
-	protected string $markId;
19
-
20
-	/**
21
-	 * Collecteur générique des occurences d'une preg dans un texte avec leurs positions et longueur
22
-	 * @param string $texte
23
-	 *   texte à analyser pour la collecte
24
-	 * @param string $if_chars
25
-	 *   caractere(s) à tester avant de tenter la preg
26
-	 * @param string $start_with
27
-	 *   caractere(s) par lesquels commencent l'expression recherchée (permet de démarrer la preg à la prochaine occurence de cette chaine)
28
-	 * @param string $preg
29
-	 *   preg utilisée pour la collecte
30
-	 * @param int $max_items
31
-	 *   pour limiter le nombre de preg collectée (pour la detection simple de présence par exemple)
32
-	 * @return array
33
-	 */
34
-	protected static function collecteur(string $texte, string $if_chars, string $start_with, string $preg, int $max_items = 0): array {
35
-
36
-		$collection = [];
37
-		$pos = 0;
38
-		while (
39
-			(!$if_chars || strpos($texte, $if_chars, $pos) !== false)
40
-			and ($next = ($start_with ? strpos($texte, $start_with, $pos) : $pos)) !== false
41
-			and preg_match($preg, $texte, $r, PREG_OFFSET_CAPTURE, $next)) {
42
-
43
-			$found_pos = $r[0][1];
44
-			$found_length = strlen($r[0][0]);
45
-			$match = [
46
-				'raw' => $r[0][0],
47
-				'match' => array_column($r, 0),
48
-				'pos' => $found_pos,
49
-				'length' => $found_length
50
-			];
51
-
52
-			$collection[] = $match;
53
-
54
-			if ($max_items and count($collection) === $max_items) {
55
-				break;
56
-			}
57
-
58
-			$pos = $match['pos'] + $match['length'];
59
-		}
60
-
61
-		return $collection;
62
-	}
63
-
64
-	/**
65
-	 * Sanitizer une collection d'occurences
66
-	 *
67
-	 * @param array $collection
68
-	 * @param string $sanitize_callback
69
-	 * @return array
70
-	 */
71
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
72
-		foreach ($collection as &$c) {
73
-			$c['raw'] = $sanitize_callback($c['raw']);
74
-		}
75
-
76
-		return $collection;
77
-	}
78
-
79
-	/**
80
-	 * @param string $texte
81
-	 * @param array $options
82
-	 * @return array
83
-	 */
84
-	public function collecter(string $texte, array $options = []): array {
85
-		$collection = [];
86
-		return $collection;
87
-	}
88
-
89
-	public function detecter($texte): bool {
90
-		if (!empty($this->markId) and strpos($texte, $this->markId) !== false) {
91
-			return true;
92
-		}
93
-		return !empty($this->collecter($texte, ['detecter_presence' => true]));
94
-	}
95
-
96
-	/**
97
-	 * Echapper les occurences de la collecte par un texte neutre du point de vue HTML
98
-	 *
99
-	 * @see retablir()
100
-	 * @param string $texte
101
-	 * @param array $options
102
-	 *   string $sanitize_callback
103
-	 * @return array
104
-	 *   texte, marqueur utilise pour echapper les modeles
105
-	 */
106
-	public function echapper(string $texte, array $options = []): string {
107
-		if (!function_exists('creer_uniqid')) {
108
-			include_spip('inc/acces');
109
-		}
110
-
111
-		$collection = $this->collecter($texte, $options);
112
-		if (!empty($options['sanitize_callback']) and is_callable($options['sanitize_callback'])) {
113
-			$collection = $this->sanitizer_collection($collection, $options['sanitize_callback']);
114
-		}
115
-
116
-		if (!empty($collection)) {
117
-			if (empty($this->markId)) {
118
-				// generer un marqueur qui n'existe pas dans le texte
119
-				do {
120
-					$this->markId = substr(md5(uniqid(static::class, 1)), 0, 7);
121
-					$this->markId = "@|".static::$markPrefix . $this->markId . "|";
122
-				} while (strpos($texte, $this->markId) !== false);
123
-			}
124
-
125
-			$offset_pos = 0;
126
-			foreach ($collection as $c) {
127
-				$rempl = $this->markId . base64_encode($c['raw']) . '|@';
128
-				$texte = substr_replace($texte, $rempl, $c['pos'] + $offset_pos, $c['length']);
129
-				$offset_pos += strlen($rempl) - $c['length'];
130
-			}
131
-		}
132
-
133
-		return $texte;
134
-	}
135
-
136
-
137
-	/**
138
-	 * Retablir les occurences échappées précédemment
139
-	 *
140
-	 * @see echapper()
141
-	 * @param string $texte
142
-	 * @return string
143
-	 */
144
-	function retablir(string $texte): string {
145
-
146
-		if (!empty($this->markId)) {
147
-			$lm = strlen($this->markId);
148
-			$pos = 0;
149
-			while (
150
-				($p = strpos($texte, $this->markId, $pos)) !== false
151
-				and $end = strpos($texte, '|@', $p + $lm)
152
-			) {
153
-				$base64 = substr($texte, $p + $lm, $end - ($p + $lm));
154
-				if ($c = base64_decode($base64, true)) {
155
-					$texte = substr_replace($texte, $c, $p, $end + 2 - $p);
156
-					$pos = $p + strlen($c);
157
-				}
158
-				else {
159
-					$pos = $end;
160
-				}
161
-			}
162
-		}
163
-
164
-		return $texte;
165
-	}
17
+    protected static string $markPrefix = 'COLLECT';
18
+    protected string $markId;
19
+
20
+    /**
21
+     * Collecteur générique des occurences d'une preg dans un texte avec leurs positions et longueur
22
+     * @param string $texte
23
+     *   texte à analyser pour la collecte
24
+     * @param string $if_chars
25
+     *   caractere(s) à tester avant de tenter la preg
26
+     * @param string $start_with
27
+     *   caractere(s) par lesquels commencent l'expression recherchée (permet de démarrer la preg à la prochaine occurence de cette chaine)
28
+     * @param string $preg
29
+     *   preg utilisée pour la collecte
30
+     * @param int $max_items
31
+     *   pour limiter le nombre de preg collectée (pour la detection simple de présence par exemple)
32
+     * @return array
33
+     */
34
+    protected static function collecteur(string $texte, string $if_chars, string $start_with, string $preg, int $max_items = 0): array {
35
+
36
+        $collection = [];
37
+        $pos = 0;
38
+        while (
39
+            (!$if_chars || strpos($texte, $if_chars, $pos) !== false)
40
+            and ($next = ($start_with ? strpos($texte, $start_with, $pos) : $pos)) !== false
41
+            and preg_match($preg, $texte, $r, PREG_OFFSET_CAPTURE, $next)) {
42
+
43
+            $found_pos = $r[0][1];
44
+            $found_length = strlen($r[0][0]);
45
+            $match = [
46
+                'raw' => $r[0][0],
47
+                'match' => array_column($r, 0),
48
+                'pos' => $found_pos,
49
+                'length' => $found_length
50
+            ];
51
+
52
+            $collection[] = $match;
53
+
54
+            if ($max_items and count($collection) === $max_items) {
55
+                break;
56
+            }
57
+
58
+            $pos = $match['pos'] + $match['length'];
59
+        }
60
+
61
+        return $collection;
62
+    }
63
+
64
+    /**
65
+     * Sanitizer une collection d'occurences
66
+     *
67
+     * @param array $collection
68
+     * @param string $sanitize_callback
69
+     * @return array
70
+     */
71
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
72
+        foreach ($collection as &$c) {
73
+            $c['raw'] = $sanitize_callback($c['raw']);
74
+        }
75
+
76
+        return $collection;
77
+    }
78
+
79
+    /**
80
+     * @param string $texte
81
+     * @param array $options
82
+     * @return array
83
+     */
84
+    public function collecter(string $texte, array $options = []): array {
85
+        $collection = [];
86
+        return $collection;
87
+    }
88
+
89
+    public function detecter($texte): bool {
90
+        if (!empty($this->markId) and strpos($texte, $this->markId) !== false) {
91
+            return true;
92
+        }
93
+        return !empty($this->collecter($texte, ['detecter_presence' => true]));
94
+    }
95
+
96
+    /**
97
+     * Echapper les occurences de la collecte par un texte neutre du point de vue HTML
98
+     *
99
+     * @see retablir()
100
+     * @param string $texte
101
+     * @param array $options
102
+     *   string $sanitize_callback
103
+     * @return array
104
+     *   texte, marqueur utilise pour echapper les modeles
105
+     */
106
+    public function echapper(string $texte, array $options = []): string {
107
+        if (!function_exists('creer_uniqid')) {
108
+            include_spip('inc/acces');
109
+        }
110
+
111
+        $collection = $this->collecter($texte, $options);
112
+        if (!empty($options['sanitize_callback']) and is_callable($options['sanitize_callback'])) {
113
+            $collection = $this->sanitizer_collection($collection, $options['sanitize_callback']);
114
+        }
115
+
116
+        if (!empty($collection)) {
117
+            if (empty($this->markId)) {
118
+                // generer un marqueur qui n'existe pas dans le texte
119
+                do {
120
+                    $this->markId = substr(md5(uniqid(static::class, 1)), 0, 7);
121
+                    $this->markId = "@|".static::$markPrefix . $this->markId . "|";
122
+                } while (strpos($texte, $this->markId) !== false);
123
+            }
124
+
125
+            $offset_pos = 0;
126
+            foreach ($collection as $c) {
127
+                $rempl = $this->markId . base64_encode($c['raw']) . '|@';
128
+                $texte = substr_replace($texte, $rempl, $c['pos'] + $offset_pos, $c['length']);
129
+                $offset_pos += strlen($rempl) - $c['length'];
130
+            }
131
+        }
132
+
133
+        return $texte;
134
+    }
135
+
136
+
137
+    /**
138
+     * Retablir les occurences échappées précédemment
139
+     *
140
+     * @see echapper()
141
+     * @param string $texte
142
+     * @return string
143
+     */
144
+    function retablir(string $texte): string {
145
+
146
+        if (!empty($this->markId)) {
147
+            $lm = strlen($this->markId);
148
+            $pos = 0;
149
+            while (
150
+                ($p = strpos($texte, $this->markId, $pos)) !== false
151
+                and $end = strpos($texte, '|@', $p + $lm)
152
+            ) {
153
+                $base64 = substr($texte, $p + $lm, $end - ($p + $lm));
154
+                if ($c = base64_decode($base64, true)) {
155
+                    $texte = substr_replace($texte, $c, $p, $end + 2 - $p);
156
+                    $pos = $p + strlen($c);
157
+                }
158
+                else {
159
+                    $pos = $end;
160
+                }
161
+            }
162
+        }
163
+
164
+        return $texte;
165
+    }
166 166
 
167 167
 }
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Idiomes.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -23,115 +23,115 @@
 block discarded – undo
23 23
  */
24 24
 class Idiomes extends AbstractCollecteur {
25 25
 
26
-	protected static string $markPrefix = 'IDIOME';
27
-
28
-	/**
29
-	 * La preg pour découper et collecter les modèles
30
-	 * @var string
31
-	 */
32
-	protected string $preg_idiome;
33
-
34
-	public function __construct(?string $preg = null) {
35
-
36
-		$this->preg_idiome = ($preg ?: '@<:(?:([a-z0-9_]+):)?([a-z0-9_]+):>@isS');
37
-	}
38
-
39
-	/**
40
-	 * Sanitizer une collection d'occurences d'idiomes : on ne fait rien
41
-	 *
42
-	 * @param array $collection
43
-	 * @param string $sanitize_callback
44
-	 * @return array
45
-	 */
46
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
47
-
48
-		return $collection;
49
-	}
50
-
51
-
52
-	/**
53
-	 * @param string $texte
54
-	 * @param array $options
55
-	 *   bool $collecter_liens
56
-	 * @return array
57
-	 */
58
-	public function collecter(string $texte, array $options = []): array {
59
-		if (!$texte) {
60
-			return [];
61
-		}
62
-
63
-		// collecter les matchs de la preg
64
-		$idiomes = $this->collecteur($texte, '', '<:', $this->preg_idiome, empty($options['detecter_presence']) ? 0 : 1);
65
-
66
-		// si on veut seulement detecter la présence, on peut retourner tel quel
67
-		if (empty($options['detecter_presence'])) {
68
-
69
-			$pos_prev = 0;
70
-			foreach ($idiomes as $k => &$idiome) {
71
-
72
-				$idiome['module'] = $idiome['match'][1];
73
-				$idiome['chaine'] = $idiome['match'][2];
74
-			}
75
-		}
76
-
77
-		return $idiomes;
78
-	}
79
-
80
-	/**
81
-	 * Traiter les idiomes d'un texte
82
-	 *
83
-	 * @uses inc_traduire_dist()
84
-	 * @uses code_echappement()
85
-	 * @uses echappe_retour()
86
-	 *
87
-	 * @param string $texte
88
-	 * @param array $options
89
-	 *   ?string $lang
90
-	 *   ?bool echappe_span
91
-	 * @return string
92
-	 */
93
-	public function traiter(string $texte, array $options) {
94
-		static $traduire;
95
-		if ($texte) {
96
-
97
-			$idiomes = $this->collecter($texte);
98
-			if (!empty($idiomes)) {
99
-				$lang = $options['lang'] ?? $GLOBALS['spip_lang'];
100
-				$echappe_span = $options['echappe_span'] ?? false;
101
-
102
-				if (is_null($traduire)) {
103
-					$traduire = charger_fonction('traduire', 'inc');
104
-					include_spip('inc/lang');
105
-				}
106
-
107
-				$offset_pos = 0;
108
-				foreach ($idiomes as $idiome) {
109
-
110
-					$cle = ($idiome['module'] ? $idiome['module'] . ':' : '') . $idiome['chaine'];
111
-					$desc = $traduire($cle, $lang, true);
112
-					$l = $desc->langue;
113
-
114
-					// si pas de traduction, on laissera l'écriture de l'idiome entier dans le texte.
115
-					if (strlen($desc->texte ?? '')) {
116
-						$trad = code_echappement($desc->texte, 'idiome', false);
117
-						if ($l !== $lang) {
118
-							$trad = str_replace("'", '"', inserer_attribut($trad, 'lang', $l));
119
-						}
120
-						if (lang_dir($l) !== lang_dir($lang)) {
121
-							$trad = str_replace("'", '"', inserer_attribut($trad, 'dir', lang_dir($l)));
122
-						}
123
-						if (!$echappe_span) {
124
-							$trad = echappe_retour($trad, 'idiome');
125
-						}
126
-						$texte = substr_replace($texte, $trad, $idiome['pos'] + $offset_pos, $idiome['length']);
127
-						$offset_pos += strlen($trad) - $idiome['length'];
128
-					}
129
-
130
-				}
131
-			}
132
-		}
133
-
134
-		return $texte;
135
-	}
26
+    protected static string $markPrefix = 'IDIOME';
27
+
28
+    /**
29
+     * La preg pour découper et collecter les modèles
30
+     * @var string
31
+     */
32
+    protected string $preg_idiome;
33
+
34
+    public function __construct(?string $preg = null) {
35
+
36
+        $this->preg_idiome = ($preg ?: '@<:(?:([a-z0-9_]+):)?([a-z0-9_]+):>@isS');
37
+    }
38
+
39
+    /**
40
+     * Sanitizer une collection d'occurences d'idiomes : on ne fait rien
41
+     *
42
+     * @param array $collection
43
+     * @param string $sanitize_callback
44
+     * @return array
45
+     */
46
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
47
+
48
+        return $collection;
49
+    }
50
+
51
+
52
+    /**
53
+     * @param string $texte
54
+     * @param array $options
55
+     *   bool $collecter_liens
56
+     * @return array
57
+     */
58
+    public function collecter(string $texte, array $options = []): array {
59
+        if (!$texte) {
60
+            return [];
61
+        }
62
+
63
+        // collecter les matchs de la preg
64
+        $idiomes = $this->collecteur($texte, '', '<:', $this->preg_idiome, empty($options['detecter_presence']) ? 0 : 1);
65
+
66
+        // si on veut seulement detecter la présence, on peut retourner tel quel
67
+        if (empty($options['detecter_presence'])) {
68
+
69
+            $pos_prev = 0;
70
+            foreach ($idiomes as $k => &$idiome) {
71
+
72
+                $idiome['module'] = $idiome['match'][1];
73
+                $idiome['chaine'] = $idiome['match'][2];
74
+            }
75
+        }
76
+
77
+        return $idiomes;
78
+    }
79
+
80
+    /**
81
+     * Traiter les idiomes d'un texte
82
+     *
83
+     * @uses inc_traduire_dist()
84
+     * @uses code_echappement()
85
+     * @uses echappe_retour()
86
+     *
87
+     * @param string $texte
88
+     * @param array $options
89
+     *   ?string $lang
90
+     *   ?bool echappe_span
91
+     * @return string
92
+     */
93
+    public function traiter(string $texte, array $options) {
94
+        static $traduire;
95
+        if ($texte) {
96
+
97
+            $idiomes = $this->collecter($texte);
98
+            if (!empty($idiomes)) {
99
+                $lang = $options['lang'] ?? $GLOBALS['spip_lang'];
100
+                $echappe_span = $options['echappe_span'] ?? false;
101
+
102
+                if (is_null($traduire)) {
103
+                    $traduire = charger_fonction('traduire', 'inc');
104
+                    include_spip('inc/lang');
105
+                }
106
+
107
+                $offset_pos = 0;
108
+                foreach ($idiomes as $idiome) {
109
+
110
+                    $cle = ($idiome['module'] ? $idiome['module'] . ':' : '') . $idiome['chaine'];
111
+                    $desc = $traduire($cle, $lang, true);
112
+                    $l = $desc->langue;
113
+
114
+                    // si pas de traduction, on laissera l'écriture de l'idiome entier dans le texte.
115
+                    if (strlen($desc->texte ?? '')) {
116
+                        $trad = code_echappement($desc->texte, 'idiome', false);
117
+                        if ($l !== $lang) {
118
+                            $trad = str_replace("'", '"', inserer_attribut($trad, 'lang', $l));
119
+                        }
120
+                        if (lang_dir($l) !== lang_dir($lang)) {
121
+                            $trad = str_replace("'", '"', inserer_attribut($trad, 'dir', lang_dir($l)));
122
+                        }
123
+                        if (!$echappe_span) {
124
+                            $trad = echappe_retour($trad, 'idiome');
125
+                        }
126
+                        $texte = substr_replace($texte, $trad, $idiome['pos'] + $offset_pos, $idiome['length']);
127
+                        $offset_pos += strlen($trad) - $idiome['length'];
128
+                    }
129
+
130
+                }
131
+            }
132
+        }
133
+
134
+        return $texte;
135
+    }
136 136
 
137 137
 }
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Modeles.php 1 patch
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -22,202 +22,202 @@
 block discarded – undo
22 22
  */
23 23
 class Modeles extends AbstractCollecteur {
24 24
 
25
-	protected static string $markPrefix = 'MODELE';
26
-
27
-	/**
28
-	 * La preg pour découper et collecter les modèles
29
-	 * @var string
30
-	 */
31
-	protected string $preg_modele;
32
-
33
-	public function __construct(?string $preg = null) {
34
-
35
-		$this->preg_modele = ($preg ?:
36
-			'@<([a-z_-]{3,})' # <modele
37
-			. '\s*([0-9]*)\s*' # id
38
-			. '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
39
-			. '\s*/?' . '>@isS' # fin du modele >
40
-		);
41
-	}
42
-
43
-	/**
44
-	 * Sanitizer une collection d'occurences de modèle : on ne fait rien
45
-	 *
46
-	 * @param array $collection
47
-	 * @param string $sanitize_callback
48
-	 * @return array
49
-	 */
50
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
51
-
52
-		return $collection;
53
-	}
54
-
55
-	/**
56
-	 * @param string $texte
57
-	 * @param array $options
58
-	 *   bool $collecter_liens
59
-	 * @return array
60
-	 */
61
-	public function collecter(string $texte, array $options = []): array {
62
-		if (!$texte) {
63
-			return [];
64
-		}
65
-
66
-		// collecter les matchs de la preg
67
-		$modeles = $this->collecteur($texte, '', '<', $this->preg_modele);
68
-
69
-		$pos_prev = 0;
70
-		foreach ($modeles as $k => &$modele) {
71
-			$pos = $modele['pos'];
72
-			$modele['type'] = $modele['match'][1];
73
-			$modele['id'] = $modele['match'][2] ?? '';
74
-			$modele['params'] = $modele['match'][3] ?? '';
75
-
76
-			$longueur = $modele['length'];
77
-			$end = $pos + $longueur;
78
-
79
-			// il faut avoir un id ou des params commençant par un | sinon c'est une simple balise html
80
-			if (empty($modele['id']) and empty($modele['params'])) {
81
-				unset($modeles[$k]);
82
-				continue;
83
-			}
84
-
85
-			// si on veut seulement detecter la présence, on peut retourner tel quel
86
-			if (!empty($options['detecter_presence'])) {
87
-				break;
88
-			}
89
-
90
-			$modele['lien'] = false;
91
-			if (!empty($options['collecter_liens'])
92
-				and $pos_fermeture_lien = stripos($texte, '</a>', $end)
93
-				and !strlen(trim(substr($texte, $end, $pos_fermeture_lien - $end)))) {
94
-
95
-				$pos_lien_ouvrant = stripos($texte, '<a', $pos_prev);
96
-				if ($pos_lien_ouvrant !== false
97
-					and $pos_lien_ouvrant < $pos
98
-					and preg_match('/<a\s[^<>]*>\s*$/i', substr($texte, $pos_prev, $pos - $pos_prev), $r)
99
-				) {
100
-					$modele['lien'] = [
101
-						'href' => extraire_attribut($r[0], 'href'),
102
-						'class' => extraire_attribut($r[0], 'class'),
103
-						'mime' => extraire_attribut($r[0], 'type'),
104
-						'title' => extraire_attribut($r[0], 'title'),
105
-						'hreflang' => extraire_attribut($r[0], 'hreflang')
106
-					];
107
-					$n = strlen($r[0]);
108
-					$pos -= $n;
109
-					$longueur = $pos_fermeture_lien - $pos + 4;
110
-					$end = $pos + $longueur;
111
-				}
112
-			}
113
-
114
-
115
-			$modele['pos'] = $pos;
116
-			$modele['length'] = $longueur;
117
-			$pos_prev = $end;
118
-		}
119
-
120
-		return $modeles;
121
-	}
122
-
123
-	/**
124
-	 * Traiter les modeles d'un texte
125
-	 * @param string $texte
126
-	 * @param array $options
127
-	 *   bool|array $doublons
128
-	 *   string $echap
129
-	 *   ?Spip\Texte\CollecteurLiens $collecteurLiens
130
-	 *   ?array $env
131
-	 *   ?string $connect
132
-	 * @return string
133
-	 */
134
-	public function traiter(string $texte, array $options) {
135
-		if ($texte) {
136
-			$doublons = $options['doublons'] ?? false;
137
-			$echap = $options['echap'] ?? '';
138
-			$collecteurLiens = $options['collecteurLiens'] ?? null;
139
-			$env = $options['env'] ?? [];
140
-			$connect = $options['connect'] ?? '';
141
-
142
-			// preserver la compatibilite : true = recherche des documents
143
-			if ($doublons === true) {
144
-				$doublons = ['documents' => ['doc', 'emb', 'img']];
145
-			}
146
-
147
-			$modeles = $this->collecter($texte, ['collecter_liens' => true]);
148
-			if (!empty($modeles)) {
149
-				include_spip('public/assembler');
150
-				$wrap_embed_html = charger_fonction('wrap_embed_html', 'inc', true);
151
-
152
-				$offset_pos = 0;
153
-				foreach ($modeles as $m) {
154
-					// calculer le modele
155
-					# hack indexation
156
-					if ($doublons) {
157
-						$texte .= preg_replace(',[|][^|=]*,s', ' ', $m['params']);
158
-					} # version normale
159
-					else {
160
-						// si un tableau de liens a ete passe, reinjecter le contenu d'origine
161
-						// dans les parametres, plutot que les liens echappes
162
-						$params = $m['params'];
163
-						if (!is_null($collecteurLiens)) {
164
-							$params = $collecteurLiens->retablir($params);
165
-						}
166
-
167
-						$modele = inclure_modele($m['type'], $m['id'], $params, $m['lien'], $connect ?? '', $env);
168
-
169
-						// en cas d'echec,
170
-						// si l'objet demande a une url,
171
-						// creer un petit encadre vers elle
172
-						if ($modele === false) {
173
-							$modele = $m['raw'];
174
-
175
-							if (!is_null($collecteurLiens)) {
176
-								$modele = $collecteurLiens->retablir($modele);
177
-							}
178
-
179
-							$contexte = array_merge($env, ['id' => $m['id'], 'type' => $m['type'], 'modele' => $modele]);
180
-
181
-							if (!empty($m['lien'])) {
182
-								# un eventuel guillemet (") sera reechappe par #ENV
183
-								$contexte['lien'] = str_replace('&quot;', '"', $m['lien']['href']);
184
-								$contexte['lien_class'] = $m['lien']['class'];
185
-								$contexte['lien_mime'] = $m['lien']['mime'];
186
-								$contexte['lien_title'] = $m['lien']['title'];
187
-								$contexte['lien_hreflang'] = $m['lien']['hreflang'];
188
-							}
189
-
190
-							$modele = recuperer_fond('modeles/dist', $contexte, [], $connect ?? '');
191
-						}
192
-
193
-						// le remplacer dans le texte
194
-						if ($modele !== false) {
195
-							$modele = protege_js_modeles($modele);
196
-
197
-							if ($wrap_embed_html) {
198
-								$modele = $wrap_embed_html($m['raw'], $modele);
199
-							}
200
-
201
-							$rempl = code_echappement($modele, $echap);
202
-							$texte = substr_replace($texte, $rempl, $m['pos'] + $offset_pos, $m['length']);
203
-							$offset_pos += strlen($rempl) - $m['length'];
204
-						}
205
-					}
206
-
207
-					// hack pour tout l'espace prive
208
-					if ((test_espace_prive() or ($doublons)) and !empty($m['id'])) {
209
-						$type = strtolower($m['type']);
210
-						foreach ($doublons ?: ['documents' => ['doc', 'emb', 'img']] as $quoi => $type_modeles) {
211
-							if (in_array($type, $type_modeles)) {
212
-								$GLOBALS["doublons_{$quoi}_inclus"][] = $m['id'];
213
-							}
214
-						}
215
-					}
216
-				}
217
-			}
218
-		}
219
-
220
-		return $texte;
221
-	}
25
+    protected static string $markPrefix = 'MODELE';
26
+
27
+    /**
28
+     * La preg pour découper et collecter les modèles
29
+     * @var string
30
+     */
31
+    protected string $preg_modele;
32
+
33
+    public function __construct(?string $preg = null) {
34
+
35
+        $this->preg_modele = ($preg ?:
36
+            '@<([a-z_-]{3,})' # <modele
37
+            . '\s*([0-9]*)\s*' # id
38
+            . '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
39
+            . '\s*/?' . '>@isS' # fin du modele >
40
+        );
41
+    }
42
+
43
+    /**
44
+     * Sanitizer une collection d'occurences de modèle : on ne fait rien
45
+     *
46
+     * @param array $collection
47
+     * @param string $sanitize_callback
48
+     * @return array
49
+     */
50
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
51
+
52
+        return $collection;
53
+    }
54
+
55
+    /**
56
+     * @param string $texte
57
+     * @param array $options
58
+     *   bool $collecter_liens
59
+     * @return array
60
+     */
61
+    public function collecter(string $texte, array $options = []): array {
62
+        if (!$texte) {
63
+            return [];
64
+        }
65
+
66
+        // collecter les matchs de la preg
67
+        $modeles = $this->collecteur($texte, '', '<', $this->preg_modele);
68
+
69
+        $pos_prev = 0;
70
+        foreach ($modeles as $k => &$modele) {
71
+            $pos = $modele['pos'];
72
+            $modele['type'] = $modele['match'][1];
73
+            $modele['id'] = $modele['match'][2] ?? '';
74
+            $modele['params'] = $modele['match'][3] ?? '';
75
+
76
+            $longueur = $modele['length'];
77
+            $end = $pos + $longueur;
78
+
79
+            // il faut avoir un id ou des params commençant par un | sinon c'est une simple balise html
80
+            if (empty($modele['id']) and empty($modele['params'])) {
81
+                unset($modeles[$k]);
82
+                continue;
83
+            }
84
+
85
+            // si on veut seulement detecter la présence, on peut retourner tel quel
86
+            if (!empty($options['detecter_presence'])) {
87
+                break;
88
+            }
89
+
90
+            $modele['lien'] = false;
91
+            if (!empty($options['collecter_liens'])
92
+                and $pos_fermeture_lien = stripos($texte, '</a>', $end)
93
+                and !strlen(trim(substr($texte, $end, $pos_fermeture_lien - $end)))) {
94
+
95
+                $pos_lien_ouvrant = stripos($texte, '<a', $pos_prev);
96
+                if ($pos_lien_ouvrant !== false
97
+                    and $pos_lien_ouvrant < $pos
98
+                    and preg_match('/<a\s[^<>]*>\s*$/i', substr($texte, $pos_prev, $pos - $pos_prev), $r)
99
+                ) {
100
+                    $modele['lien'] = [
101
+                        'href' => extraire_attribut($r[0], 'href'),
102
+                        'class' => extraire_attribut($r[0], 'class'),
103
+                        'mime' => extraire_attribut($r[0], 'type'),
104
+                        'title' => extraire_attribut($r[0], 'title'),
105
+                        'hreflang' => extraire_attribut($r[0], 'hreflang')
106
+                    ];
107
+                    $n = strlen($r[0]);
108
+                    $pos -= $n;
109
+                    $longueur = $pos_fermeture_lien - $pos + 4;
110
+                    $end = $pos + $longueur;
111
+                }
112
+            }
113
+
114
+
115
+            $modele['pos'] = $pos;
116
+            $modele['length'] = $longueur;
117
+            $pos_prev = $end;
118
+        }
119
+
120
+        return $modeles;
121
+    }
122
+
123
+    /**
124
+     * Traiter les modeles d'un texte
125
+     * @param string $texte
126
+     * @param array $options
127
+     *   bool|array $doublons
128
+     *   string $echap
129
+     *   ?Spip\Texte\CollecteurLiens $collecteurLiens
130
+     *   ?array $env
131
+     *   ?string $connect
132
+     * @return string
133
+     */
134
+    public function traiter(string $texte, array $options) {
135
+        if ($texte) {
136
+            $doublons = $options['doublons'] ?? false;
137
+            $echap = $options['echap'] ?? '';
138
+            $collecteurLiens = $options['collecteurLiens'] ?? null;
139
+            $env = $options['env'] ?? [];
140
+            $connect = $options['connect'] ?? '';
141
+
142
+            // preserver la compatibilite : true = recherche des documents
143
+            if ($doublons === true) {
144
+                $doublons = ['documents' => ['doc', 'emb', 'img']];
145
+            }
146
+
147
+            $modeles = $this->collecter($texte, ['collecter_liens' => true]);
148
+            if (!empty($modeles)) {
149
+                include_spip('public/assembler');
150
+                $wrap_embed_html = charger_fonction('wrap_embed_html', 'inc', true);
151
+
152
+                $offset_pos = 0;
153
+                foreach ($modeles as $m) {
154
+                    // calculer le modele
155
+                    # hack indexation
156
+                    if ($doublons) {
157
+                        $texte .= preg_replace(',[|][^|=]*,s', ' ', $m['params']);
158
+                    } # version normale
159
+                    else {
160
+                        // si un tableau de liens a ete passe, reinjecter le contenu d'origine
161
+                        // dans les parametres, plutot que les liens echappes
162
+                        $params = $m['params'];
163
+                        if (!is_null($collecteurLiens)) {
164
+                            $params = $collecteurLiens->retablir($params);
165
+                        }
166
+
167
+                        $modele = inclure_modele($m['type'], $m['id'], $params, $m['lien'], $connect ?? '', $env);
168
+
169
+                        // en cas d'echec,
170
+                        // si l'objet demande a une url,
171
+                        // creer un petit encadre vers elle
172
+                        if ($modele === false) {
173
+                            $modele = $m['raw'];
174
+
175
+                            if (!is_null($collecteurLiens)) {
176
+                                $modele = $collecteurLiens->retablir($modele);
177
+                            }
178
+
179
+                            $contexte = array_merge($env, ['id' => $m['id'], 'type' => $m['type'], 'modele' => $modele]);
180
+
181
+                            if (!empty($m['lien'])) {
182
+                                # un eventuel guillemet (") sera reechappe par #ENV
183
+                                $contexte['lien'] = str_replace('&quot;', '"', $m['lien']['href']);
184
+                                $contexte['lien_class'] = $m['lien']['class'];
185
+                                $contexte['lien_mime'] = $m['lien']['mime'];
186
+                                $contexte['lien_title'] = $m['lien']['title'];
187
+                                $contexte['lien_hreflang'] = $m['lien']['hreflang'];
188
+                            }
189
+
190
+                            $modele = recuperer_fond('modeles/dist', $contexte, [], $connect ?? '');
191
+                        }
192
+
193
+                        // le remplacer dans le texte
194
+                        if ($modele !== false) {
195
+                            $modele = protege_js_modeles($modele);
196
+
197
+                            if ($wrap_embed_html) {
198
+                                $modele = $wrap_embed_html($m['raw'], $modele);
199
+                            }
200
+
201
+                            $rempl = code_echappement($modele, $echap);
202
+                            $texte = substr_replace($texte, $rempl, $m['pos'] + $offset_pos, $m['length']);
203
+                            $offset_pos += strlen($rempl) - $m['length'];
204
+                        }
205
+                    }
206
+
207
+                    // hack pour tout l'espace prive
208
+                    if ((test_espace_prive() or ($doublons)) and !empty($m['id'])) {
209
+                        $type = strtolower($m['type']);
210
+                        foreach ($doublons ?: ['documents' => ['doc', 'emb', 'img']] as $quoi => $type_modeles) {
211
+                            if (in_array($type, $type_modeles)) {
212
+                                $GLOBALS["doublons_{$quoi}_inclus"][] = $m['id'];
213
+                            }
214
+                        }
215
+                    }
216
+                }
217
+            }
218
+        }
219
+
220
+        return $texte;
221
+    }
222 222
 
223 223
 }
Please login to merge, or discard this patch.