Completed
Push — master ( 579209...5b53e6 )
by cam
01:04
created
prive/formulaires/editer_liens.php 3 patches
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.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 
106 106
 	// L'éditabilité :) est définie par un test permanent (par exemple "associermots") ET le 4ème argument
107 107
 	include_spip('inc/autoriser');
108
-	$editable = ($editable and autoriser('associer' . $table_source, $objet, $id_objet)
108
+	$editable = ($editable and autoriser('associer'.$table_source, $objet, $id_objet)
109 109
 		and autoriser('modifier', $objet, $id_objet));
110 110
 
111 111
 	if (
@@ -119,15 +119,15 @@  discard block
 block discarded – undo
119 119
 
120 120
 	// squelettes de vue et de d'association
121 121
 	// ils sont différents si des rôles sont définis.
122
-	$skel_vue = $table_source . '_lies';
123
-	$skel_ajout = $table_source . '_associer';
122
+	$skel_vue = $table_source.'_lies';
123
+	$skel_ajout = $table_source.'_associer';
124 124
 
125 125
 	// description des roles
126 126
 	include_spip('inc/roles');
127 127
 	if ($roles = roles_presents($objet_source, $objet)) {
128 128
 		// on demande de nouveaux squelettes en conséquence
129
-		$skel_vue = $table_source . '_roles_lies';
130
-		$skel_ajout = $table_source . '_roles_associer';
129
+		$skel_vue = $table_source.'_roles_lies';
130
+		$skel_ajout = $table_source.'_roles_associer';
131 131
 	}
132 132
 
133 133
 	$oups = '';
@@ -226,12 +226,12 @@  discard block
 block discarded – undo
226 226
 	include_spip('inc/autoriser');
227 227
 	if (autoriser('modifier', $objet, $id_objet)) {
228 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');
229
+		lien_gerer__oups('editer_liens', 'request');
230 230
 
231 231
 		// annuler les suppressions du coup d'avant ?
232 232
 		if (
233 233
 			_request('annuler_oups')
234
-			and $oups = lien_gerer__oups('editer_liens','get')
234
+			and $oups = lien_gerer__oups('editer_liens', 'get')
235 235
 		) {
236 236
 			if ($oups_objets = charger_fonction("editer_liens_oups_{$table_source}_{$objet}_{$objet_lien}", 'action', true)) {
237 237
 				$oups_objets($oups);
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 				}
248 248
 			}
249 249
 			# oups ne persiste que pour la derniere action, si suppression
250
-			lien_gerer__oups('editer_liens','reset');
250
+			lien_gerer__oups('editer_liens', 'reset');
251 251
 		}
252 252
 
253 253
 		$supprimer = _request('supprimer_lien');
@@ -310,9 +310,9 @@  discard block
 block discarded – undo
310 310
 				}
311 311
 			}
312 312
 			if (!empty($oups)) {
313
-				lien_gerer__oups('editer_liens','set', $oups);
313
+				lien_gerer__oups('editer_liens', 'set', $oups);
314 314
 			} else {
315
-				lien_gerer__oups('editer_liens','reset');
315
+				lien_gerer__oups('editer_liens', 'reset');
316 316
 			}
317 317
 		}
318 318
 
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 			# une suppression suivie d'un ajout dans le meme hit est un remplacement
343 343
 			# non annulable !
344 344
 			if ($ajout_ok) {
345
-				lien_gerer__oups('editer_liens','reset');
345
+				lien_gerer__oups('editer_liens', 'reset');
346 346
 			}
347 347
 		}
348 348
 
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 						objet_qualifier_liens([$objet2 => $idl], [$objet1 => $ids], $qualif);
360 360
 					}
361 361
 					set_request('id_lien_ajoute', $ids);
362
-					lien_gerer__oups('editer_liens','reset');
362
+					lien_gerer__oups('editer_liens', 'reset');
363 363
 				}
364 364
 			}
365 365
 		}
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 function lien_retrouver_qualif($objet_lien, $lien) {
425 425
 	// un role est défini dans la liaison
426 426
 	$defs = explode('-', $lien);
427
-	[$objet1, , $objet2, , $role] = array_pad($defs, 5, null);
427
+	[$objet1,, $objet2,, $role] = array_pad($defs, 5, null);
428 428
 	if ($objet_lien == $objet1) {
429 429
 		$colonne_role = roles_colonne($objet1, $objet2);
430 430
 	} else {
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
 		do {
606 606
 			$t = array_shift($trace);
607 607
 			$function = $t['function'] ?? '';
608
-			if (strpos($function, 'formulaires_'. $form) === 0) {
608
+			if (strpos($function, 'formulaires_'.$form) === 0) {
609 609
 				if (isset($t['args'])) {
610 610
 					$args = json_encode($t['args']);
611 611
 				}
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -549,15 +549,13 @@
 block discarded – undo
549 549
 						or $oups['args'] !== lien_gerer__oups_collecter_args($form, debug_backtrace(null, 5))
550 550
 						or empty($oups['oups_value'])) {
551 551
 						$oups = null;
552
-					}
553
-					else {
552
+					} else {
554 553
 						$oups = $oups['oups_value'];
555 554
 						// controler le contenu
556 555
 						foreach ($oups as $k => $oup) {
557 556
 							if (!is_array($oup)) {
558 557
 								unset($oups[$k]);
559
-							}
560
-							else {
558
+							} else {
561 559
 								foreach ($oup as $champ => $valeur) {
562 560
 									if (!is_scalar($champ)
563 561
 										or !is_scalar($valeur)
Please login to merge, or discard this patch.
ecrire/maj/2021.php 2 patches
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.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -23,13 +23,13 @@  discard block
 block discarded – undo
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] = [
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 		spip_log('supprimer sessions auteur', 'maj');
49 49
 		if ($dir = opendir(_DIR_SESSIONS)) {
50 50
 			while (($f = readdir($dir)) !== false) {
51
-				spip_unlink(_DIR_SESSIONS . $f);
51
+				spip_unlink(_DIR_SESSIONS.$f);
52 52
 				if (time() >= _TIME_OUT) {
53 53
 					return;
54 54
 				}
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/AbstractCollecteur.php 3 patches
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.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -118,13 +118,13 @@
 block discarded – undo
118 118
 				// generer un marqueur qui n'existe pas dans le texte
119 119
 				do {
120 120
 					$this->markId = substr(md5(uniqid(static::class, 1)), 0, 7);
121
-					$this->markId = "@|".static::$markPrefix . $this->markId . "|";
121
+					$this->markId = "@|".static::$markPrefix.$this->markId."|";
122 122
 				} while (strpos($texte, $this->markId) !== false);
123 123
 			}
124 124
 
125 125
 			$offset_pos = 0;
126 126
 			foreach ($collection as $c) {
127
-				$rempl = $this->markId . base64_encode($c['raw']) . '|@';
127
+				$rempl = $this->markId.base64_encode($c['raw']).'|@';
128 128
 				$texte = substr_replace($texte, $rempl, $c['pos'] + $offset_pos, $c['length']);
129 129
 				$offset_pos += strlen($rempl) - $c['length'];
130 130
 			}
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -154,8 +154,7 @@
 block discarded – undo
154 154
 				if ($c = base64_decode($base64, true)) {
155 155
 					$texte = substr_replace($texte, $c, $p, $end + 2 - $p);
156 156
 					$pos = $p + strlen($c);
157
-				}
158
-				else {
157
+				} else {
159 158
 					$pos = $end;
160 159
 				}
161 160
 			}
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Idiomes.php 2 patches
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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -107,7 +107,7 @@
 block discarded – undo
107 107
 				$offset_pos = 0;
108 108
 				foreach ($idiomes as $idiome) {
109 109
 
110
-					$cle = ($idiome['module'] ? $idiome['module'] . ':' : '') . $idiome['chaine'];
110
+					$cle = ($idiome['module'] ? $idiome['module'].':' : '').$idiome['chaine'];
111 111
 					$desc = $traduire($cle, $lang, true);
112 112
 					$l = $desc->langue;
113 113
 
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Modeles.php 2 patches
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.
Spacing   +2 added lines, -3 removed lines patch added patch discarded remove patch
@@ -32,11 +32,10 @@
 block discarded – undo
32 32
 
33 33
 	public function __construct(?string $preg = null) {
34 34
 
35
-		$this->preg_modele = ($preg ?:
36
-			'@<([a-z_-]{3,})' # <modele
35
+		$this->preg_modele = ($preg ?: '@<([a-z_-]{3,})' # <modele
37 36
 			. '\s*([0-9]*)\s*' # id
38 37
 			. '([|](?:<[^<>]*>|[^>])*?)?' # |arguments (y compris des tags <...>)
39
-			. '\s*/?' . '>@isS' # fin du modele >
38
+			. '\s*/?'.'>@isS' # fin du modele >
40 39
 		);
41 40
 	}
42 41
 
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Liens.php 1 patch
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -17,103 +17,103 @@
 block discarded – undo
17 17
  */
18 18
 class Liens extends AbstractCollecteur {
19 19
 
20
-	protected static string $markPrefix = 'LIEN';
21
-
22
-	/**
23
-	 * La preg pour découper et collecter les modèles
24
-	 * @var string
25
-	 */
26
-	protected string $preg_lien;
27
-
28
-	public function __construct(?string $preg = null) {
29
-
30
-		// Regexp des raccourcis, aussi utilisee pour la fusion de sauvegarde Spip
31
-		// Laisser passer des paires de crochets pour la balise multi
32
-		// mais refuser plus d'imbrications ou de mauvaises imbrications
33
-		// sinon les crochets ne peuvent plus servir qu'a ce type de raccourci
34
-		$this->preg_lien = ($preg ?: '/\[([^][]*?([[][^]>-]*[]][^][]*)*)->(>?)([^]]*)\]/msS');
35
-	}
36
-
37
-
38
-	/**
39
-	 * Sanitizer une collection d'occurences de liens : il faut sanitizer le href et le texte uniquement
40
-	 *
41
-	 * @param array $collection
42
-	 * @param string $sanitize_callback
43
-	 * @return array
44
-	 */
45
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
46
-		foreach ($collection as &$lien) {
47
-			$t = $sanitize_callback($lien['texte']);
48
-			if ($t !== $lien['texte']) {
49
-				$lien['raw'] = str_replace($lien['texte'], $t, $lien['raw']);
50
-				$lien['texte'] = $t;
51
-			}
52
-			$href = $sanitize_callback($lien['href']);
53
-			if ($href !== $lien['href']) {
54
-				$lien['raw'] = str_replace($lien['href'], $href, $lien['raw']);
55
-				$lien['href'] = $href;
56
-			}
57
-		}
58
-
59
-		return $collection;
60
-	}
61
-
62
-	/**
63
-	 * @param string $texte
64
-	 * @param array $options
65
-	 *   bool $collecter_liens
66
-	 * @return array
67
-	 */
68
-	public function collecter(string $texte, array $options = []): array {
69
-		if (!$texte) {
70
-			return [];
71
-		}
72
-
73
-		$liens = [];
74
-		if (strpos($texte, '->') !== false) {
75
-
76
-			$desechappe_crochets = false;
77
-			// si il y a un crochet ouvrant échappé ou un crochet fermant échappé, les substituer pour les ignorer
78
-			if (strpos($texte, '\[') !== false or strpos($texte, '\]') !== false) {
79
-				$texte = str_replace(['\[', '\]'], ["\x1\x5", "\x1\x6"], $texte);
80
-				$desechappe_crochets = true;
81
-			}
82
-
83
-			// collecter les matchs de la preg
84
-			$liens = $this->collecteur($texte, '->', '[', $this->preg_lien, empty($options['detecter_presence']) ? 0 : 1);
85
-
86
-			// si on veut seulement detecter la présence, on peut retourner tel quel
87
-			if (empty($options['detecter_presence'])) {
88
-
89
-				foreach ($liens as $k => &$lien) {
90
-
91
-					$lien['href'] = end($lien['match']);
92
-					$lien['texte'] = $lien['match'][1];
93
-					$lien['ouvrant'] = $lien['match'][3] ?? '';
94
-
95
-					// la mise en lien automatique est passee par la a tort !
96
-					// corrigeons pour eviter d'avoir un <a...> dans un href...
97
-					if (strncmp($lien['href'], '<a', 2) == 0) {
98
-						$href = extraire_attribut($lien['href'], 'href');
99
-						// remplacons dans la source qui peut etre reinjectee dans les arguments
100
-						// d'un modele
101
-						$lien['raw'] = str_replace($lien['href'], $href, $lien['raw']);
102
-						// et prenons le href comme la vraie url a linker
103
-						$lien['href'] = $href;
104
-					}
105
-
106
-					if ($desechappe_crochets and strpos($lien['raw'], "\x1") !== false) {
107
-						$lien['raw'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['raw']);
108
-						$lien['texte'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['texte']);
109
-						$lien['href'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['href']);
110
-					}
111
-
112
-				}
113
-			}
114
-		}
115
-
116
-		return $liens;
117
-	}
20
+    protected static string $markPrefix = 'LIEN';
21
+
22
+    /**
23
+     * La preg pour découper et collecter les modèles
24
+     * @var string
25
+     */
26
+    protected string $preg_lien;
27
+
28
+    public function __construct(?string $preg = null) {
29
+
30
+        // Regexp des raccourcis, aussi utilisee pour la fusion de sauvegarde Spip
31
+        // Laisser passer des paires de crochets pour la balise multi
32
+        // mais refuser plus d'imbrications ou de mauvaises imbrications
33
+        // sinon les crochets ne peuvent plus servir qu'a ce type de raccourci
34
+        $this->preg_lien = ($preg ?: '/\[([^][]*?([[][^]>-]*[]][^][]*)*)->(>?)([^]]*)\]/msS');
35
+    }
36
+
37
+
38
+    /**
39
+     * Sanitizer une collection d'occurences de liens : il faut sanitizer le href et le texte uniquement
40
+     *
41
+     * @param array $collection
42
+     * @param string $sanitize_callback
43
+     * @return array
44
+     */
45
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
46
+        foreach ($collection as &$lien) {
47
+            $t = $sanitize_callback($lien['texte']);
48
+            if ($t !== $lien['texte']) {
49
+                $lien['raw'] = str_replace($lien['texte'], $t, $lien['raw']);
50
+                $lien['texte'] = $t;
51
+            }
52
+            $href = $sanitize_callback($lien['href']);
53
+            if ($href !== $lien['href']) {
54
+                $lien['raw'] = str_replace($lien['href'], $href, $lien['raw']);
55
+                $lien['href'] = $href;
56
+            }
57
+        }
58
+
59
+        return $collection;
60
+    }
61
+
62
+    /**
63
+     * @param string $texte
64
+     * @param array $options
65
+     *   bool $collecter_liens
66
+     * @return array
67
+     */
68
+    public function collecter(string $texte, array $options = []): array {
69
+        if (!$texte) {
70
+            return [];
71
+        }
72
+
73
+        $liens = [];
74
+        if (strpos($texte, '->') !== false) {
75
+
76
+            $desechappe_crochets = false;
77
+            // si il y a un crochet ouvrant échappé ou un crochet fermant échappé, les substituer pour les ignorer
78
+            if (strpos($texte, '\[') !== false or strpos($texte, '\]') !== false) {
79
+                $texte = str_replace(['\[', '\]'], ["\x1\x5", "\x1\x6"], $texte);
80
+                $desechappe_crochets = true;
81
+            }
82
+
83
+            // collecter les matchs de la preg
84
+            $liens = $this->collecteur($texte, '->', '[', $this->preg_lien, empty($options['detecter_presence']) ? 0 : 1);
85
+
86
+            // si on veut seulement detecter la présence, on peut retourner tel quel
87
+            if (empty($options['detecter_presence'])) {
88
+
89
+                foreach ($liens as $k => &$lien) {
90
+
91
+                    $lien['href'] = end($lien['match']);
92
+                    $lien['texte'] = $lien['match'][1];
93
+                    $lien['ouvrant'] = $lien['match'][3] ?? '';
94
+
95
+                    // la mise en lien automatique est passee par la a tort !
96
+                    // corrigeons pour eviter d'avoir un <a...> dans un href...
97
+                    if (strncmp($lien['href'], '<a', 2) == 0) {
98
+                        $href = extraire_attribut($lien['href'], 'href');
99
+                        // remplacons dans la source qui peut etre reinjectee dans les arguments
100
+                        // d'un modele
101
+                        $lien['raw'] = str_replace($lien['href'], $href, $lien['raw']);
102
+                        // et prenons le href comme la vraie url a linker
103
+                        $lien['href'] = $href;
104
+                    }
105
+
106
+                    if ($desechappe_crochets and strpos($lien['raw'], "\x1") !== false) {
107
+                        $lien['raw'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['raw']);
108
+                        $lien['texte'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['texte']);
109
+                        $lien['href'] = str_replace(["\x1\x5", "\x1\x6"], ['[', ']'], $lien['href']);
110
+                    }
111
+
112
+                }
113
+            }
114
+        }
115
+
116
+        return $liens;
117
+    }
118 118
 
119 119
 }
Please login to merge, or discard this patch.
ecrire/src/Texte/Collecteur/Multis.php 3 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -209,9 +209,9 @@
 block discarded – undo
209 209
 								// il ne faut pas echapper en div si propre produit un seul paragraphe
210 210
 								include_spip('inc/texte');
211 211
 								$trad_propre = preg_replace(',(^<p[^>]*>|</p>$),Uims', '', propre($trad));
212
-								$mode = preg_match(',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS', $trad_propre) ? 'div' : 'span';
212
+								$mode = preg_match(',</?('._BALISES_BLOCS.')[>[:space:]],iS', $trad_propre) ? 'div' : 'span';
213 213
 								if ($mode === 'div') {
214
-									$trad = rtrim($trad) . "\n\n";
214
+									$trad = rtrim($trad)."\n\n";
215 215
 								}
216 216
 								$trad = code_echappement($trad, 'multi', false, $mode);
217 217
 								$trad = str_replace("'", '"', inserer_attribut($trad, 'lang', $l));
Please login to merge, or discard this patch.
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -29,210 +29,210 @@
 block discarded – undo
29 29
  */
30 30
 class Multis extends AbstractCollecteur {
31 31
 
32
-	protected static string $markPrefix = 'MULTI';
33
-
34
-	/**
35
-	 * La preg pour découper et collecter les modèles
36
-	 * @var string
37
-	 */
38
-	protected string $preg_multi;
39
-
40
-	public function __construct(?string $preg = null) {
41
-
42
-		$this->preg_multi = ($preg ?: '@<multi>(.*?)</multi>@sS');
43
-	}
44
-
45
-	/**
46
-	 * Sanitizer une collection d'occurences de multi : on sanitize chaque texte de langue séparemment
47
-	 *
48
-	 * @param array $collection
49
-	 * @param string $sanitize_callback
50
-	 * @return array
51
-	 */
52
-	protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
53
-
54
-		foreach ($collection as &$multi) {
55
-			$changed = false;
56
-			foreach ($multi['trads'] as $lang => $trad) {
57
-				$t = $sanitize_callback($trad);
58
-				if ($t !== $trad) {
59
-					$changed = true;
60
-					$multi['trads'][$lang] = $t;
61
-				}
62
-			}
63
-			if ($changed) {
64
-				$texte = $this->agglomerer_trads($multi['trads']);
65
-				$multi['raw'] = str_replace($multi['texte'], $texte, $multi['raw']);
66
-				$multi['texte'] = $texte;
67
-			}
68
-		}
69
-		return $collection;
70
-	}
71
-
72
-
73
-	/**
74
-	 * Convertit le contenu d'une balise `<multi>` en un tableau
75
-	 *
76
-	 * Exemple de blocs.
77
-	 * - `texte par défaut [fr] en français [en] en anglais`
78
-	 * - `[fr] en français [en] en anglais`
79
-	 *
80
-	 * @param string $bloc
81
-	 *     Le contenu intérieur d'un bloc multi
82
-	 * @return array [code de langue => texte]
83
-	 *     Peut retourner un code de langue vide, lorsqu'un texte par défaut est indiqué.
84
-	 **/
85
-	protected function extraire_trads($bloc) {
86
-		$trads = [];
87
-
88
-		if (strlen($bloc)) {
89
-			$langs = $this->collecteur($bloc, ']', '[', '@[\[]([a-z]{2,3}(_[a-z]{2,3})?(_[a-z]{2,3})?)[\]]@siS');
90
-			$lang = '';
91
-			$pos_prev = 0;
92
-			foreach ($langs as $l) {
93
-				$pos = $l['pos'];
94
-				if ($lang or $pos > $pos_prev) {
95
-					$trads[$lang] = substr($bloc, $pos_prev, $pos - $pos_prev);
96
-				}
97
-				$lang = $l['match'][1];
98
-				$pos_prev = $pos + $l['length'];
99
-			}
100
-			$trads[$lang] = substr($bloc, $pos_prev);
101
-		}
102
-
103
-		return $trads;
104
-	}
105
-
106
-	/**
107
-	 * Recoller ensemble les trads pour reconstituer le texte dans la balise <multi>...</multi>
108
-	 * @param $trads
109
-	 * @return string
110
-	 */
111
-	protected function agglomerer_trads($trads) {
112
-		$texte = '';
113
-		foreach ($trads as $lang => $trad) {
114
-			if ($texte or $lang) {
115
-				$texte .= "[$lang]";
116
-			}
117
-			$texte .= $trad;
118
-		}
119
-		return $texte;
120
-	}
121
-
122
-	/**
123
-	 * @param string $texte
124
-	 * @param array $options
125
-	 *   bool $collecter_liens
126
-	 * @return array
127
-	 */
128
-	public function collecter(string $texte, array $options = []): array {
129
-		if (!$texte) {
130
-			return [];
131
-		}
132
-
133
-		// collecter les matchs de la preg
134
-		$multis = $this->collecteur($texte, '', '<multi', $this->preg_multi, empty($options['detecter_presence']) ? 0 : 1);
135
-
136
-		// si on veut seulement detecter la présence, on peut retourner tel quel
137
-		if (empty($options['detecter_presence'])) {
138
-			foreach ($multis as $k => &$multi) {
139
-				$multi['texte'] = $multi['match'][1];
140
-				// extraire les trads du texte
141
-				$multi['trads'] = $this->extraire_trads($multi['texte']);
142
-			}
143
-		}
144
-
145
-		return $multis;
146
-	}
147
-
148
-	/**
149
-	 * Traiter les multis d'un texte
150
-	 *
151
-	 * @uses approcher_langue()
152
-	 * @uses lang_typo()
153
-	 * @uses code_echappement()
154
-	 * @uses echappe_retour()
155
-	 *
156
-	 * @param string $texte
157
-	 * @param array $options
158
-	 *   ?string $lang
159
-	 *   ?string $lang_defaut
160
-	 *   ?bool echappe_span
161
-	 *   ?bool appliquer_typo
162
-	 * @return string
163
-	 */
164
-	public function traiter(string $texte, array $options) {
165
-		if ($texte) {
166
-
167
-			$multis = $this->collecter($texte);
168
-			if (!empty($multis)) {
169
-				$lang = $options['lang'] ?? $GLOBALS['spip_lang'];
170
-				$lang_defaut = $options['lang_defaut'] ?? _LANGUE_PAR_DEFAUT;
171
-				$echappe_span = $options['echappe_span'] ?? false;
172
-				$appliquer_typo = $options['appliquer_typo'] ?? true;
173
-
174
-				if (!function_exists('approcher_langue')) {
175
-					include_spip('inc/lang');
176
-				}
177
-				if (!function_exists('code_echappement')) {
178
-					include_spip('inc/texte_mini');
179
-				}
180
-
181
-				$offset_pos = 0;
182
-				foreach ($multis as $m) {
183
-
184
-					// chercher la version de la langue courante
185
-					$trads = $m['trads'];
186
-					if (empty($trads)) {
187
-						$trad = '';
188
-					}
189
-					elseif ($l = approcher_langue($trads, $lang)) {
190
-						$trad = $trads[$l];
191
-					} else {
192
-						if ($lang_defaut == 'aucune') {
193
-							$trad = '';
194
-						} else {
195
-							// langue absente, prendre le fr ou une langue précisée (meme comportement que inc/traduire.php)
196
-							// ou la premiere dispo
197
-							if (!$l = approcher_langue($trads, $options['lang_defaut'])) {
198
-								$l = array_keys($trads);
199
-								$l = reset($l);
200
-							}
201
-
202
-							// mais typographier le texte selon les regles de celle-ci
203
-							// Attention aux blocs multi sur plusieurs lignes
204
-							if ($appliquer_typo) {
205
-								$trad = $trads[$l];
206
-								$typographie = charger_fonction(lang_typo($l), 'typographie');
207
-								$trad = $typographie($trad);
208
-
209
-								// Tester si on echappe en span ou en div
210
-								// il ne faut pas echapper en div si propre produit un seul paragraphe
211
-								include_spip('inc/texte');
212
-								$trad_propre = preg_replace(',(^<p[^>]*>|</p>$),Uims', '', propre($trad));
213
-								$mode = preg_match(',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS', $trad_propre) ? 'div' : 'span';
214
-								if ($mode === 'div') {
215
-									$trad = rtrim($trad) . "\n\n";
216
-								}
217
-								$trad = code_echappement($trad, 'multi', false, $mode);
218
-								$trad = str_replace("'", '"', inserer_attribut($trad, 'lang', $l));
219
-								if (lang_dir($l) !== lang_dir($lang)) {
220
-									$trad = str_replace("'", '"', inserer_attribut($trad, 'dir', lang_dir($l)));
221
-								}
222
-								if (!$echappe_span) {
223
-									$trad = echappe_retour($trad, 'multi');
224
-								}
225
-							}
226
-						}
227
-					}
228
-
229
-					$texte = substr_replace($texte, $trad, $m['pos'] + $offset_pos, $m['length']);
230
-					$offset_pos += strlen($trad) - $m['length'];
231
-				}
232
-			}
233
-		}
234
-
235
-		return $texte;
236
-	}
32
+    protected static string $markPrefix = 'MULTI';
33
+
34
+    /**
35
+     * La preg pour découper et collecter les modèles
36
+     * @var string
37
+     */
38
+    protected string $preg_multi;
39
+
40
+    public function __construct(?string $preg = null) {
41
+
42
+        $this->preg_multi = ($preg ?: '@<multi>(.*?)</multi>@sS');
43
+    }
44
+
45
+    /**
46
+     * Sanitizer une collection d'occurences de multi : on sanitize chaque texte de langue séparemment
47
+     *
48
+     * @param array $collection
49
+     * @param string $sanitize_callback
50
+     * @return array
51
+     */
52
+    protected function sanitizer_collection(array $collection, string $sanitize_callback): array {
53
+
54
+        foreach ($collection as &$multi) {
55
+            $changed = false;
56
+            foreach ($multi['trads'] as $lang => $trad) {
57
+                $t = $sanitize_callback($trad);
58
+                if ($t !== $trad) {
59
+                    $changed = true;
60
+                    $multi['trads'][$lang] = $t;
61
+                }
62
+            }
63
+            if ($changed) {
64
+                $texte = $this->agglomerer_trads($multi['trads']);
65
+                $multi['raw'] = str_replace($multi['texte'], $texte, $multi['raw']);
66
+                $multi['texte'] = $texte;
67
+            }
68
+        }
69
+        return $collection;
70
+    }
71
+
72
+
73
+    /**
74
+     * Convertit le contenu d'une balise `<multi>` en un tableau
75
+     *
76
+     * Exemple de blocs.
77
+     * - `texte par défaut [fr] en français [en] en anglais`
78
+     * - `[fr] en français [en] en anglais`
79
+     *
80
+     * @param string $bloc
81
+     *     Le contenu intérieur d'un bloc multi
82
+     * @return array [code de langue => texte]
83
+     *     Peut retourner un code de langue vide, lorsqu'un texte par défaut est indiqué.
84
+     **/
85
+    protected function extraire_trads($bloc) {
86
+        $trads = [];
87
+
88
+        if (strlen($bloc)) {
89
+            $langs = $this->collecteur($bloc, ']', '[', '@[\[]([a-z]{2,3}(_[a-z]{2,3})?(_[a-z]{2,3})?)[\]]@siS');
90
+            $lang = '';
91
+            $pos_prev = 0;
92
+            foreach ($langs as $l) {
93
+                $pos = $l['pos'];
94
+                if ($lang or $pos > $pos_prev) {
95
+                    $trads[$lang] = substr($bloc, $pos_prev, $pos - $pos_prev);
96
+                }
97
+                $lang = $l['match'][1];
98
+                $pos_prev = $pos + $l['length'];
99
+            }
100
+            $trads[$lang] = substr($bloc, $pos_prev);
101
+        }
102
+
103
+        return $trads;
104
+    }
105
+
106
+    /**
107
+     * Recoller ensemble les trads pour reconstituer le texte dans la balise <multi>...</multi>
108
+     * @param $trads
109
+     * @return string
110
+     */
111
+    protected function agglomerer_trads($trads) {
112
+        $texte = '';
113
+        foreach ($trads as $lang => $trad) {
114
+            if ($texte or $lang) {
115
+                $texte .= "[$lang]";
116
+            }
117
+            $texte .= $trad;
118
+        }
119
+        return $texte;
120
+    }
121
+
122
+    /**
123
+     * @param string $texte
124
+     * @param array $options
125
+     *   bool $collecter_liens
126
+     * @return array
127
+     */
128
+    public function collecter(string $texte, array $options = []): array {
129
+        if (!$texte) {
130
+            return [];
131
+        }
132
+
133
+        // collecter les matchs de la preg
134
+        $multis = $this->collecteur($texte, '', '<multi', $this->preg_multi, empty($options['detecter_presence']) ? 0 : 1);
135
+
136
+        // si on veut seulement detecter la présence, on peut retourner tel quel
137
+        if (empty($options['detecter_presence'])) {
138
+            foreach ($multis as $k => &$multi) {
139
+                $multi['texte'] = $multi['match'][1];
140
+                // extraire les trads du texte
141
+                $multi['trads'] = $this->extraire_trads($multi['texte']);
142
+            }
143
+        }
144
+
145
+        return $multis;
146
+    }
147
+
148
+    /**
149
+     * Traiter les multis d'un texte
150
+     *
151
+     * @uses approcher_langue()
152
+     * @uses lang_typo()
153
+     * @uses code_echappement()
154
+     * @uses echappe_retour()
155
+     *
156
+     * @param string $texte
157
+     * @param array $options
158
+     *   ?string $lang
159
+     *   ?string $lang_defaut
160
+     *   ?bool echappe_span
161
+     *   ?bool appliquer_typo
162
+     * @return string
163
+     */
164
+    public function traiter(string $texte, array $options) {
165
+        if ($texte) {
166
+
167
+            $multis = $this->collecter($texte);
168
+            if (!empty($multis)) {
169
+                $lang = $options['lang'] ?? $GLOBALS['spip_lang'];
170
+                $lang_defaut = $options['lang_defaut'] ?? _LANGUE_PAR_DEFAUT;
171
+                $echappe_span = $options['echappe_span'] ?? false;
172
+                $appliquer_typo = $options['appliquer_typo'] ?? true;
173
+
174
+                if (!function_exists('approcher_langue')) {
175
+                    include_spip('inc/lang');
176
+                }
177
+                if (!function_exists('code_echappement')) {
178
+                    include_spip('inc/texte_mini');
179
+                }
180
+
181
+                $offset_pos = 0;
182
+                foreach ($multis as $m) {
183
+
184
+                    // chercher la version de la langue courante
185
+                    $trads = $m['trads'];
186
+                    if (empty($trads)) {
187
+                        $trad = '';
188
+                    }
189
+                    elseif ($l = approcher_langue($trads, $lang)) {
190
+                        $trad = $trads[$l];
191
+                    } else {
192
+                        if ($lang_defaut == 'aucune') {
193
+                            $trad = '';
194
+                        } else {
195
+                            // langue absente, prendre le fr ou une langue précisée (meme comportement que inc/traduire.php)
196
+                            // ou la premiere dispo
197
+                            if (!$l = approcher_langue($trads, $options['lang_defaut'])) {
198
+                                $l = array_keys($trads);
199
+                                $l = reset($l);
200
+                            }
201
+
202
+                            // mais typographier le texte selon les regles de celle-ci
203
+                            // Attention aux blocs multi sur plusieurs lignes
204
+                            if ($appliquer_typo) {
205
+                                $trad = $trads[$l];
206
+                                $typographie = charger_fonction(lang_typo($l), 'typographie');
207
+                                $trad = $typographie($trad);
208
+
209
+                                // Tester si on echappe en span ou en div
210
+                                // il ne faut pas echapper en div si propre produit un seul paragraphe
211
+                                include_spip('inc/texte');
212
+                                $trad_propre = preg_replace(',(^<p[^>]*>|</p>$),Uims', '', propre($trad));
213
+                                $mode = preg_match(',</?(' . _BALISES_BLOCS . ')[>[:space:]],iS', $trad_propre) ? 'div' : 'span';
214
+                                if ($mode === 'div') {
215
+                                    $trad = rtrim($trad) . "\n\n";
216
+                                }
217
+                                $trad = code_echappement($trad, 'multi', false, $mode);
218
+                                $trad = str_replace("'", '"', inserer_attribut($trad, 'lang', $l));
219
+                                if (lang_dir($l) !== lang_dir($lang)) {
220
+                                    $trad = str_replace("'", '"', inserer_attribut($trad, 'dir', lang_dir($l)));
221
+                                }
222
+                                if (!$echappe_span) {
223
+                                    $trad = echappe_retour($trad, 'multi');
224
+                                }
225
+                            }
226
+                        }
227
+                    }
228
+
229
+                    $texte = substr_replace($texte, $trad, $m['pos'] + $offset_pos, $m['length']);
230
+                    $offset_pos += strlen($trad) - $m['length'];
231
+                }
232
+            }
233
+        }
234
+
235
+        return $texte;
236
+    }
237 237
 
238 238
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -185,8 +185,7 @@
 block discarded – undo
185 185
 					$trads = $m['trads'];
186 186
 					if (empty($trads)) {
187 187
 						$trad = '';
188
-					}
189
-					elseif ($l = approcher_langue($trads, $lang)) {
188
+					} elseif ($l = approcher_langue($trads, $lang)) {
190 189
 						$trad = $trads[$l];
191 190
 					} else {
192 191
 						if ($lang_defaut == 'aucune') {
Please login to merge, or discard this patch.
ecrire/inc/modeles.php 1 patch
Indentation   +12 added lines, -12 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
 /**
@@ -26,16 +26,16 @@  discard block
 block discarded – undo
26 26
  */
27 27
 function traiter_modeles($texte, $doublons = false, $echap = '', string $connect = '', ?Spip\Texte\Collecteur\Liens $collecteurLiens = null, $env = []) {
28 28
 
29
-	include_spip("src/Texte/Collecteur/AbstractCollecteur");
30
-	include_spip("src/Texte/Collecteur/Modeles");
31
-	$collecteurModeles = new Spip\Texte\Collecteur\Modeles();
29
+    include_spip("src/Texte/Collecteur/AbstractCollecteur");
30
+    include_spip("src/Texte/Collecteur/Modeles");
31
+    $collecteurModeles = new Spip\Texte\Collecteur\Modeles();
32 32
 
33
-	$options = [
34
-		'doublons' => $doublons,
35
-		'echap' => $echap,
36
-		'connect' => $connect,
37
-		'collecteurLiens' => $collecteurLiens,
38
-		'env' => $env
39
-	];
40
-	return $collecteurModeles->traiter($texte ?? '', $options);
33
+    $options = [
34
+        'doublons' => $doublons,
35
+        'echap' => $echap,
36
+        'connect' => $connect,
37
+        'collecteurLiens' => $collecteurLiens,
38
+        'env' => $env
39
+    ];
40
+    return $collecteurModeles->traiter($texte ?? '', $options);
41 41
 }
Please login to merge, or discard this patch.
ecrire/inc/liens.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -11,5 +11,5 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
Please login to merge, or discard this patch.